Exemplo n.º 1
0
def set_rsi(data_pd):
    upper_rsi = 80
    lower_rsi = 20

    data_pd['rsi6'] = pd.Series(rsi(data_pd['close'], 6)).fillna(0).tolist()
    data_pd['rsi12'] = pd.Series(rsi(data_pd['close'], 12)).fillna(0).tolist()
    data_pd['rsi24'] = pd.Series(rsi(data_pd['close'], 24)).fillna(0).tolist()

    # 1、超买超卖点位
    high_low_point(data_pd, lower_rsi, upper_rsi)

    # 2、金叉死叉
    cross_point(data_pd)
Exemplo n.º 2
0
def Update():
    print(
        str(dt.datetime.now()) + "	 " + timeframe +
        " Bar Closed - Running Update Function...")

    # Calculate Indicators
    iRSI = rsi(pricedata['bidclose'], rsi_periods)
    iSMA = sma(pricedata['bidclose'], sma_periods)

    # Print Price/Indicators Data
    print("Close Price: " + str(pricedata['bidclose'][len(pricedata) - 1]))
    print("RSI: " + str(iRSI[-1]))
    print("SMA: " + str(iSMA[-1]))

    # Trading Logic

    # Buy Logic, if RSI crosses above lower_rsi, and  close price is above SMA, then BUY
    if crossesOver(iRSI, lower_rsi) and pricedata['bidclose'][-1] > iSMA[-1]:
        # Buy Signal
        if countOpenTrades("B") == 0:
            enter("B")
        if countOpenTrades("S") != 0:
            exit("S")

    # Sell Logic, if RSI crosses under upper_rsi, and close price is below SMA, then SELL
    if crossesUnder(iRSI, upper_rsi) and pricedata['bidclose'][-1] < iSMA[-1]:
        # Sell Signal
        if countOpenTrades("S") == 0:
            enter("S")
        if countOpenTrades("B") != 0:
            exit("B")

    print(
        str(dt.datetime.now()) + "	 " + timeframe +
        " Update Function Completed.\n")
Exemplo n.º 3
0
    def getData(self):
        #get url to data from kraken api
        pair = self.pair
        interval = str(self.interval)
        base = 'https://api.kraken.com'
        endpoint = '/0/public/OHLC'
        params = '?pair=' + pair + '&interval=' + interval
        url = base + endpoint + params
        #download the data
        json_string = requests.get(url)
        dictionary = json.loads(json_string.text)
        dict_len = len(dictionary['result'][pair])
        self.dflength = dict_len
        #creat pandas df
        col_names = ['time', 'open', 'high', 'low', 'close', 'volume', 'sma20', 'sma40', 'rsi', 'obv','hma20']
        df = pd.DataFrame(columns = col_names)

        #creat df cause the import stuff would work
        for x in range(dict_len):
            temp = dictionary['result'][pair][x]
            df = df.append({col_names[0]: temp[0], col_names[1]: temp[1], col_names[2]: temp[2], col_names[3]: temp[3], col_names[4]: temp[4], col_names[5]: temp[5]}, ignore_index=True)

        #turn df into floats
        for col in col_names:
            df[col] = df[col].astype(float)
        #add techinical indicatiors to the df
        df['time'] = [datetime.fromtimestamp(x) for x in df['time']]
        df['sma20'] = sma(df['close'].tolist(), 20)
        df['sma40'] = sma(df['close'].tolist(), 50)
        df['hma20'] = hma(df['close'].tolist(), 200)

        df['rsi'] = rsi(df['close'].tolist(), 10)
        df['obv'] = obv(df['close'].tolist(), df['volume'].tolist())

        return df
Exemplo n.º 4
0
def add_indicators(data, ema_period=[5, 25, 100], rsi_period=[14], prefix=""):
    result = None
    for period in ema_period:
        r_r = ema(data, period)
        df = pd.DataFrame(r_r,
                          index=data.index,
                          columns=[prefix + "_%dema" % period])
        if result is None:
            result = df
        else:
            result = pd.merge(df,
                              result,
                              how='outer',
                              left_index=True,
                              right_index=True)
    for period in rsi_period:
        r_r = rsi(data, period)
        df = pd.DataFrame(r_r,
                          index=data.index,
                          columns=[prefix + "_%drsi" % period])
        result = pd.merge(df,
                          result,
                          how='outer',
                          left_index=True,
                          right_index=True)
    return result
Exemplo n.º 5
0
    def __compute_indicator(self, period, lower, upper):
        try:
            data = self.ohlcv.copy()
            indicator = rsi(data.close, int(period))
            data.loc[:, 'indicator'] = indicator

            return data
        except Exception as e:
            logger.exception(e)
Exemplo n.º 6
0
def Update(currency, rsi_period, upper_rsi, lower_rsi):
    print(
        str(dt.datetime.now()) + "     " + timeframe +
        " Bar Closed - Running Update Function...")

    df = candles(currency)

    # Calculate Indicators
    df["rsi"] = rsi(df['c'], rsi_periods)
    iRSI = rsi(df['c'], rsi_periods)

    # Print Price/Indicators
    print("Close Price: " + str(df['c'][-1]))
    print("RSI: " + str(iRSI[len(iRSI) - 1]))

    # TRADING LOGIC

    # Entry Logic
    # If RSI crosses over lower_rsi, Open Buy Trade
    if crossesOver(iRSI, lower_rsi):
        print("   BUY SIGNAL!")
        print("   Opening Buy Trade...")
        enter("B", currency)
    # If RSI crosses under upper_rsi, Open Sell Trade
    if crossesUnder(iRSI, upper_rsi):
        print("   SELL SIGNAL!")
        print("   Opening Sell Trade...")
        enter("S", currency)

    # Exit Logic
    # If RSI is greater than upper_rsi and we have Buy Trade(s), Close Buy Trade(s)
    if iRSI[len(iRSI) - 1] > upper_rsi and countOpenTrades("B", currency) > 0:
        print("   RSI above " + str(upper_rsi) + ". Closing Buy Trade(s)...")
        exit("B", currency)
    # If RSI is less than than lower_rsi and we have Sell Trade(s), Close Sell Trade(s)
    if iRSI[len(iRSI) - 1] < lower_rsi and countOpenTrades("S", currency) > 0:
        print("   RSI below " + str(lower_rsi) + ". Closing Sell Trade(s)...")
        exit("S", currency)

    print(
        str(dt.datetime.now()) + "     " + timeframe +
        " Update Function Completed.\n")
Exemplo n.º 7
0
def historicData(script, start_dt, end_dt):
    data = pd.DataFrame(
        u.get_ohlc(u.get_instrument_by_symbol('NSE_EQ', script),
                   OHLCInterval.Minute_1,
                   datetime.strptime(start_dt, '%d/%m/%Y').date(),
                   datetime.strptime(end_dt, '%d/%m/%Y').date()))
    data = data.tail(60)
    ##---------SMA CROSSOVER CALCULATION-----------------------------------------##
    data["sma5"] = data.cp.rolling(window=5).mean()
    data["sma50"] = data.cp.rolling(window=50).mean()
    data["difference"] = data["sma5"] - data["sma50"]
    ##-------------------------RSI CALCULATION-----------------------------------##
    data['rsi'] = rsi(data["close"], 14)
    print(data.tail(5))
    return data
