Example #1
0
def rsi_buy(ticker):
    my_list = rh.account.build_holdings()
    if my_list.get(ticker) == None :
        got_it =  False
        close = []
        dfh = rh.get_historicals(ticker,'day','regular') # list of dictionaries # gets the daily candlesticks
        for key in dfh:
            close.append(float(key['close_price']))
    
        data = np.array(close)
        if(len(close) > rsiPeriod):
            rsi_list = list(ti.rsi(data,rsiPeriod))
            print("Latest RSI value: {}".format(rsi_list[len(rsi_list) - 1]))
            print("")
            if rsi_list[len(rsi_list) - 1] <= 31 and not got_it: # sell the stock less than 32
                os.system('python robin_calls.py buy 1 '+ticker) #using the robin_calls module's terminal command from click group
                got_it = True
                
                
                if rsi_list[len(rsi_list) - 1] >= 69 and got_it: # buy the stock greater than 69
                os.system('python robin_calls.py sell 1 '+ticker)
                got_it = False
                
    else:
        close = []
        dfh = rh.get_historicals(ticker,'day','regular') # list of dictionaries
        for key in dfh:
            close.append(float(key['close_price']))
    
        data = np.array(close)
        rsi_list = list((ti.rsi(data,rsiPeriod)))
        print("Ticker: "+ticker)
        print("Latest RSI value: {}".format(rsi_list[len(rsi_list) - 1]))
        print("")
        print("Number of shares: " + my_list.get(ticker).get('quantity'))
        print("")
            