def Update():
    print(
        str(dt.datetime.now()) + "	 " + timeframe +
        " Bar Closed - Running Update Function...")

    # Calculate Indicators
    iRSI = rsi(pricedata['bidclose'], rsi_periods)

    # Print Price/Indicators
    print("Close Price: " + str(pricedata['bidclose'][len(pricedata) - 1]))
    print("RSI: " + str(iRSI[len(iRSI) - 1]))

    # TRADING LOGIC

    # Entry Logic
    if isTradingTime():
        # If RSI crosses over lower_rsi, Open Buy Trade
        if crossesOver(iRSI, lower_rsi):
            print("	  BUY SIGNAL!")
            print("	  Opening Buy Trade...")
            enter("B")
        # If RSI crosses under upper_rsi, Open Sell Trade
        if crossesUnder(iRSI, upper_rsi):
            print("	  SELL SIGNAL!")
            print("	  Opening Sell Trade...")
            enter("S")
    else:
        print("	  Is not time to trade. Cannot open new positions.")

    # Exit Logic
    # If RSI is greater than upper_rsi and we have Buy Trade(s), Close Buy Trade(s)
    if iRSI[len(iRSI) - 1] > upper_rsi and countOpenTrades("B") > 0:
        print("	  RSI above " + str(upper_rsi) + ". Closing Buy Trade(s)...")
        exit("B")
    # If RSI is less than than lower_rsi and we have Sell Trade(s), Close Sell Trade(s)
    if iRSI[len(iRSI) - 1] < lower_rsi and countOpenTrades("S") > 0:
        print("	  RSI below " + str(lower_rsi) + ". Closing Sell Trade(s)...")
        exit("S")

    print(
        str(dt.datetime.now()) + "	 " + timeframe +
        " Update Function Completed.\n")
Exemplo n.º 9
0
    def getData(self):
        #get url to data from kraken api
        data = pd.read_csv("Kraken_BTCUSD_1h.csv")

        #creat pandas df
        col_names = [
            'time', 'symbol', 'open', 'high', 'low', 'close', 'volume',
            'volume usd', 'sma20', 'sma40', 'rsi', 'obv'
        ]
        df = pd.DataFrame(data, columns=col_names)
        print df  #turn df into floats
        for col in col_names:
            df[col] = df[col].astype(float)
        #add techinical indicatiors to the df
        #df['time'] = [datetime.fromtimestamp(x) for x in df['time']]
        df['sma20'] = sma(df['close'].tolist(), 20)
        df['sma40'] = sma(df['close'].tolist(), 40)
        df['rsi'] = rsi(df['close'].tolist(), 14)
        df['obv'] = obv(df['close'].tolist(), df['volume'].tolist())

        return df
Exemplo n.º 10
0
 def rsi(self, df):
     period = 14
     if len(df) < period:
         period = len(df) // 2
     data = rsi(df, period)
     return (data)
Exemplo n.º 11
0
def Update():
    global message_text

    global lrsiPosCompra
    global lrsiPosVenta

    global lstoPosSell
    global lstoPosBuy

    global lregrPosSell
    global lregrPosBuy
    message_text = message_text + (
            '\n' + str(dt.datetime.now()) + " " + timeframe + " Bar Closed - Running Update Function..." + symbol)
    # *****************************************************************************
    # # Calcular Indicador RSI

    iRSI = rsi(pricedata['bidclose'], rsi_periods)
    message_text = message_text + '\n' + "RSI: " + str(iRSI[len(iRSI) - 1])
    pricedata_stadistics['RSI'] = iRSI

    # # Lbuy_operacion_rsi = crossesOver(lower_rsi, iRSI)
    # # Lsell_operacion_rsi = crossesUnder(upper_rsi, iRSI)
    Lbuy_operacion_rsi = False
    Lsell_operacion_rsi = False

    if iRSI[len(iRSI) - 1] < lower_rsi:
         message_text = message_text + '\n' + "RSI Posicion Compra: "
         lrsiPosCompra = True
    if lrsiPosCompra:
        if iRSI[len(iRSI) - 1] > lower_rsi:
           lrsiPosCompra = False
           Lbuy_operacion_rsi = True

    if iRSI[len(iRSI) - 1] > upper_rsi:
         message_text = message_text + '\n' + "RSI Posicion Venta: "
         lrsiPosVenta = True
    if lrsiPosVenta:
         if iRSI[len(iRSI) - 1] < upper_rsi:
             lrsiPosVenta = False
             Lsell_operacion_rsi = True

    message_text = message_text + "\n rsi buy:" + str(Lbuy_operacion_rsi)
    message_text = message_text + "\n rsi sell:" + str(Lsell_operacion_rsi)

    # Calcular STO
    # istodata_per_k = per_k(pricedata['bidclose'], data_per_k)
    # istodata_per_d = per_d(pricedata['bidclose'], data_per_d)
    # pricedata_stadistics['istodata_per_k'] = istodata_per_k
    # pricedata_stadistics['istodata_per_d'] = istodata_per_d
    #
    # # lbuy_Operacion_sto = crossesOver(istodata_per_d, lower_sto)
    # # lsell_Operacion_sto = crossesUnder(istodata_per_d, upper_sto)
    #
    # message_text = message_text + '\n' + "STO D: " + str(istodata_per_d[len(istodata_per_d) - 1])
    # lbuy_Operacion_sto = False
    # lsell_Operacion_sto = False
    # if istodata_per_d[len(istodata_per_d) - 1] < lower_sto:
    #     message_text = message_text + '\n' + "STO Posicion Compra: "
    #     lstoPosBuy = True
    # if lstoPosBuy:
    #     if istodata_per_d[len(istodata_per_d) - 1] > lower_sto:
    #         lstoPosBuy = False
    #         lbuy_Operacion_sto = True
    #
    # if istodata_per_d[len(istodata_per_d) - 1] > upper_sto:
    #     message_text = message_text + '\n' + "STO Posicion Venta: "
    #     lstoPosSell = True
    #
    # if lstoPosSell:
    #     if istodata_per_d[len(istodata_per_d) - 1] < upper_sto:
    #         lstoPosSell = False
    #         lsell_Operacion_sto = True
    #
    # message_text = message_text + "\n sto buy:" + str(lbuy_Operacion_sto)
    # message_text = message_text + "\n sto sell:" + str(lsell_Operacion_sto)
    #
    #
    #
    #
    for index, row in pricedata_stadistics.iterrows():
         pricedata_stadistics.loc[index, 'upper_rsi'] = upper_rsi
         pricedata_stadistics.loc[index, 'lower_rsi'] = lower_rsi
    #     pricedata_stadistics.loc[index, 'lower_sto'] = lower_sto
    #     pricedata_stadistics.loc[index, 'upper_sto'] = upper_sto
         pricedata_stadistics.loc[index, 'RSI_middle'] = 50

    # *********************************************************************
    # ** Estadistica General - Regresion Lineal Simple 1
    # *********************************************************************
    pricedata_stadistics.iloc[0:0]
    pricedata_stadistics['bidclose'] = pricedata['bidclose'].values
    pricedata_stadistics['bidopen'] = pricedata['bidopen'].values
    pricedata_stadistics['x'] = np.arange(len(pricedata_stadistics))



    # ************* Calcular la poscion Relativa Y
    for index, row in pricedata_stadistics.iterrows():
        pricedata_stadistics.loc[index, 'y'] = int(
            '{:.5f}'.format((pricedata_stadistics.loc[index, 'bidclose'])).replace('.', ''))

    max_value = max(np.array(pricedata_stadistics['y'].values))
    min_value = min(np.array(pricedata_stadistics['y'].values))
    for index, row in pricedata_stadistics.iterrows():
        value = pricedata_stadistics.loc[index, 'y'] - min_value
        NewPricePosition = ((value * 100) / max_value) * 100
        pricedata_stadistics.loc[index, 'y'] = NewPricePosition

    # ***********  Calcular la poscion Relativa X
    max_value = max(np.array(pricedata_stadistics['x'].values))
    min_value = min(np.array(pricedata_stadistics['x'].values))
    for index, row in pricedata_stadistics.iterrows():
        value = pricedata_stadistics.loc[index, 'x'] - min_value
        NewPricePosition = ((value * 100) / max_value)
        pricedata_stadistics.loc[index, 'x'] = NewPricePosition

    # ***********************************************************
    # *  EMA'S================
    # ***********************************************************
    iFastSMA = sma(pricedata_stadistics['y'], fast_sma_periods)
    iSlowSMA = sma(pricedata_stadistics['y'], slow_sma_periods)
    # iTooSlowSMA = sma(pricedata_stadistics['y'], too_slow_sma_periods)
    pricedata_stadistics['emaFast'] = iFastSMA
    pricedata_stadistics['emaSlow'] = iSlowSMA
    ##pricedata_stadistics['emaTooSlow'] = iTooSlowSMA

    lbuy_sma = crossesOver(iFastSMA, iSlowSMA)
    lsell_sma = crossesUnder(iFastSMA, iSlowSMA)

    message_text = message_text + "\n sma buy:" + str(lbuy_sma)
    message_text = message_text + "\n sma sell:" + str(lsell_sma)

    # ***********************************************************
    # *  Regresion al precio de cierre las velas ================
    # ***********************************************************
    regresionLineal_xx = np.array(pricedata_stadistics['x'].values)
    regresionLineal_yy = np.array(pricedata_stadistics['y'].values)
    regresionLineal_bb = regresionlineal2.estimate_b0_b1(regresionLineal_xx, regresionLineal_yy)
    y_pred_sup = regresionLineal_bb[0] + regresionLineal_bb[1] * regresionLineal_xx
    pricedata_stadistics['y_pred'] = y_pred_sup

    # Recreacion del Eje X para Presentacion de la Regresion.
    for index, row in pricedata_stadistics.iterrows():
        pricedata_stadistics.loc[index, 'x_pred'] = pricedata_stadistics.loc[0, 'y_pred']

    # Calculo de Angulo
    vx = np.array(pricedata_stadistics['x'])
    vy = np.array(pricedata_stadistics['y_pred'])

    x1 = vx[0]
    y1 = vy[0]

    x2 = vx[-1]
    y2 = vy[-1]

    x = x2 - x1
    y = y2 - y1

    angle = math.atan2(y, x) * (180.0 / math.pi)
    angle = round(angle, 2)
    # angle2 = np.rad2deg(np.arctan2(vy[-1] - vy[0], vx[-1] - vx[0]))

    message_text = message_text + "\nAngulo: " + str(angle)
    #
    # pricedata_stadistics['y_bidhigh'] = pricedata['bidhigh'].values
    # pricedata_stadistics['y_bidlow'] = pricedata['bidlow'].values
    # # ************* Calcular la poscion Relativa Y
    # for index, row in pricedata_stadistics.iterrows():
    #     pricedata_stadistics.loc[index, 'y_bidhigh'] = int(
    #         '{:.5f}'.format((pricedata_stadistics.loc[index, 'y_bidhigh'])).replace('.', ''))
    #     pricedata_stadistics.loc[index, 'y_bidlow'] = int(
    #         '{:.5f}'.format((pricedata_stadistics.loc[index, 'y_bidlow'])).replace('.', ''))
    #
    # max_value = max(np.array(pricedata_stadistics['y_bidhigh'].values))
    # min_value = min(np.array(pricedata_stadistics['y_bidhigh'].values))
    # for index, row in pricedata_stadistics.iterrows():
    #     value = pricedata_stadistics.loc[index, 'y_bidhigh'] - min_value
    #     NewPricePosition = ((value * 100) / max_value) * 100
    #     pricedata_stadistics.loc[index, 'y_bidhigh'] = NewPricePosition
    #
    # max_value = max(np.array(pricedata_stadistics['y_bidlow'].values))
    # min_value = min(np.array(pricedata_stadistics['y_bidlow'].values))
    # for index, row in pricedata_stadistics.iterrows():
    #     value = pricedata_stadistics.loc[index, 'y_bidlow'] - min_value
    #     NewPricePosition = ((value * 100) / max_value) * 100
    #     pricedata_stadistics.loc[index, 'y_bidlow'] = NewPricePosition
    #
    # # Regresion al precio mas alto velas ======================
    # regresionLineal_xx = np.array(pricedata_stadistics['x'].values)
    # regresionLineal_yy = np.array(pricedata_stadistics['y_bidhigh'].values)
    # regresionLineal_bb = regresionlineal2.estimate_b0_b1(regresionLineal_xx, regresionLineal_yy)
    #
    # y_pred_sup = regresionLineal_bb[0] + regresionLineal_bb[1] * regresionLineal_xx
    # pricedata_stadistics['y_pred_bidhigh'] = y_pred_sup
    #
    # # Regresion al precio de cierre las velas ======================
    # regresionLineal_xx = np.array(pricedata_stadistics['x'].values)
    # regresionLineal_yy = np.array(pricedata_stadistics['y_bidlow'].values)
    # regresionLineal_bb = regresionlineal2.estimate_b0_b1(regresionLineal_xx, regresionLineal_yy)
    # y_pred_sup = regresionLineal_bb[0] + regresionLineal_bb[1] * regresionLineal_xx
    # pricedata_stadistics['y_pred_bidlow'] = y_pred_sup

    # # *********************************************************************
    # # ** Estadistica General - Regresion Lineal
    # # *********************************************************************
    # pricedata_stadistics_sup.iloc[0:0]
    # pricedata_stadistics_sup['bidclose'] = pricedata_sup['bidclose'].values
    # pricedata_stadistics_sup['bidhigh'] = pricedata_sup['bidhigh'].values
    # pricedata_stadistics_sup['bidlow'] = pricedata_sup['bidlow'].values
    # pricedata_stadistics_sup['rowid'] = np.arange(len(pricedata_stadistics_sup))
    #
    # # *************BIDHIGH
    # # ************* Calcular la poscion Relativa Y
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     pricedata_stadistics_sup.loc[index, 'Y_bidhigh'] = int(
    #         '{:.5f}'.format((pricedata_stadistics_sup.loc[index, 'bidhigh'])).replace('.', ''))
    #
    # max_value = max(np.array(pricedata_stadistics_sup['Y_bidhigh'].values))
    # min_value = min(np.array(pricedata_stadistics_sup['Y_bidhigh'].values))
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     value = pricedata_stadistics_sup.loc[index, 'Y_bidhigh'] - min_value
    #     NewPricePosition = (value * 100) / max_value
    #     pricedata_stadistics_sup.loc[index, 'Y_bidhigh'] = NewPricePosition
    #
    # # ***********  Calcular la poscion Relativa X
    # max_value = max(np.array(pricedata_stadistics_sup['rowid'].values))
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     value = pricedata_stadistics_sup.loc[index, 'rowid']
    #     NewPricePosition = (value * 100) / max_value
    #     pricedata_stadistics_sup.loc[index, 'X_bidhigh'] = NewPricePosition
    #
    # # Regresion al precio mas Alto de las velas ======================
    # regresionLineal_xx_sup = np.array(pricedata_stadistics_sup['X_bidhigh'].values)
    # regresionLineal_yy_sup = np.array(pricedata_stadistics_sup['Y_bidhigh'].values)
    # regresionLineal_bb_sup = regresionlineal2.estimate_b0_b1(regresionLineal_xx_sup, regresionLineal_yy_sup)
    # y_pred_sup = regresionLineal_bb_sup[0] + regresionLineal_bb_sup[1] * regresionLineal_xx_sup
    #
    # pricedata_stadistics_sup['y_pred_bidhigh'] = y_pred_sup
    # pricedata_stadistics_sup['x_pred_bidhigh'] = regresionLineal_xx_sup
    #
    #
    #

    #
    # # *************BIDLOW
    # # ************* Calcular la poscion Relativa Y
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     pricedata_stadistics_sup.loc[index, 'Y_bidlow'] = int(
    #         '{:.5f}'.format((pricedata_stadistics_sup.loc[index, 'bidlow'])).replace('.', ''))
    #
    # max_value = max(np.array(pricedata_stadistics_sup['Y_bidlow'].values))
    # min_value = min(np.array(pricedata_stadistics_sup['Y_bidlow'].values))
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     value = pricedata_stadistics_sup.loc[index, 'Y_bidlow'] - min_value
    #     NewPricePosition = (value * 100) / max_value
    #     pricedata_stadistics_sup.loc[index, 'Y_bidlow'] = NewPricePosition
    #
    # # ***********  Calcular la poscion Relativa X
    # max_value = max(np.array(pricedata_stadistics_sup['rowid'].values))
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     value = pricedata_stadistics_sup.loc[index, 'rowid']
    #     NewPricePosition = (value * 100) / max_value
    #     pricedata_stadistics_sup.loc[index, 'X_bidlow'] = NewPricePosition
    #
    #
    #
    #
    # # Regresion al precio mas Alto de las velas ======================
    # regresionLineal_xx_sup = np.array(pricedata_stadistics_sup['X_bidlow'].values)
    # regresionLineal_yy_sup = np.array(pricedata_stadistics_sup['Y_bidhigh'].values)
    # regresionLineal_bb_sup = regresionlineal2.estimate_b0_b1(regresionLineal_xx_sup, regresionLineal_yy_sup)
    # y_pred_sup = regresionLineal_bb_sup[0] + regresionLineal_bb_sup[1] * regresionLineal_xx_sup
    #
    # pricedata_stadistics_sup['y_pred_bidlow'] = y_pred_sup
    # pricedata_stadistics_sup['x_pred_bidlow'] = regresionLineal_xx_sup
    #
    #
    #

    #
    #
    # # create circle
    # c = plt.Circle((x1, y1), radius=10, color='red', alpha=.3)
    # plt.gca().add_artist(c)
    #
    # #plt.text(x1, y1, str(round(angle, 2)) + ' °')

    # # Regresion al mas bajo de las velas ======================
    # regresionLineal_xx_sup = np.array(pricedata_stadistics_sup['rowid'].tail(numberofregresion_sup).values)
    # regresionLineal_yy_sup = np.array(pricedata_stadistics_sup['bidlow'].tail(numberofregresion_sup).values)
    # regresionLineal_bb_sup = regresionlineal2.estimate_b0_b1(regresionLineal_xx_sup, regresionLineal_yy_sup)
    # y_pred_sup = regresionLineal_bb_sup[0] + regresionLineal_bb_sup[1] * regresionLineal_xx_sup
    #
    # numberRegx = len(pricedata_stadistics_sup) - numberofregresion_sup
    # posreg = 0
    # for index, row in pricedata_stadistics_sup.iterrows():
    #     if numberRegx <= pricedata_stadistics_sup.loc[index, 'rowid']:
    #         pricedata_stadistics_sup.loc[index, 'y_pred_bidlow'] = y_pred_sup[posreg]
    #         posreg = posreg + 1
    #
    # # *********************************************************************
    # # ***    Proyecion de Precios * Se puede Mejorar con Ciclo
    # # *********************************************************************
    # lv_index_1 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 1]['date']
    # lv_rowid_1 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 1]['rowid']
    # lv_y_pred_askhigh_1 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 1]['y_pred_bidhigh']
    # lv_y_pred_asklow_1 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 1]['y_pred_bidlow']
    #
    # lv_index_2 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 2]['date']
    # lv_rowid_2 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 2]['rowid']
    # lv_y_pred_askhigh_2 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 2]['y_pred_bidhigh']
    # lv_y_pred_asklow_2 = pricedata_stadistics_sup.iloc[len(pricedata_stadistics_sup) - 2]['y_pred_bidlow']
    #
    # lv_index_base = lv_index_1 - lv_index_2
    # lv_rowid_base = lv_rowid_1 - lv_rowid_2
    # lv_y_pred_askhigh_base = lv_y_pred_askhigh_1 - lv_y_pred_askhigh_2
    # lv_y_pred_asklow_base = lv_y_pred_asklow_1 - lv_y_pred_asklow_2
    #
    # pricedata_stadistics_proyeccion.iloc[0:0]
    # for proyect_times in range(2):
    #     pricedata_stadistics_proyeccion.loc[lv_index_1] = pd.Series(
    #         {'rowid': lv_rowid_1,
    #          'y_pred_bidhigh': lv_y_pred_askhigh_1,
    #          'y_pred_bidlow': lv_y_pred_asklow_1
    #          })
    #     lv_index_1 = lv_index_1 + lv_index_base
    #     lv_rowid_1 = lv_rowid_1 + lv_rowid_base
    #     lv_y_pred_askhigh_1 = lv_y_pred_askhigh_1 + lv_y_pred_askhigh_base
    #     lv_y_pred_asklow_1 = lv_y_pred_asklow_1 + lv_y_pred_asklow_base
    #
    # pricedata_stadistics_proyeccion_tenden.iloc[0:0]
    # for proyect_times in range(3):
    #     pricedata_stadistics_proyeccion_tenden.loc[lv_index_1] = pd.Series(
    #         {'rowid': lv_rowid_1,
    #          'y_pred_bidhigh': lv_y_pred_askhigh_1,
    #          'y_pred_bidlow': lv_y_pred_asklow_1
    #          })
    #     lv_index_1 = lv_index_1 + lv_index_base
    #     lv_rowid_1 = lv_rowid_1 + lv_rowid_base
    #     lv_y_pred_askhigh_1 = lv_y_pred_askhigh_1 + lv_y_pred_askhigh_base
    #     lv_y_pred_asklow_1 = lv_y_pred_asklow_1 + lv_y_pred_asklow_base
    #

    # Calculamos La tendencia con los valores de de la proyection las velas mas altas y mas bajas.
    lv_Tendency = "Lateral"
    if pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] < \
            pricedata_stadistics.iloc[1]['y_pred'] and \
            pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] < \
            pricedata_stadistics.iloc[1]['y_pred']:
        lv_Tendency = "Bajista"
    elif pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] > \
            pricedata_stadistics.iloc[1]['y_pred'] and \
            pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] > \
            pricedata_stadistics.iloc[1]['y_pred']:
        lv_Tendency = "Alcista"
    message_text = message_text + "\nTendencia Regresion Lineal: " + lv_Tendency

    # lv_posicion_venta = False
    # lv_posicion_compra = False
    #
    # if lv_Tendency == "Bajista" and (pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['emaTooSlow'] >
    #                                  pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y']):
    #     lv_posicion_venta = True
    #     lv_posicion_compra = False
    #
    # elif lv_Tendency == "Alcista" and (pricedata_stadistics.iloc[len(pricedata_stadistics) - 1][
    #                                        'emaTooSlow'] < pricedata_stadistics.iloc[len(pricedata_stadistics) - 1][
    #                                        'y']):
    #     lv_posicion_venta = False
    #     lv_posicion_compra = True
    #
    # message_text = message_text + "\nPosicion de Venta: " + str(lv_posicion_venta) + " Posicion de Compra: " + str(
    #     lv_posicion_compra)

    # # Print Price/Indicators
    # print("Close Price: " + str(pricedata['bidclose'][len(pricedata) - 1]))
    # # print("Fast SMA: " + str(iFastSMA[len(iFastSMA) - 1]))
    # # print("Slow SMA: " + str(iSlowSMA[len(iSlowSMA) - 1]))

    lregr_Operacion_buy = False
    lregr_Operacion_sell = False
    if pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] > pricedata_stadistics.loc[0, 'y_pred']:
        message_text = message_text + '\n' + "  - > Angulo Posicion Venta: "
        lregrPosSell = True

    if lregrPosSell:
        if pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] < pricedata_stadistics.loc[0, 'y_pred']:
            lregrPosSell = False
            lregr_Operacion_sell = True


    if pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] < pricedata_stadistics.loc[0, 'y_pred']:
        message_text = message_text + '\n' + "  - > Angulo Posicion Compra: "
        lregrPosBuy = True

    if lregrPosBuy:
        if pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] > pricedata_stadistics.loc[0, 'y_pred']:
            lregrPosBuy = False
            lregr_Operacion_buy = True



    message_text = message_text + "\n Regresion  buy:" + str(lregrPosBuy)  + " Operacion:" + str(lregr_Operacion_buy)
    message_text = message_text + "\n Regresion  sell:" + str(lregrPosSell) + " Operacion:" + str(lregr_Operacion_sell)


    # # TRADING LOGIC
    #
    if Lbuy_operacion_rsi or (crossesOver(iFastSMA, iSlowSMA) and angle >= angulo_plus):  # or lbuy_sma or Lbuy_operacion_rsi) and angle >= angulo_plus:
        # if (lbuy_Operacion_sto) and angle >= angulo_plus:# or lbuy_sma or Lbuy_operacion_rsi) and angle >= angulo_plus:
        # if crossesOver(iFastSMA, iSlowSMA) and angle >= angulo_plus:
        # if crossesOver(iFastSMA, iSlowSMA) and lv_posicion_compra and angle >= angulo_plus:
        # if Lbuy_operacion_rsi and angle >= angulo_plus:
        message_text = message_text + "\n	  BUY SIGNAL!"
        if countOpenTrades("S") > 0:
            message_text = message_text + "\n	  Closing Sell Trade(s)..."
            exit("S")
        if countOpenTrades("B") == 0:
            message_text = message_text + "\n	  Opening Buy Trade..."
            enter("B")

    if Lsell_operacion_rsi or (crossesUnder(iFastSMA, iSlowSMA) and angle <= angulo_minus):  # or lsell_sma or Lsell_operacion_rsi) and :
        # if (lsell_Operacion_sto) and angle <= angulo_minus:# or lsell_sma or Lsell_operacion_rsi) and :
        # if crossesUnder(iFastSMA, iSlowSMA) and angle <= angulo_minus:
        # if crossesUnder(iFastSMA, iSlowSMA) and lv_posicion_venta and angle <= angulo_minus:
        # if Lsell_ris and angle <= angulo_minus:
        message_text = message_text + "\n	  SELL SIGNAL!"
        if countOpenTrades("B") > 0:
            message_text = message_text + "\n	  Closing Buy Trade(s)..."
            exit("B")
        if countOpenTrades("S") == 0:
            message_text = message_text + "\n	  Opening Sell Trade..."
            enter("S")

    message_text = message_text + "\n" + str(
        dt.datetime.now()) + " " + timeframe + " Update Function Completed.========= \n"
    print(message_text)
    message_text = ''