if __name__ == "__main__":
    api = tradeapi.REST(key_id = 'fromAlpacaAPI',secret_key = 'fromAlpacaAPI',base_url = 'https://paper-api.alpaca.markets',api_version = 'v2')
    clock = api.get_clock() # seperate API to check when the market is open
    
    rh.login("email","password",store_session = True)
    rh.cancel_all_stock_orders() #cancels all the orders that may have been remaining from the previous day 
    print("==================================")
    while clock.is_open:
        main()
        time.sleep(20)
    
    for val in rh.account.build_holdings():
        print("Ticker: {}".format(val))
        print("#:{}".format((rh.account.build_holdings()[val]['quantity'][0])))
    """
Example #2
0
async def run():
    while True:
        time_string = time.strftime("%m/%d/%Y, %H:%M:%S", time.localtime())

        # POST TIME
        print("\nGetting historical quotes on {}".format(time_string))

        # This gets the last 60 days including today.
        five_min_day_yahoo = yahoo_finance.get_stock_history(stock_ticker, "5m")

        # Create list of closing prices from RH API
        close_prices = []
        [close_prices.append(float(key['close_price'])) for key in day_year_quotes["results"][0]["historicals"]]

        # Get stock quote
        quote_data = rh.get_quote(stock_ticker)

        # Get latest trade price
        latest_trade_price = get_latest_trading_price(quote_data)

        # Manually insert LATEST TRADE PRICE to CLOSE PRICES to calculate RSI better.
        close_prices.append(float(latest_trade_price))

        # Create Numpy DataFrame
        DAILY_DATA = np.array(close_prices)
        FIVEMIN_DATA = np.array(five_min_day_yahoo)

        # Get stock instrument
        instrument = rh.instruments(stock_ticker)[0]

        # Calculate Indicator
        indicator_period = 3
        rsi = ti.rsi(DAILY_DATA, period=indicator_period)
        rsi_5 = ti.rsi(FIVEMIN_DATA, period=indicator_period)

        trade_logic_data = {"LTP": str(latest_trade_price), 'RSI':rsi, "RSI_5":rsi_5, }

        print("Previous daily RSIs")
        get_list_of_rsi(DAILY_DATA, rsi)
        print("-----------------------")
        print("Previous 5 minute RSIs")
        get_list_of_rsi(FIVEMIN_DATA, rsi_5)

        ## BUYING LOGIC
        robinhood_function.buy_stock(trade_logic_data, instrument, user, rh, quote_data)

        ## SELLING LOGIC
        robinhood_function.sell_stock(trade_logic_data, instrument, user, rh, quote_data)

        # Call this method again every 5 minutes for new price changes
        print()
        print()
        await asyncio.sleep(config.SLEEP)
Example #3
0
 def rsi(self, name='rsi', period=14):
     if len(self.df_ohlc) > period:
         self._add_column_to_ohlc(
             name, ti.rsi(self.df_ohlc.priceclose.values, period))
         return True
     else:
         return False
Example #4
0
def rsi(ticker):
    rsiPeriod = 14
    close = []
    dfh = rh.get_historicals(ticker,'day','regular') # list of dictionaries
    for key in dfh:
        close.append(float(key['close_price']))

    data = np.array(close)
    if(len(close) > rsiPeriod):
        rsi_list = list((ti.rsi(data,rsiPeriod)))
        #print("Ticker: "+ticker)
        #print("Latest RSI value: {}".format(rsi_list[len(rsi_list) - 1]))
        #print("")
        if rsi_list[len(rsi_list) - 1] <= 31:
            #os.system('python robin_calls.py buy 1 '+ticker)
            #got_it = True
            return True
        
        
        if rsi_list[len(rsi_list) - 1] >= 69:
            #os.system('python robin_calls.py sell 1 '+ticker)
            #got_it = False
            return True
    
    return False
Example #5
0
    async def evaluate(self, cryptocurrency, symbol, time_frame, candle_data, candle):
        if candle_data is not None and len(candle_data) > self.period_length:
            rsi_v = tulipy.rsi(candle_data, period=self.period_length)

            if len(rsi_v) and not math.isnan(rsi_v[-1]):
                long_trend = EvaluatorUtil.TrendAnalysis.get_trend(rsi_v, self.long_term_averages)
                short_trend = EvaluatorUtil.TrendAnalysis.get_trend(rsi_v, self.short_term_averages)

                # check if trend change
                if short_trend > 0 > long_trend:
                    # trend changed to up
                    self.set_eval_note(-short_trend)

                elif long_trend > 0 > short_trend:
                    # trend changed to down
                    self.set_eval_note(short_trend)

                # use RSI current value
                last_rsi_value = rsi_v[-1]
                if last_rsi_value > 50:
                    self.set_eval_note(rsi_v[-1] / 200)
                else:
                    self.set_eval_note((rsi_v[-1] - 100) / 200)
                await self.evaluation_completed(cryptocurrency, symbol, time_frame,
                                                eval_time=evaluators_util.get_eval_time(full_candle=candle,
                                                                                        time_frame=time_frame))
                return
        self.eval_note = commons_constants.START_PENDING_EVAL_NOTE
        await self.evaluation_completed(cryptocurrency, symbol, time_frame,
                                        eval_time=evaluators_util.get_eval_time(full_candle=candle,
                                                                                time_frame=time_frame))
    def eval_impl(self):
        period_length = 14
        if len(self.data[PriceIndexes.IND_PRICE_CLOSE.value]) > period_length:
            rsi_v = tulipy.rsi(self.data[PriceIndexes.IND_PRICE_CLOSE.value],
                               period=period_length)

            if len(rsi_v) and not math.isnan(rsi_v[-1]):
                long_trend = TrendAnalysis.get_trend(rsi_v,
                                                     self.long_term_averages)
                short_trend = TrendAnalysis.get_trend(rsi_v,
                                                      self.short_term_averages)

                # check if trend change
                if short_trend > 0 > long_trend:
                    # trend changed to up
                    self.set_eval_note(-short_trend)

                elif long_trend > 0 > short_trend:
                    # trend changed to down
                    self.set_eval_note(short_trend)

                # use RSI current value
                last_rsi_value = rsi_v[-1]
                if last_rsi_value > 50:
                    self.set_eval_note(rsi_v[-1] / 200)
                else:
                    self.set_eval_note((rsi_v[-1] - 100) / 200)
Example #7
0
    async def ohlcv_callback(self, exchange: str, exchange_id: str,
                             symbol: str, time_frame, candle):
        period_length = 14
        candle_data = self.get_symbol_candles(exchange, exchange_id, symbol, time_frame).\
            get_symbol_close_candles(period_length).base
        if candle_data is not None and len(candle_data) > period_length:
            rsi_v = tulipy.rsi(candle_data, period=period_length)

            if len(rsi_v) and not math.isnan(rsi_v[-1]):
                long_trend = TrendAnalysis.get_trend(rsi_v,
                                                     self.long_term_averages)
                short_trend = TrendAnalysis.get_trend(rsi_v,
                                                      self.short_term_averages)

                # check if trend change
                if short_trend > 0 > long_trend:
                    # trend changed to up
                    self.set_eval_note(-short_trend)

                elif long_trend > 0 > short_trend:
                    # trend changed to down
                    self.set_eval_note(short_trend)

                # use RSI current value
                last_rsi_value = rsi_v[-1]
                if last_rsi_value > 50:
                    self.set_eval_note(rsi_v[-1] / 200)
                else:
                    self.set_eval_note((rsi_v[-1] - 100) / 200)
                await self.evaluation_completed(self.cryptocurrency, symbol,
                                                time_frame)
    def get_rsi(self, stock, loadHist=False):
        # this function calculates the RSI value

        self._L.info('\n\n### RSI TREND ANALYSIS (%s for %s) ###' %
                     (stock.name, stock.direction))

        while True:
            if loadHist:
                self.load_historical_data(stock,
                                          interval=gvars.fetchItval['little'])

            # calculations
            rsi = ti.rsi(stock.df.close.values, 14)  # it uses 14 periods
            rsi = rsi[-1]

            if (stock.direction == 'buy') and ((rsi > 50) and (rsi < 80)):
                self._L.info('OK: RSI is %.2f' % rsi)
                return True, rsi

            elif (stock.direction == 'sell') and ((rsi < 50) and (rsi > 20)):
                self._L.info('OK: RSI is %.2f' % rsi)
                return True, rsi

            else:
                self._L.info('RSI: %.0f, waiting (dir: %s)' %
                             (rsi, stock.direction))

                self.timeout += gvars.sleepTimes['RS']
                time.sleep(gvars.sleepTimes['RS'])
                return False
Example #9
0
def run(sc):
    global enteredTrade
    global rsiPeriod
    print("Getting historical quotes")
    # Get 5 minute bar data for Ford stock
    historical_quotes = rh.get_historical_quotes("F", "5minute", "day")
    closePrices = []
    #format close prices for RSI
    currentIndex = 0
    for key in historical_quotes["results"][0]["historicals"]:
        if (currentIndex >=
                len(historical_quotes["results"][0]["historicals"]) -
            (rsiPeriod + 1)):
            closePrices.append(float(key['close_price']))
        currentIndex += 1
    DATA = np.array(closePrices)
    print(len(closePrices))
    if (len(closePrices) > (rsiPeriod)):
        #Calculate RSI
        rsi = ti.rsi(DATA, period=rsiPeriod)
        instrument = rh.instruments("F")[0]
        #If rsi is less than or equal to 30 buy
        if rsi[len(rsi) - 1] <= 30 and not enteredTrade:
            print("Buying RSI is below 30!")
            rh.place_buy_order(instrument, 1)
            enteredTrade = True
        #Sell when RSI reaches 70
        if rsi[len(rsi) - 1] >= 70 and enteredTrade:
            print("Selling RSI is above 70!")
            rh.place_sell_order(instrument, 1)
            enteredTrade = False
        print(rsi)
    #call this method again every 5 minutes for new price changes
    s.enter(300, 1, run, (sc, ))
Example #10
0
def return_ifr(tick,inicio='2014-01-01',fim=date.today(),window=7,colum='ifr'):
    df=wb.DataReader(tick,'yahoo',inicio,fim)
    #retorna o indice de força relativa 
    ifrs = ti.rsi(df['Close'].values,window)
     #Cria o DataFrame com os valores da media movel e usa a data como indice
    ifrs = pd.DataFrame(data = ifrs, index = df.index[(window):], columns=[colum])
    return ifrs
Example #11
0
def performance_indicators(df, period):
    # generate the performance indicators
    data = df.astype('float64')
    rsi = ti.rsi(data['day_close'].values, period)
    rsi = np.insert(rsi, 0, [np.nan for i in range(period)])

    wma = ti.wma(data['day_close'].values, period=period)
    wma = np.insert(wma, 0, [np.nan for i in range(period - 1)])

    vwma = ti.vwma(close=data['day_close'].values,
                   volume=data['day_volume'].values,
                   period=period)
    vwma = np.insert(vwma, 0, [np.nan for i in range(period - 1)])

    willr = ti.willr(high=data['day_high'].values,
                     low=data['day_low'].values,
                     close=data['day_close'].values,
                     period=period)
    willr = np.insert(willr, 0, [np.nan for i in range(period - 1)])

    stddev = ti.stddev(data['day_close'].values, period=period)
    stddev = np.insert(stddev, 0, [np.nan for i in range(period - 1)])

    # set the performance indicator data
    df[f'{period}days_rsi'] = rsi
    df[f'{period}days_wma'] = wma
    df[f'{period}days_vwma'] = vwma
    df[f'{period}days_willr'] = willr
    df[f'{period}days_stddev'] = stddev
    return df
Example #12
0
def test_for_dataset_psar(acc_step, acc_max, file_name,
                          should_display_metric_visuals):
    # load data
    with open(file_name, 'r') as history_json_file:
        history = json.load(history_json_file)

    print('Loaded ' + str(len(history['Data'])) + ' minutes of currency data.')

    # Create the pandas DataFrames for price time-series fields
    price_df = pd.DataFrame(history['Data'])
    price_open = price_df['open'].tolist()
    price_close = price_df['close'].tolist()
    price_high = price_df['high'].tolist()
    price_low = price_df['low'].tolist()

    print('History data frame loaded')

    # Create numpy array
    price_list_np_array = np.array(price_open)

    # Expose info about tulip indicator for
    tulip_util.print_info(ti.rsi)
    tulip_util.print_info(ti.psar)

    # Try out tulip indicator on numpy array
    rsi = ti.rsi(price_list_np_array, 120)

    # high_low = np.array([price_high, price_low], np.int32)
    price_high_np = np.array(price_high)
    price_low_np = np.array(price_low)

    # Run PSAR
    psar = ti.psar(high=price_high_np,
                   low=price_low_np,
                   acceleration_factor_step=acc_step,
                   acceleration_factor_maximum=acc_max)

    # Calculate total potential gains of time-series
    print("Total potential gains: " +
          str(test_util.calculate_potential_gains(price_df)))

    # Run desired test
    # test_metrics_instance = run_test.run_test(60, price_open)
    test_metrics_instance = run_test_psar.run_test(
        price_open, price_high_np, price_low_np, acc_step, acc_max,
        detect_buy_sar.detect_buy_sar, detect_sell_sar.detect_sell_sar)
    # detect_buy_psar_updated.detect_buy_sar_updated,
    # detect_sell_psar_updated.detect_sell_sar_updated)

    # test_metrics_instance = run_test_sequential.run_test_sequential(price_df, acc_step, acc_max)

    if should_display_metric_visuals:
        display_metrics(test_metrics_instance, price_open, psar,
                        should_display_metric_visuals)

    return test_metrics_instance
Example #13
0
 def rsi(self):
     """
     0-30: Oversold Area
     30-70: Neutral Area
     70-100: Overbought Area
     """
     try:
         return rsi(self.data, 9)
     except Exception:
         logging.exception('')
Example #14
0
def test_TA_basics():
    rsi_result = tulipy.rsi(DATA, period=9)
    assert all(74 < v < 86 for v in rsi_result)
    assert len(rsi_result) == 6
    sma_result = tulipy.sma(DATA, period=9)
    assert all(74 < v < 86 for v in sma_result)
    assert len(sma_result) == 7
    bands = tulipy.bbands(DATA, period=9, stddev=2)
    assert all(80 < v < 89 for band in bands for v in band)
    assert len(bands) == 3
Example #15
0
 def stoch_rsi(self, name='stoch_rsi', kp=14, ksp=3, d=3):
     if len(self.df_ohlc) > kp:
         if 'rsi' not in self.df_ohlc.columns:
             self._add_column_to_ohlc(
                 "rsi", ti.rsi(self.df_ohlc.priceclose.values, kp))
         v = self.df_ohlc.rsi.dropna().values
         self._add_column_to_ohlc(name, ti.stoch(v, v, v, kp, ksp, d))
         return True
     else:
         return False
Example #16
0
 def calculate(self, candles):        
     candles_len = len(candles)
     if candles_len < self.period+1:
         return float(0)
     
     val_array = np.array([float(x['ohlc'].close) for x in candles[-(self.period+1):]])
     
     #calculate 
     cur_rsi = ti.rsi (val_array, period=self.period)
     
     return float(cur_rsi[-1])
Example #17
0
 def stoch_rsi(self, name='stoch_rsi', kp=14, ksp=3, d=3):
     try:
         if 'rsi' not in self.df_ohlc.columns:
             self._add_column_to_ohlc(
                 "rsi", ti.rsi(self.df_ohlc.priceclose.values, kp))
         v = self.df_ohlc.rsi.dropna().values
         self._add_column_to_ohlc(name, ti.stoch(v, v, v, kp, ksp, d))
         return True
     except Exception as err:
         print("stoch_rsi error>>>", err.__repr__())
         return False
    def analyse(self):

        close = self.bars[:, 0].copy(order='C').astype('float64')
        if not (close.size - self.parameter > 0):
            raise RuntimeError
        my_result = ti.rsi(close, self.parameter)
        median = np.median(my_result)
        if not np.isnan(median):
            self.calc = float(median)
        else:
            self.logger.warning("Data causes nan. {}".format(close))
        return super(RsiFilter, self).analyse()
Example #19
0
 def _get_rsi_averages(self, symbol_candles, time_frame, include_in_construction):
     # compute the slow and fast RSI average
     candle_data = trading_api.get_symbol_close_candles(symbol_candles, time_frame,
                                                        include_in_construction=include_in_construction)
     if len(candle_data) > self.period_length:
         rsi_v = tulipy.rsi(candle_data, period=self.period_length)
         rsi_v = data_util.drop_nan(rsi_v)
         if len(rsi_v):
             slow_average = numpy.mean(rsi_v[-self.slow_eval_count:])
             fast_average = numpy.mean(rsi_v[-self.fast_eval_count:])
             return slow_average, fast_average, rsi_v
     return None, None, None
 def _get_rsi_averages(self):
     # compute the slow and fast RSI average
     if len(self.data[
             PriceIndexes.IND_PRICE_CLOSE.value]) > self.period_length:
         rsi_v = tulipy.rsi(self.data[PriceIndexes.IND_PRICE_CLOSE.value],
                            period=self.period_length)
         rsi_v = DataUtil.drop_nan(rsi_v)
         if len(rsi_v):
             slow_average = numpy.mean(rsi_v[-self.slow_eval_count:])
             fast_average = numpy.mean(rsi_v[-self.fast_eval_count:])
             return slow_average, fast_average, rsi_v
     return None, None, None
Example #21
0
def run(sc):
    global enteredTrade
    global rsiPeriod
    print("Getting historical quotes")
    # Get 5 minute bar data for Ford stock
    historical_quotes = rh.get_historicals("F", span="month", bounds="regular")
    closePrices = []
    #format close prices for RSI
    currentIndex = 0
    currentSupport = 0
    currentResistance = 0
    for key in historical_quotes["results"][0]["historicals"]:
        if (currentIndex >=
                len(historical_quotes["results"][0]["historicals"]) -
            (rsiPeriod + 1)):
            if (currentIndex >= (rsiPeriod - 1) and datetime.strptime(
                    key['begins_at'], '%Y-%m-%dT%H:%M:%SZ').minute == 0):
                currentSupport = 0
                currentResistance = 0
                print("Resetting support and resistance")
            if (float(key['close_price']) < currentSupport
                    or currentSupport == 0):
                currentSupport = float(key['close_price'])
                print("Current Support is : ")
                print(currentSupport)
            if (float(key['close_price']) > currentResistance):
                currentResistance = float(key['close_price'])
                print("Current Resistance is : ")
                print(currentResistance)
            closePrices.append(float(key['close_price']))
        currentIndex += 1
    DATA = np.array(closePrices)
    if (len(closePrices) > (rsiPeriod)):
        #Calculate RSI
        rsi = ti.rsi(DATA, period=rsiPeriod)
        instrument = rh.instruments("F")[0]
        #If rsi is less than or equal to 30 buy
        if rsi[len(rsi) - 1] <= 30 and float(
                key['close_price']) <= currentSupport and not enteredTrade:
            print("Buying RSI is below 30!")
            rh.place_buy_order(instrument, 1)
            enteredTrade = True
        #Sell when RSI reaches 70
        if rsi[len(rsi) - 1] >= 70 and float(
                key['close_price']
        ) >= currentResistance and currentResistance > 0 and enteredTrade:
            print("Selling RSI is above 70!")
            rh.place_sell_order(instrument, 1)
            enteredTrade = False
        print(rsi)
    #call this method again every 1 minutes for new price changes
    s.enter(60, 1, run, (sc, ))
Example #22
0
def RSI(candlestickperiod, period):
    closeprices = []
    listoftime = []
    EMA = candlestickinfo(22, candlestickperiod)
    for i in range(len(EMA['candles'])):
        if EMA['candles'][i]['complete'] == True:
            if EMA['candles'][i]['time'] not in listoftime:
                closeprices.append(float(EMA['candles'][i]['mid']['c']))
                listoftime.append(EMA['candles'][i]['time'])
    closearray = np.array(closeprices)

    ta = ti.rsi(closearray, period = period)
    return ta
Example #23
0
    def analyse(self):

        close = self.bars[:, 0].copy(order='C').astype('float64')
        if not (close.size - self.parameter > 0):
            raise RuntimeError
        my_result = ti.rsi(close, self.parameter)
        median = np.median(my_result)
        if not np.isnan(median):
            self.calc = float(median)
        else:
            self.logger.warning("Data causes nan. {}".format(close))
        if self.calc >= self.buy:
            return BaseFilter.BUY
        elif self.calc <= self.sell:
            return BaseFilter.SELL

        return BaseFilter.HOLD
Example #24
0
 def execute(self, sc):
     if len(self.closePrices) > self.rsiPeriod:
         # Calculate RSI
         rsi = ti.rsi(self.data, period=self.rsiPeriod)
         instrument = self.rh.instruments("F")[0]
         # If rsi is less than or equal to 30 buy
         if rsi[len(rsi) - 1] <= 30 and not self.enteredPosition:
             print("Buying RSI is below 30!")
             self.rh.place_buy_order(instrument, 1)
             self.enteredPosition = True
         # Sell when RSI reaches 70
         if rsi[len(rsi) - 1] >= 70 and self.enteredPosition:
             print("Selling RSI is above 70!")
             self.rh.place_sell_order(instrument, 1)
             self.enteredPosition = False
         print(rsi)
         # call this method again every 5 minutes for new price changes
     self.s.enter(300, 1, self.execute, (sc, ))
Example #25
0
    def inds(self):

        Indicators = {}

        for i in range(len(self.time)):
            #i/o?
            ''' 2 = High, 3 = Low, 4 = Close, 5 = Volume
            collects the needed market data into one list to push to the indicators'''
            close = self.time[i][4].values.copy(order='C')
            high = self.time[i][2].values.copy(order='C')
            low = self.time[i][3].values.copy(order='C')
            volume = self.time[i][5].values.copy(order='C')
            # !!!This needs to be changed. Each volume of the base time must be indexed up to the slice
            __time = self.time[i][6]

            # these are the indicators currently being used, and recored
            Indicators[i] = {
                'stochrsi': ti.stochrsi(close, 5),
                'rsi': ti.rsi(close, 5),
                # indicators that need to be doublechecked
                'mfi': ti.mfi(high, low, close, volume, 5),
                'sar': ti.psar(high, low, .2, 2),
                'cci': ti.cci(high, low, close, 5),
                'ema': ti.ema(close, 5)
            }
            # this one is good
            Indicators[i]['stoch_k'], Indicators[i]['stoch_d'] = ti.stoch(
                high, low, close, 5, 3, 3)

            # check on this, to see if it functions properly
            Indicators[i]['bbands_lower'], Indicators[i]['bbands_middle'],
            Indicators[i]['bbands_upper'] = ti.bbands(close, 5, 2)

            Indicators[i]['macd'], Indicators[i]['macd_signal'],
            Indicators[i]['macd_histogram'] = ti.macd(close, 12, 26, 9)

            Indicators[i]['time'] = __time
            Indicators[i]['close'] = close
            ''' below changes the length of each array to match the longest one, for a pandas df
             np.nan for the tail of the shorter ones'''
            Indicators[i] = to_pd(Indicator=Indicators[i]).dropna(how='all')
        return Indicators
def strat(pair, quantity, interval):
    global inpos
    while True:
        # get data
        Get_kline(pair, interval)
        closes = Get_kline.closes
        # indicators
        rsi = tulipy.rsi(closes, 14)
        rsiema = tulipy.ema(rsi, 22)
        last_rsi = rsi[-1]
        last_rsiema = rsiema[-1]

        # Buy
        if last_rsi > last_rsiema and last_rsi > 50 and inpos == False:
            if testing == False:
                print(f'Buying {quantity} {pair}')
                price = Get_price(pair)
                order_succeded = Limit_buy(pair, quantity, price)
                if order_succeded:
                    inpos = True
                    print(f'{fg.yellow}sucess{ac.clear}')

        # Sell
        elif inpos and last_rsi < last_rsiema or last_rsi < 50:
            if testing == False:
                print(f'Selling {quantity} {pair}')
                price = Get_price(pair)
                balance = Asset_balance(pair)
                if balance > quantity:
                    order_succeded = Limit_sell(pair, quantity, price)
                if balance < quantity:
                    order_succeded = Limit_sell(pair, balance, price)
                if order_succeded:
                    print(f'{fg.yellow}sucess{ac.clear}')
                    time.sleep(3600)
                    inpos = False

        price = Get_price(pair)
        print(f'{pair}: {round(price, 2)}')
        time.sleep(1)
Example #27
0
def run(sc):
    global enteredTrade
    print("Getting historical quotes")
    # do your stuff
    historical_quotes = rh.get_historical_quotes("F", "5minute", "day")
    closePrices = []
    #format close prices for RSI
    for key in historical_quotes["results"][0]["historicals"]:
        closePrices.append(float(key['close_price']))
    DATA = np.array(closePrices)
    #Calculate RSI
    rsi = ti.rsi(DATA, period=5)
    instrument = rh.instruments("F")[0]
    #If rsi is less than or equal to 30 buy
    if rsi[len(rsi) - 1] <= 30 and not enteredTrade:
        enteredTrade = True
        rh.place_buy_order(instrument, 1)
    #Sell when RSI reaches 70
    if rsi[len(rsi) - 1] >= 70 and enteredTrade:
        rh.place_sell_order(instrument, 1)
        enteredTrade = False
    print(rsi[len(rsi) - 1])
    s.enter(60, 1, run, (sc, ))
Example #28
0
    def __call__(self, Coin):
        CloseValues = np.array(
            [c[3] for c in Coin.Candlesticks[-(self.slow_sma_period + 20):]])

        if CloseValues.shape[0] < self.slow_sma_period:
            return 0

        slow_SMA = ti.sma(CloseValues, period=self.slow_sma_period)[-1]
        fast_SMA = ti.sma(CloseValues, period=self.fast_sma_period)[-1]

        # BEAR TREND;
        if slow_SMA > fast_SMA:
            RSI_period = self.bear_rsi_period
            score_adjust = self.bear_score_adjust
        else:
            RSI_period = self.bull_rsi_period
            score_adjust = self.bull_score_adjust

        Period = max(1, min(RSI_period, CloseValues.shape[0] - 1))

        RSI = ti.rsi(CloseValues, period=Period)

        return max(min(100, RSI[-1] - score_adjust), -100)
Example #29
0
def calculate_rsi(df, period):
    """ Calculates the RSI for the period given"""

    # Tail the data-frame to the needed data
    data = df.tail(period + 1)
    return ti.rsi(data['day_close'].values, period)[0]
Example #30
0
    barsets = api.get_barset(symbol_chunk, 'day', after=date.today().isoformat)

    # loop over keys in barset dictionary
    for symbol in barsets:
        print(f'processing symbol: {symbol}')
        recent_closes = [bar.c for bar in barsets[symbol]]

        ## loop over bar value in dictionary
        for bar in barsets[symbol]:
            stock_id = stock_dict[symbol]

            if len(recent_closes) >= 50 and date.today().isoformat(
            ) == bar.t.date().isoformat():
                sma_20 = tulipy.sma(numpy.array(recent_closes), period=20)[-1]
                sma_50 = tulipy.sma(numpy.array(recent_closes), period=50)[-1]
                rsi_14 = tulipy.rsi(numpy.array(recent_closes), period=14)[-1]
            else:
                sma_20, sma_50, rsi_14 = None, None, None  #tuple assignment
            ## get db stock_id from stock_dict list

            cursor.execute(
                """
                INSERT INTO stock_price (stock_id, date, open, high, low, close, volume, sma_20, sma_50, rsi_14)
                VALUES (?,?,?,?,?,?,?,?,?,?)
            """, (stock_id, bar.t.date(), bar.o, bar.h, bar.l, bar.c, bar.v,
                  sma_20, sma_50, rsi_14))

# #polygon integration requires alpaca upgrade or direct access through polygon api
# minute_bars = api.polygon.historic_agg_v2('Z', 1, 'minute', _from='2020-10-02', to= '2020-10-22')
# for bar in minute_bars:
#     print(bar)