Exemplo n.º 12
0
def screen():
    client = Client("api-key", "api-secret", {"verify": False, "timeout": 20})
    positiveCoin = get_positive_coin.coin

    bollCoin = []
    for m in positiveCoin:
        candles = client.get_klines(symbol=m,
                                    interval=client.KLINE_INTERVAL_15MINUTE)
        close = []
        for n in candles:
            close.append(float(n[4]))
        pb = pbb(close, 20, 2.0, 2.0)
        if pb[-1] < 10:
            bollCoin.append(m)

    macdCoin = []
    for m in bollCoin:
        candles = client.get_klines(symbol=m,
                                    interval=client.KLINE_INTERVAL_5MINUTE)
        close = []
        for n in candles:
            close.append(float(n[4]))
        mac = macd(close, 12, 26)
        macs = macds(mac)
        mach = macdh(mac, macs)
        if mach[-1] > 0 and (macs[-1] - macs[-2]) < 0 and (mac[-1] -
                                                           mac[-2]) > 0:
            macdCoin.append(m)

    rsiCoin = []
    for m in macdCoin:
        candles = client.get_klines(symbol=m,
                                    interval=client.KLINE_INTERVAL_15MINUTE)
        close = []
        for n in candles:
            close.append(float(n[4]))
        rs = rsi(close, 14)
        if rs[-1] < 30:
            rsiCoin.append(m)
    buyingCoin = ''
    maxDemandRatio = 0
    for m in rsiCoin:
        depth = client.get_order_book(symbol=m)
        buyingVol = 0
        sellingVol = 0
        for n in depth['bids'][0:20]:
            buyingVol = buyingVol + float(n[1])
        for n in depth['asks'][0:20]:
            sellingVol = sellingVol + float(n[1])
        demandRatio = buyingVol / sellingVol
        print(demandRatio)
        print(maxDemandRatio)
        if demandRatio > maxDemandRatio:
            maxDemandRatio = demandRatio
            buyingCoin = m

    if maxDemandRatio < 1.5:
        buyingCoin = ''

    print(bollCoin)
    print(macdCoin)
    print(rsiCoin)
    print(buyingCoin)
    return buyingCoin
Exemplo n.º 13
0
def Update():
    global pricedata_stadistics, operacionventa, operacioncompra

    print(str(dt.datetime.now()) + " " + timeframe + " Vela Formada - Analizando -  Running Update Function...")

    pricedata_stadistics['index'] = pricedata['bidclose'].index
    pricedata_stadistics['bidclose'] = pricedata['bidclose'].values
    pricedata_stadistics['bidhigh'] = pricedata['bidhigh'].values
    pricedata_stadistics['askclose'] = pricedata['askclose'].values
    pricedata_stadistics['askhigh'] = pricedata['askhigh'].values
    pricedata_stadistics['asklow'] = pricedata['asklow'].values
    pricedata_stadistics['askclose'] = pricedata['askclose'].values
    pricedata_stadistics['bidlow'] = pricedata['bidlow'].values

    pricedata_stadistics['tickqty'] = pricedata['tickqty'].values

    # Calculate Indicators
    iFastSMA = sma(pricedata['bidclose'], fast_sma_periods)
    iSlowSMA = sma(pricedata['bidclose'], slow_sma_periods)

    pricedata_stadistics['emaFast'] = iFastSMA
    pricedata_stadistics['emaSlow'] = iSlowSMA

    # Adds a "n_high" column with max value of previous 14 periods
    pricedata_stadistics['n_high'] = pricedata_stadistics['bidhigh'].rolling(stoK).max()
    # Adds an "n_low" column with min value of previous 14 periods
    pricedata_stadistics['n_low'] = pricedata_stadistics['bidlow'].rolling(stoK).min()
    # Uses the min/max values to calculate the %k (as a percentage)
    pricedata_stadistics['per_k'] = (pricedata_stadistics['bidclose'] - pricedata_stadistics['n_low']) * 100 / (
            pricedata_stadistics['n_high'] - pricedata_stadistics['n_low'])
    # Uses the %k to calculates a SMA over the past 3 values of %k
    pricedata_stadistics['per_d'] = pricedata_stadistics['per_k'].rolling(stoD).mean()

    # data_per_k = per_k(pricedata['bidclose'], stoK)
    # data_per_d = per_d(pricedata['bidclose'], stoD)

    data_per_k = pricedata_stadistics['per_k']
    data_per_d = pricedata_stadistics['per_d']
    # pricedata_stadistics['per_k'] = data_per_k
    # pricedata_stadistics['per_d'] = data_per_d

    # Calcular Indicador
    iRSI = rsi(pricedata_stadistics['bidclose'], 15)
    print("RSI: " + str(iRSI[len(iRSI) - 1]))

    for index, row in pricedata_stadistics.iterrows():
        pricedata_stadistics.loc[index, 'lower_sto'] = 20
        pricedata_stadistics.loc[index, 'upper_sto'] = 80
        pricedata_stadistics.loc[index, 'macdline0'] = 0.00

    # ***********************************************************
    # *  Regresion al precio de cierre las velas ================
    # ***********************************************************
    pricedata_stadistics['x'] = np.arange(len(pricedata_stadistics))
    # ************* Calcular la poscion Relativa Y
    for index, row in pricedata_stadistics.iterrows():
        pricedata_stadistics.loc[index, 'y'] = int(
            '{:.5f}'.format((pricedata_stadistics.loc[index, 'bidclose'])).replace('.', ''))

    max_value = max(np.array(pricedata_stadistics['y'].values))
    min_value = min(np.array(pricedata_stadistics['y'].values))
    for index, row in pricedata_stadistics.iterrows():
        value = pricedata_stadistics.loc[index, 'y'] - min_value
        NewPricePosition = ((value * 100) / max_value) * 100
        pricedata_stadistics.loc[index, 'y'] = NewPricePosition

    # ***********  Calcular la poscion Relativa X
    max_value = max(np.array(pricedata_stadistics['x'].values))
    min_value = min(np.array(pricedata_stadistics['x'].values))
    for index, row in pricedata_stadistics.iterrows():
        value = pricedata_stadistics.loc[index, 'x'] - min_value
        NewPricePosition = ((value * 100) / max_value)
        pricedata_stadistics.loc[index, 'x'] = NewPricePosition

    regresionLineal_xx = np.array(pricedata_stadistics['x'].values)
    regresionLineal_yy = np.array(pricedata_stadistics['y'].values)

    regresionLineal_bb = regresionlineal2.estimate_b0_b1(regresionLineal_xx, regresionLineal_yy)
    y_pred_sup = regresionLineal_bb[0] + regresionLineal_bb[1] * regresionLineal_xx
    pricedata_stadistics['y_pred'] = y_pred_sup

    if pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] < \
            pricedata_stadistics.iloc[1]['y_pred'] and \
            pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] < \
            pricedata_stadistics.iloc[1]['y_pred']:
        lv_Tendency = "Bajista"
    elif pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] > \
            pricedata_stadistics.iloc[1]['y_pred'] and \
            pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['y_pred'] > \
            pricedata_stadistics.iloc[1]['y_pred']:
        lv_Tendency = "Alcista"

    # MACD        ########################################################################
    exp1 = pricedata_stadistics['bidclose'].ewm(span=macdFast, adjust=False).mean()
    exp2 = pricedata_stadistics['bidclose'].ewm(span=macdSlow, adjust=False).mean()
    macd = exp1 - exp2
    pricedata_stadistics['macd'] = pricedata_stadistics.index.map(macd)
    pricedata_stadistics['signal'] = pd.DataFrame(
        pricedata_stadistics['macd'].ewm(span=macdSmooth, adjust=False).mean())
    pricedata_stadistics['hist'] = pd.DataFrame(pricedata_stadistics['macd'] - pricedata_stadistics['signal'])

    # Imprimir Precio/Indicador
    # print("Precio Cierre: " + str(pricedata['bidclose'][len(pricedata) - 1]))

    # print("Tendencia Regresion Lineal: " + lv_Tendency)
    lv_signal = pricedata_stadistics.iloc[len(pricedata_stadistics) - 1]['signal']
    print("MACD Signal: " + str(lv_signal) + " SubValuacion:  " + str(macdsub) + " SobreValuacion:  " + str(macduper))
    print("STO D" + str(data_per_d[len(data_per_d) - 1]))

    if iRSI[len(iRSI) - 1] <= 40 and crossesOver(data_per_d,
                                                 pricedata_stadistics['lower_sto']) and lv_signal <= macdsub:
        print("	 SEÑAL DE COMPRA ! \n")
        print('''        
              __,_,
              [_|_/ 
               //
             _//    __
            (_|)   |@@|
             \ \__ \--/ __
              \o__|----|  |   __
                  \ }{ /\ )_ / _\_
                  /\__/\ \__O (__
                 (--/\--)    \__/
                 _)(  )(_
                `---''---`
            ''')
        print("	 SEÑAL DE COMPRA ! \n")
        if countOpenTrades("S") > 0:
            print("	  Cerrando Ventas Abiertas...\n")
            exit("S")
        print("	  Abrir Operacion de Compra...\n")
        if countOpenTrades("B") == 0:
            enter("B")
            operacioncompra = True

    # Verifica el Cruce del SMA para Abajo.
    # if crossesUnder(data_per_d, 0.80):
    # if crossesUnder(pricedata_stadistics['signal'], 0.0004):
    if iRSI[len(iRSI) - 1] >= 60 and crossesUnder(data_per_d, pricedata_stadistics['upper_sto']) and lv_signal >= macduper:
        print("	  SEÑAL DE VENTA ! \n")
        print('''
               __
           _  |@@|
          / \ \--/ __
          ) O|----|  |   __
         / / \ }{ /\ )_ / _\_
         )/  /\__/\ \__O (__
        |/  (--/\--)    \__/
        /   _)(  )(_
           `---''---`

        ''')
        print("	  SEÑAL DE VENTA ! \n")
        if countOpenTrades("B") > 0:
            print("	  Cerrando Operacion de Compras...\n")
            exit("B")
        print("	  Abrir Operacion de Venta...\n")
        if countOpenTrades("S") == 0:
            enter("S")
            operacionventa = True

    # Cerrar Ventas #########################################
    if operacionventa and crossesOver(data_per_d, pricedata_stadistics['lower_sto']):
        if countOpenTrades("S") > 0:
            print("	  Cerrando Ventas Abiertas...\n")
            operacionventa = False
            exit("S")

    # Cerrar Compras #########################################
    if operacioncompra and crossesUnder(data_per_d, pricedata_stadistics['upper_sto']):
        if countOpenTrades("B") > 0:
            print("	  Cerrando Compras Abiertas...\n")
            operacioncompra = False
            exit("B")
    print(str(dt.datetime.now()) + " " + timeframe + " Verificacion Realizada.\n")
def Update():

    print(str(dt.datetime.now()) + "     " + timeframe + " Vela Cerrada - Corriendo Funcion de Actualizacion...")

    # Calcular Indicador
    iRSI = rsi(pricedata['bidclose'], rsi_periods)

    # Print Price/Indicators
    print("Precio de Cierre: " + str(pricedata['bidclose'][len(pricedata) - 1]))
    print("RSI: " + str(iRSI[len(iRSI) - 1]))

    # si RSI cruza el lower_rsi, Abrir Operacion de Trade
    if crossesOver(iRSI, lower_rsi):
        print("	 SEÑAL DE COMPRA ! \n")
        print('''        
                     __,_,
                     [_|_/ 
                      //
                    _//    __
                   (_|)   |@@|
                    \ \__ \--/ __
                     \o__|----|  |   __
                         \ }{ /\ )_ / _\_
                         /\__/\ \__O (__
                        (--/\--)    \__/
                        _)(  )(_
                       `---''---`
                   ''')
        print("	 SEÑAL DE COMPRA ! \n")
        enter("B")
    # If RSI crosses under upper_rsi, Open Sell Trade
    if crossesUnder(iRSI, upper_rsi):
        print("	  SEÑAL DE VENTA ! \n")
        print('''
                     __
                 _  |@@|
                / \ \--/ __
                ) O|----|  |   __
               / / \ }{ /\ )_ / _\_
               )/  /\__/\ \__O (__
              |/  (--/\--)    \__/
              /   _)(  )(_
                 `---''---`

              ''')
        print("	  SEÑAL DE VENTA ! \n")
        enter("S")


    # Logica de Cierre
    # If RSI is superior than upper_rsi y hay una operacion de compra cierra las operaciones
    if iRSI[len(iRSI) - 1] > upper_rsi and countOpenTrades("B") > 0:
        print("   RSI above " + str(upper_rsi) + ". Closing Buy Trade(s)...")
        exit("B")

    # If RSI is inferior que lower_rsi y tenemos una peracion de venta cierre todas las operaciones de venta.
    if iRSI[len(iRSI) - 1] < lower_rsi and countOpenTrades("S") > 0:
        print("   RSI below " + str(lower_rsi) + ". Closing Sell Trade(s)...")
        exit("S")

    print(str(dt.datetime.now()) + "     " + timeframe + " Actualizacion Completada.\n")
Exemplo n.º 15
0
            if stream1[len(stream1) - 2] > stream2[len(stream2) - 2]:
                return False
            elif stream1[len(stream1) - 2] < stream2[len(stream2) - 2]:
                return True
            else:
                x = 2
                while stream1[len(stream1) - x] == stream2[len(stream2) - x]:
                    x = x + 1
                if stream1[len(stream1) - x] < stream2[len(stream2) - x]:
                    return True
                else:
                    return False


df = candles("EUR_USD")
df["rsi"] = rsi(df['c'], rsi_periods)


# Returns true if stream1 crossed under stream2 in most recent candle, stream2 can be integer/float or data array
def crossesUnder(stream1, stream2):
    # If stream2 is an int or float, check if stream1 has crossed under that fixed number
    if isinstance(stream2, int) or isinstance(stream2, float):
        if stream1[len(stream1) - 1] >= stream2:
            return False
        else:
            if stream1[len(stream1) - 2] < stream2:
                return False
            elif stream1[len(stream1) - 2] > stream2:
                return True
            else:
                x = 2
Exemplo n.º 16
0
 def get_analysis(self, data):
     return rsi(data, self.params['period'])[-1]
    def Update(self):

        self.logMessages = self.logMessages + "\n" + (
            str(dt.datetime.now()) + " " + self.timeframe +
            " Vela Formada - Analizando -  Running Update Function...")

        self.pricedata_stadistics['index'] = self.pricedata['bidclose'].index
        self.pricedata_stadistics['bidclose'] = self.pricedata[
            'bidclose'].values
        self.pricedata_stadistics['bidhigh'] = self.pricedata['bidhigh'].values
        self.pricedata_stadistics['askclose'] = self.pricedata[
            'askclose'].values
        self.pricedata_stadistics['askhigh'] = self.pricedata['askhigh'].values
        self.pricedata_stadistics['asklow'] = self.pricedata['asklow'].values
        self.pricedata_stadistics['askclose'] = self.pricedata[
            'askclose'].values
        self.pricedata_stadistics['bidlow'] = self.pricedata['bidlow'].values
        self.pricedata_stadistics['tickqty'] = self.pricedata['tickqty'].values

        # Calculate Indicators
        iFastSMA = sma(self.pricedata['bidclose'], self.fast_sma_periods)
        iSlowSMA = sma(self.pricedata['bidclose'], self.slow_sma_periods)
        self.pricedata_stadistics['emaFast'] = iFastSMA
        self.pricedata_stadistics['emaSlow'] = iSlowSMA

        # Adds a "n_high" column with max value of previous 14 periods
        self.pricedata_stadistics['n_high'] = self.pricedata_stadistics[
            'bidhigh'].rolling(self.stoK).max()
        # Adds an "n_low" column with min value of previous 14 periods
        self.pricedata_stadistics['n_low'] = self.pricedata_stadistics[
            'bidlow'].rolling(self.stoK).min()
        # Uses the min/max values to calculate the %k (as a percentage)

        self.pricedata_stadistics['per_k'] = \
            (
                    (self.pricedata_stadistics['bidclose'] - self.pricedata_stadistics['n_low']) / \
                    (self.pricedata_stadistics['n_high'] - self.pricedata_stadistics['n_low'])
            ) * 100

        # Uses the %k to calculates a SMA over the past 3 values of %k
        self.pricedata_stadistics['per_d'] = self.pricedata_stadistics[
            'per_k'].rolling(self.stoD).mean()

        # data_per_k = per_k(pricedata['bidclose'], stoK)
        # data_per_d = per_d(pricedata['bidclose'], stoD)

        data_per_k = self.pricedata_stadistics['per_k']
        data_per_d = self.pricedata_stadistics['per_d']
        # pricedata_stadistics['per_k'] = data_per_k
        # pricedata_stadistics['per_d'] = data_per_d
        # self.pricedata_stadistics.loc[index, 'lower_sto'] = 20
        # self.pricedata_stadistics.loc[index, 'upper_sto'] = 80

        self.logMessages = self.logMessages + "\n" + (
            "STO K " + str(data_per_k[len(data_per_k) - 1]))
        self.logMessages = self.logMessages + "\n" + (
            "STO D " + str(data_per_d[len(data_per_d) - 1]))

        # Calcular Indicador
        iRSI = rsi(self.pricedata_stadistics['bidclose'], 15)
        self.logMessages = self.logMessages + "\n" + ("RSI: " +
                                                      str(iRSI[len(iRSI) - 1]))

        for index, row in self.pricedata_stadistics.iterrows():
            self.pricedata_stadistics.loc[index, 'lower_sto'] = 20
            self.pricedata_stadistics.loc[index, 'upper_sto'] = 80
            self.pricedata_stadistics.loc[index, 'macdline0'] = 0.00
            self.pricedata_stadistics.loc[index, 'macdsub'] = self.macdsub
            self.pricedata_stadistics.loc[index, 'macdupper'] = self.macduper

        # ***********************************************************
        # *  Regresion al precio de cierre las velas ================
        # ***********************************************************
        self.pricedata_stadistics['x'] = np.arange(
            len(self.pricedata_stadistics))

        # ************* Calcular la poscion Relativa Y
        for index, row in self.pricedata_stadistics.iterrows():
            self.pricedata_stadistics.loc[index, 'y'] = int('{:.5f}'.format(
                (self.pricedata_stadistics.loc[index,
                                               'bidclose'])).replace('.', ''))
        max_value = max(np.array(self.pricedata_stadistics['y'].values))
        min_value = min(np.array(self.pricedata_stadistics['y'].values))
        for index, row in self.pricedata_stadistics.iterrows():
            value = self.pricedata_stadistics.loc[index, 'y'] - min_value
            NewPricePosition = ((value * 100) / max_value) * 100
            self.pricedata_stadistics.loc[index, 'y'] = NewPricePosition

        # ***********  Calcular la poscion Relativa X
        max_value = max(np.array(self.pricedata_stadistics['x'].values))
        min_value = min(np.array(self.pricedata_stadistics['x'].values))
        for index, row in self.pricedata_stadistics.iterrows():
            value = self.pricedata_stadistics.loc[index, 'x'] - min_value
            NewPricePosition = ((value * 100) / max_value)
            self.pricedata_stadistics.loc[index, 'x'] = NewPricePosition

        regresionLineal_xx = np.array(self.pricedata_stadistics['x'].values)
        regresionLineal_yy = np.array(self.pricedata_stadistics['y'].values)

        regresionLineal_bb = regresionlineal2.estimate_b0_b1(
            regresionLineal_xx, regresionLineal_yy)
        y_pred_sup = regresionLineal_bb[
            0] + regresionLineal_bb[1] * regresionLineal_xx
        self.pricedata_stadistics['y_pred'] = y_pred_sup

        if self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['y_pred'] < \
                self.pricedata_stadistics.iloc[1]['y_pred'] and \
                self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['y_pred'] < \
                self.pricedata_stadistics.iloc[1]['y_pred']:
            lv_Tendency = "Bajista"
        elif self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['y_pred'] > \
                self.pricedata_stadistics.iloc[1]['y_pred'] and \
                self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['y_pred'] > \
                self.pricedata_stadistics.iloc[1]['y_pred']:
            lv_Tendency = "Alcista"

        # MACD        ########################################################################
        exp1 = self.pricedata_stadistics['bidclose'].ewm(span=self.macdFast,
                                                         adjust=False).mean()
        exp2 = self.pricedata_stadistics['bidclose'].ewm(span=self.macdSlow,
                                                         adjust=False).mean()
        macd = exp1 - exp2
        self.pricedata_stadistics[
            'macd'] = self.pricedata_stadistics.index.map(macd)
        self.pricedata_stadistics['signal'] = pd.DataFrame(
            self.pricedata_stadistics['macd'].ewm(span=self.macdSmooth,
                                                  adjust=False).mean())
        self.pricedata_stadistics['hist'] = pd.DataFrame(
            self.pricedata_stadistics['macd'] -
            self.pricedata_stadistics['signal'])

        # Imprimir Precio/Indicador
        # self.logMessages = self.logMessages + "\n" + ("Precio Cierre: " + str(pricedata['bidclose'][len(pricedata) - 1]))

        # self.logMessages = self.logMessages + "\n" + ("Tendencia Regresion Lineal: " + lv_Tendency)
        lv_signal = self.pricedata_stadistics.iloc[
            len(self.pricedata_stadistics) - 1]['signal']
        self.logMessages = self.logMessages + "\n" + (
            "MACD Signal: " + str(lv_signal) + " SubValuacion:  " +
            str(self.macdsub) + " SobreValuacion:  " + str(self.macduper))

        self.logMessages = self.logMessages + "\n" + ("RSI " +
                                                      str(iRSI[len(iRSI) - 1]))

        # data_per_d['lower_sto']
        # if self.crossesOver(data_per_k, data_per_d) and lv_signal <= self.macdsub and \
        #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['signal'] > \
        #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['macd']:

        # if self.crossesOver(data_per_k, data_per_d) and lv_signal <= self.macdsub and \
        #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['signal'] > \
        #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['macd']:

        # if self.crossesOver(data_per_k, data_per_d) and data_per_d[len(data_per_d) - 1] <= 20 and \
        #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['bidclose'] > iFastSMA[
        #    len(iFastSMA) - 1]:

        if self.crossesOver(self.pricedata_stadistics['y'],
                            self.pricedata_stadistics['y_pred']
                            ) and lv_Tendency == "Alcista":
            self.logMessages = self.logMessages + "\n" + "	 SEÑAL DE COMPRA ! \n"
            self.logMessages = self.logMessages + "\n" + ('''        
                  __,_,
                  [_|_/ 
                   //
                 _//    __
                (_|)   |@@|
                 \ \__ \--/ __
                  \o__|----|  |   __
                      \ }{ /\ )_ / _\_
                      /\__/\ \__O (__
                     (--/\--)    \__/
                     _)(  )(_
                    `---''---`
                ''')
            self.logMessages = self.logMessages + "\n" + "	 SEÑAL DE COMPRA !"
            if self.countOpenTrades("S") > 0:
                self.logMessages = self.logMessages + "\n" + "	  Cerrando Ventas Abiertas..."
                self.exit("S")
            self.logMessages = self.logMessages + "\n" + "	  Abrir Operacion de Compra..."
            if self.countOpenTrades("B") == 0:
                self.enter("B")
                # playsound("file_example_MP3_700KB.mp3")
                self.operacioncompra = True

        # Verifica el Cruce del SMA para Abajo.
        if self.crossesUnder(self.pricedata_stadistics['y'],
                             self.pricedata_stadistics['y_pred']
                             ) and lv_Tendency == "Bajista":
            # if crossesUnder(pricedata_stadistics['signal'], 0.0004):
            # if self.crossesUnder(data_per_k, data_per_d) and lv_signal >= self.macduper and \
            #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['signal'] < \
            #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['macd']:

            # if self.crossesUnder(data_per_k, data_per_d) and data_per_d[len(data_per_d) - 1] >= 80 and \
            #        self.pricedata_stadistics.iloc[len(self.pricedata_stadistics) - 1]['bidclose'] < iFastSMA[
            #    len(iFastSMA) - 1]:
            self.logMessages = self.logMessages + "\n" + "	  SEÑAL DE VENTA ! \n"
            self.logMessages = self.logMessages + "\n" + ('''
                   __
               _  |@@|
              / \ \--/ __
              ) O|----|  |   __
             / / \ }{ /\ )_ / _\_
             )/  /\__/\ \__O (__
            |/  (--/\--)    \__/
            /   _)(  )(_
               `---''---`

            ''')
            self.logMessages = self.logMessages + "\n" + "	  SEÑAL DE VENTA ! "
            if self.countOpenTrades("B") > 0:
                self.logMessages = self.logMessages + "\n" + "	  Cerrando Operacion de Compras..."
                self.exit("B")
            self.logMessages = self.logMessages + "\n" + "	  Abrir Operacion de Venta..."
            if self.countOpenTrades("S") == 0:
                self.enter("S")
                # playsound("file_example_MP3_700KB.mp3")
                self.operacionventa = True

        self.logMessages = self.logMessages + "\n" + (
            str(dt.datetime.now()) + " " + self.timeframe + "Verificacion "
            "Realizada.\n")
Exemplo n.º 18
0
def relative_strength_index(data, period):
    return rsi(data, period)