def run(self, df):
        rsi_indicator = RSIIndicator(df["close"], 14)
        df["RSI"] = rsi_indicator.rsi()  # added a column with RSI osscilator

        res = []
        current_stock = 0
        lim = 100
        for i in range(len(df)):
            frame = df.iloc[i]
            d = {}
            d["timestamp"] = frame["timestamp"]
            #             print("fram rsi ",frame['RSI'])
            if frame["RSI"] <= self.oversold:
                d["actions"] = "buy"
                d["quantity"] = lim  # np.random.randint(0,lim,1)[0]
                current_stock += d["quantity"]

            elif frame["RSI"] >= self.overbought and current_stock > lim:
                d["actions"] = "sell"
                d["quantity"] = lim  # np.random.randint(,current_stock,1)[0]
                current_stock -= d["quantity"]

            else:
                continue
            res.append(d)

        return res
Exemple #2
0
def ta_rsi(df):
    """
    Relative Strenght Index
    :param df: pandas dataframe
    :return: pandas dataframe
    """
    temp_df = df.copy()
    # temp = RSIIndicator(close=df["Close"], window=mc["rsi_wind"])
    temp = RSIIndicator(close=df["Close"])
    temp_df["ta_rsi"] = temp.rsi()
    return temp_df
 def get_Stoch_RSI_Indicator(self, period=14, smooth=[3, 3], col='Close', fillna=False):
     """
     get Stoch RSI Indicator
     """
     rsi = RSIIndicator(close=self.df[col], n=period, fillna=fillna).rsi()
     stochrsi = (rsi - rsi.rolling(period).min()) / (rsi.rolling(period).max() - rsi.rolling(period).min())
     stochrsi_K = stochrsi.rolling(smooth[0]).mean()
     stochrsi_D = stochrsi_K.rolling(smooth[1]).mean()
     self.df['Stoch_RSI'] = stochrsi * 100
     self.df['Stoch_RSI_K'] = stochrsi_K * 100
     self.df['Stoch_RSI_D'] = stochrsi_D * 100
     return self.df
Exemple #4
0
    def get_signal(self, stock):
        rsi_bars = self.wb.get_bars(stock, interval=self.time_period, extendTrading=0, count=14)

        # Initialize RSI
        rsi = RSIIndicator(close=rsi_bars['close'], window=20, fillna=True)
        rsi_series = rsi.rsi()
        current_rsi = rsi_series[13]

        # Make conclusions from data
        if current_rsi <= 30:
            return 1
        elif current_rsi >= 70:
            return -1
        else:
            return 0
Exemple #5
0
    def acceptCandle(self, candle):
        '''
        accepts a candle and updates current state of strategy to determine buy/sell
        '''
        self.addCandle(candle)

        rsi = RSIIndicator(self.candleDf['C'])

        prevRsi = rsi.rsi().iloc[-2]
        currentRsi = rsi.rsi().iloc[-1]

        if currentRsi >= self.oversold and prevRsi < self.oversold:
            self.buy(0.05 * self.capital)
        elif currentRsi <= self.overbought and prevRsi > self.overbought:
            self.sell()
def get_indicators(df):
    """
        Add set of technical indicators to the dataframe, return original data frame with new features
    """
    feature_df = df.copy()
    feature_df['RSI'] = RSIIndicator(close=df[CLOSE]).rsi()
    feature_df['Stochastic'] = StochasticOscillator(high=df[HIGH],
                                                    low=df[LOW],
                                                    close=df[CLOSE]).stoch()
    feature_df['Stochastic_signal'] = StochasticOscillator(
        high=df[HIGH], low=df[LOW], close=df[CLOSE]).stoch_signal()
    feature_df['ADI'] = AccDistIndexIndicator(
        high=df[HIGH], low=df[LOW], close=df[CLOSE],
        volume=df[VOLUME]).acc_dist_index()
    feature_df['OBV'] = OnBalanceVolumeIndicator(
        close=df[CLOSE], volume=df[VOLUME]).on_balance_volume()
    feature_df['ATR'] = AverageTrueRange(high=df[HIGH],
                                         low=df[LOW],
                                         close=df[CLOSE]).average_true_range()
    feature_df['ADX'] = ADXIndicator(high=df[HIGH],
                                     low=df[LOW],
                                     close=df[CLOSE]).adx()
    feature_df['ADX_pos'] = ADXIndicator(high=df[HIGH],
                                         low=df[LOW],
                                         close=df[CLOSE]).adx_pos()
    feature_df['ADX_neg'] = ADXIndicator(high=df[HIGH],
                                         low=df[LOW],
                                         close=df[CLOSE]).adx_neg()
    feature_df['MACD'] = MACD(close=df[CLOSE]).macd()
    feature_df['MACD_diff'] = MACD(close=df[CLOSE]).macd_diff()
    feature_df['MACD_signal'] = MACD(close=df[CLOSE]).macd_signal()
    return feature_df
Exemple #7
0
def get_rsi(config, company):
    close_prices = company.prices
    dataframe = company.technical_indicators
    rsi_time_period = 20

    rsi_indicator = RSIIndicator(close_prices, rsi_time_period)
    dataframe['RSI'] = rsi_indicator.rsi()

    low_rsi = 40
    high_rsi = 70

    generate_buy_sell_signals(
        lambda x, dataframe: dataframe['RSI'].values[x] < low_rsi,
        lambda x, dataframe: dataframe['RSI'].values[x] > high_rsi, dataframe,
        'RSI')

    return dataframe
Exemple #8
0
    def stock_scan(ticker_set,name, comp_op, rsi_threshold,enddate, plot_chart=False):
        ''' A tool to scan stocks using RSI. 
        Checks for oversold/overbought conditions. 
        Written by Vinod Mathew Sebastian'''
        dataset = []
        newList = []
        dataset = ticker_set.split(" ")
        if comp_op == "greater_than":
            checking_state_message_0 = 'Overbought?'
            checking_state_message_1 = 'over'
        if comp_op == "less_than":
            checking_state_message_0 = 'Oversold?'
            checking_state_message_1 = 'below'
 # Program Logic               
        message = False
        for stock in dataset:
            data1 = data_for_chart[stock]
            data2 = data1['Adj Close']
            rsii = RSIIndicator(close=data2, window=20, fillna = True)                    
            rs = rsii.rsi()
            rsplt = mpf.make_addplot(rs,panel=1)
            if comp_op == "greater_than":
                condition = rs[enddate]>threshold
            elif comp_op == "less_than":
                condition = rs[enddate]<threshold
            if condition:
                newList.append(stock)
                if plot_chart:
                    fig, axes = mpf.plot(data1, type='candle', volume=True,addplot=rsplt, returnfig=True, main_panel=0,volume_panel=2,panel_ratios=(6,2,1))
                    axes[0].legend("")
                    axes[0].set_title(stock)
                    st.write(fig)
                    if not message:
                        st.write("If you do not like to view the chart(s), change Plot Chart = False in the left pane ")
                        message = True;
                    
        if (newList):
            st.subheader("{} Stocks: RSI {} {}".format(checking_state_message_0, checking_state_message_1, threshold))
            for ech in newList:
                st.write(ech)
            if not plot_chart:
                st.write("If you like to view the chart(s), change Plot Chart = True in the left pane ")
        else:
            st.write("No {} stocks matching your criteria: RSI {} {}".format(name,checking_state_message_1, threshold))

        newList.clear()
Exemple #9
0
 def calculate_ta(self):
     self.data['rsi'] = RSIIndicator(close=self.data["close"], n=14).rsi()
     self.data["ema_8"] = EMAIndicator(close=self.data["close"],
                                       n=8).ema_indicator()
     self.data["ema_21"] = EMAIndicator(close=self.data["close"],
                                        n=21).ema_indicator()
     self.data["ema_55"] = EMAIndicator(close=self.data["close"],
                                        n=55).ema_indicator()
Exemple #10
0
    def fit(self, df: DataFrame):
        rsi = RSIIndicator(df["Close"], n=self.rsi_n, fillna=False).rsi().fillna(method='ffill').fillna(value=0)
        rsi_ema = EMAIndicator(close=rsi, n=self.ema_n).ema_indicator().fillna(method='ffill').fillna(value=0)

        rsi[:self.ema_n - 1] = 0

        args = df[["Open", "Close"]].join(rsi).join(rsi_ema)

        super().apply_choose(args)
        return super().fit(df)
Exemple #11
0
def RSIndex(close, window):
    # Getting values of Relative Strength Index from the `ta` module
    RSI = RSIIndicator(close=close, window=int(window), fillna=False)
    RSI = RSI.rsi().dropna()

    # Creating DataFrame
    df = pd.DataFrame()

    # Adding all the required columns to the DataFrame
    df['Close'] = close
    df['RSI'] = RSI
    df['Positions'] = 0

    # Analysing market conditions from RSI value
    df.loc[df['RSI'] <= 35, 'Positions'] = 1
    df.loc[(df['RSI'] > 35) & (df['RSI'] < 65), 'Positions'] = 0
    df.loc[df['RSI'] >= 65, 'Positions'] = -1

    return df['Close'], df['Positions']
Exemple #12
0
def spef(symbol,start_date,end_date):
    data = yf.download(symbol, start=start_date, end=end_date)
    df = pd.DataFrame(data)

    RSI = RSIIndicator(close=df['Close'])
    df["RSI"] = RSI.rsi()

    Stochk = stochrsi_k(close=df['Close'])
    df["Stochk"] = Stochk

    MACD = md(close=df['Close'])
    df["MACD_diff"] = MACD.macd_diff()

    AvgTru = atr(high=df['High'],low=df['Low'],close=df['Close'],n=7)
    df["ATR"] = AvgTru.average_true_range()

    df["Signal"] = ""

    df['20sma'] = df['Close'].rolling(window=20).mean()
    df['stddev'] = df['Close'].rolling(window=20).std()
    df['lower_band'] = df['20sma'] - (2 * df['stddev'])
    df['upper_band'] = df['20sma'] + (2 * df['stddev'])

    df['TR'] = abs(df['High'] - df['Low'])
    df['ATR'] = df['TR'].rolling(window=20).mean()

    df['lower_keltner'] = df['20sma'] - (df['ATR'] * 1.5)
    df['upper_keltner'] = df['20sma'] + (df['ATR'] * 1.5)

    def in_squeeze(df):
        return df['lower_band'] > df['lower_keltner'] and df['upper_band'] < df['upper_keltner']

    df['squeeze_on'] = df.apply(in_squeeze, axis=1)       

    for i in range(0,len(df)):
        if df["RSI"].iloc[i] > 50 and df["Stochk"][i] > 50 and df["MACD_diff"][i] > 0:
            df["Signal"][i] = "Buy"
        elif df["RSI"].iloc[i] < 50 and df["Stochk"][i] < 50 and df["MACD_diff"][i] < 0:
            df["Signal"][i] = "Sell"
        else:
            df["Signal"][i] = "Neutral"

    return df
Exemple #13
0
    def get_indicators(self, rsi_n=14, ema_n=12):
        indicator_rsi = RSIIndicator(close=self.chart.close,
                                     n=int(rsi_n),
                                     fillna=False).rsi()
        indicator_rsi_ema = EMAIndicator(close=indicator_rsi,
                                         n=int(ema_n)).ema_indicator()

        indicator_rsi[:int(ema_n) - 1] = 0

        return indicator_rsi, indicator_rsi_ema.fillna(0)
    def acceptCandle(self, candle):
        '''
        accepts a candle and updates current state of strategy to determine buy/sell
        '''
        self.addCandle(candle)

        macd = MACD(self.candleDf['C'], 20, 6, 5)
        rsi = RSIIndicator(self.candleDf['C'], 8)

        prevRsi = rsi.rsi().iloc[-2]
        currentRsi = rsi.rsi().iloc[-1]

        # print(macd.macd().iloc[-1], macd.macd_signal().iloc[-1], macd.macd_diff().iloc[-1], macd.macd().iloc[-1] - macd.macd_signal().iloc()[-1])

        if macd.macd_diff().iloc[-1] >= 0 and macd.macd_diff().iloc[-2] < 0\
            and currentRsi >= self.oversold and prevRsi < self.oversold:
            self.buy(0.05 * self.capital)
        elif macd.macd_diff().iloc[-1] <= 0 and macd.macd_diff().iloc[-2] > 0\
            and currentRsi <= self.overbought and prevRsi > self.overbought:
            self.sell()
Exemple #15
0
def run(ticker):

    signal_is_sent = check_signal_is_sent(ticker)

    if (not signal_is_sent):

        tf_1hour = get_candles(ticker)
        rsi_1hour = RSIIndicator(close=tf_1hour.close).rsi()
        bolinger_1hour = BollingerBands(close=tf_1hour.close)

        condition_short = rsi_1min[-1] >= 80 and rsi_5min[-1] >= 80
        condition_long = rsi_1min[-1] <= 20 and rsi_5min[-1] <= 20

        # Trade size depends on STOP_LOSS_THRESH. MT5 limitations.
        STOP_LOSS_THRESH = (
            open_close_hour_dif_mean[ticker]
        )
        trade_size = calculate_trade_size(
            STOP_LOSS_THRESH, tf_1min.close[-1]
        ) / ticker_info[ticker]['min_lot']
        trade_size = round(trade_size)

        cur_time = str(datetime.now().time())
        if condition_short:
            sl = round(
                tf_1min.close[-1] + STOP_LOSS_THRESH * tf_1min.close[-1],
                ticker_info[ticker]['price_digits']
            )
            tp = round(
                tf_1min.close[-1] - STOP_LOSS_THRESH * tf_1min.close[-1],
                ticker_info[ticker]['price_digits']
            )
            print('\n', cur_time, ticker, ': SHORT', str(trade_size), tf_1min.close[-1], sl, tp, '\n')
            messsage = ' '.join(
                [cur_time, ticker, 'SHORT', str(trade_size), str(sl), str(tp)]
            )
            send_message(messsage)
            set_signal_is_sent_flag(ticker)
        elif condition_long:
            sl = round(
                tf_1min.close[-1] - STOP_LOSS_THRESH * tf_1min.close[-1],
                ticker_info[ticker]['price_digits']
            )
            tp = round(
                tf_1min.close[-1] + STOP_LOSS_THRESH * tf_1min.close[-1],
                ticker_info[ticker]['price_digits']
            )
            print('\n', cur_time, ticker, ': LONG', str(trade_size), tf_1min.close[-1], sl, tp, '\n')
            messsage = ' '.join(
                [cur_time, ticker, 'LONG', str(trade_size), str(sl), str(tp)]
            )
            send_message(messsage)
            set_signal_is_sent_flag(ticker)
Exemple #16
0
 def action(self, indicator):
     # Derive the action based on past data
     # action: 1 means buy, -1 means sell, 0 means do nothing
     close = indicator['c']
     indicator['momentum_rsi'] = RSIIndicator(close=close).rsi()
     indicator['momentum_rsi_prev'] = indicator['momentum_rsi'].shift(1)
     
     # If 69 -> 70: Sell, If 30 -> 29: Buy
     indicator['sell'] = ((indicator['momentum_rsi_prev'] < self.parameters['rsi70']) & \
                          (indicator['momentum_rsi'] >= self.parameters['rsi70'])).astype(int)
     indicator['buy'] = ((indicator['momentum_rsi_prev'] >= self.parameters['rsi30']) & \
                         (indicator['momentum_rsi'] < self.parameters['rsi30'])).astype(int)
     indicator['action'] = indicator['buy'] - indicator['sell']
Exemple #17
0
    def add_indicators(self,data):
        warnings.filterwarnings("ignore",category=RuntimeWarning)
        # SMA n =20
        data['ma'] = SMAIndicator(data['Close'],20).sma_indicator()
        data['rsi'] = RSIIndicator(data['Close'],14).rsi()
        data['macd'] = MACD(data['Close'],26,12,9).macd()
        data['macd_signal'] = MACD(data['Close'],26,12,9).macd_signal()
        data['macd_hist'] = MACD(data['Close'],26,12,9).macd_diff()
        data['adx'] = ADXIndicator(data['High'],data['Low'],data['Close'],14).adx()        
        data['adx_neg'] = ADXIndicator(data['High'],data['Low'],data['Close'],14).adx_neg()
        data['adx_pos'] = ADXIndicator(data['High'],data['Low'],data['Close'],14).adx_pos()

        return data
Exemple #18
0
    def get_symbol(self, symbol, main, sub):
        #-----------------------
        # Assign class variables
        self.symbol = symbol
        self.main = self.parse_query_main(main)
        self.sub = self.parse_query_sub(sub)
        self.df = yfinance.download(symbol,
                                    start=today - timedelta(weeks=52),
                                    end=today)
        self.chart = ChartCls(self.df, intSub=len(self.sub))

        #------------
        # Build chart
        if 'rsi' in sub:
            taRsi = RSIIndicator(close=self.df["Close"])
            dfRsi = pd.concat([taRsi.rsi()], axis=1)
            self.chart.BuildOscillator(sub.index('rsi'),
                                       dfRsi,
                                       intUpper=70,
                                       intLower=30,
                                       strTitle='RSI')
        self.plot_chart()
def add_momentum_indicators(data: pd.DataFrame) -> pd.DataFrame:
    """Adds the momentum indicators.

    Parameters
    ----------
    data : pd.DataFrame
        A dataframe with daily stock values. Must include: open, high,
        low, close and volume. It should also be sorted in a descending
        manner.

    Returns
    -------
    pd.DataFrame
        The input dataframe with the indicators added.
    """
    rsi = RSIIndicator(data['close'])
    stoch_osc = StochasticOscillator(data['high'], data['low'], data['close'])

    data.loc[:, 'rsi'] = rsi.rsi()
    data.loc[:, 'stoch_osc'] = stoch_osc.stoch()
    data.loc[:, 'stoch_osc_signal'] = stoch_osc.stoch_signal()

    return data
Exemple #20
0
    def PlotRSI(stock_ticker, close, window):
        # Getting values of Relative Strength Index from the `ta` module
        RSI = RSIIndicator(close=close, window=int(window), fillna=False)

        # Creating DataFrame
        df = pd.DataFrame()

        # Adding all the required columns to the DataFrame
        df['RSI'] = RSI.rsi().dropna()

        # Initialising matplotlib
        fig = plt.figure(figsize=(7, 6))

        ax = fig.add_subplot(1, 1, 1)
        x_axis = df.index

        # Plotting 70 and 30 RSI lines
        ax.plot(x_axis, [70] * len(x_axis), label="overbought")
        ax.plot(x_axis, [30] * len(x_axis), label="oversold")

        # Plotting RSI
        ax.plot(x_axis, df['RSI'], label="RSI")
        ax.legend()

        plt.ylabel(f'RSI: {stock_ticker}', fontsize=15)
        plt.xlabel('Date', fontsize=15)
        plt.title(f'Relative Strength Index: {stock_ticker}', fontsize=20)
        plt.legend()
        try:
            plt.savefig(f'image/{stock_ticker}/RSI_{stock_ticker}.png',
                        bbox_inches='tight')
        except:
            directory = f'image/{stock_ticker}'
            for f in os.listdir(stock_ticker):
                os.remove(os.path.join(directory, f))
            plt.savefig(f'image/{stock_ticker}/RSI_{stock_ticker}.png',
                        bbox_inches='tight')
Exemple #21
0
def main():
    zerodha = get_zerodha_client(ZERODHA_CONFIG)
    instruments = zerodha.instruments("NSE")
    stock_list = filter_instruments(instruments)
    print_str = ""
    for candle in CANDLE_SIZE_SET:
        print_str += candle + "    "
    print("                     {}".format(print_str))
    row = ["STOCK"]
    row.extend(CANDLE_SIZE_SET)
    with open("rsi.csv", "w") as write_file:
        csvwriter = csv.writer(write_file)
        csvwriter.writerow(row)
    for stock in stock_list:
        try:
            range_list = []
            last_rsi = {}
            for CANDLE_SIZE in CANDLE_SIZE_SET:
                candles = get_data_of_stock(zerodha, stock, CANDLE_SIZE)
                rsi = RSIIndicator(close=candles['close'], n=RSI_DAYS)
                last_rsi[CANDLE_SIZE] = rsi.rsi().tail(
                    CANDLES_TO_OBSERVE).iloc[0]
                if (CANDLES_TO_OBSERVE == 1):
                    range_stock = get_range(rsi.rsi().tail(CANDLES_TO_OBSERVE),
                                            stock["stock"])
                    range_list.append(range_stock)
                else:
                    crossovers = get_crossovers(
                        rsi.rsi().tail(CANDLES_TO_OBSERVE))
                    print_crossovers(crossovers, stock["stock"])
            alerts = get_alerts(last_rsi)
            print_range(range_list, stock["stock"], alerts)
            if WRITE_TO_FILE:
                write_to_file(range_list, stock["stock"])
        except Exception as e:
            print(e)
    def action(self, indicator):
        # Derive the action based on past data
        # action: 1 means buy, -1 means sell, 0 means do nothing
        close = indicator["c"]
        indicator["momentum_rsi"] = RSIIndicator(close=close).rsi()
        indicator["momentum_rsi_prev"] = indicator["momentum_rsi"].shift(1)

        # If 69 -> 70: Sell, If 30 -> 29: Buy
        indicator["sell"] = (
            (indicator["momentum_rsi_prev"] < self.parameters["rsi70"])
            & (indicator["momentum_rsi"] >= self.parameters["rsi70"])
        ).astype(int)
        indicator["buy"] = (
            (indicator["momentum_rsi_prev"] >= self.parameters["rsi30"])
            &
            (indicator["momentum_rsi"] < self.parameters["rsi30"])).astype(int)
        indicator["action"] = indicator["buy"] - indicator["sell"]
Exemple #23
0
class TestRSIIndicator(unittest.TestCase):
    """
    https://school.stockcharts.com/doku.php?id=technical_indicators:relative_strength_index_rsi
    Note: Using a more simple initilization (directly `ewm`; stockcharts uses `sma` + `ewm`)
    """

    _filename = 'ta/tests/data/cs-rsi.csv'

    def setUp(self):
        self._df = pd.read_csv(self._filename, sep=',')
        self._indicator = RSIIndicator(close=self._df['Close'], n=14, fillna=False)

    def tearDown(self):
        del(self._df)

    def test_rsi(self):
        target = 'RSI'
        result = self._indicator.rsi()
        pd.testing.assert_series_equal(self._df[target].tail(), result.tail(), check_names=False)
Exemple #24
0
    def initialize_candles(self):
        dates, opens, highs, lows, closes, volumes = [], [], [], [], [], []
        candles = self.client.get_klines(symbol=self.coin, interval=self.interval)
        for candle in candles:
            dates.append(candle[0])
            opens.append(candle[1])
            highs.append(candle[2])
            lows.append(candle[3])
            closes.append(candle[4])
            volumes.append(candle[5])

        self.data['date'] = dates
        self.data['open'] = np.array(opens).astype(np.float)
        self.data['high'] = np.array(highs).astype(np.float)
        self.data['low'] = np.array(lows).astype(np.float)
        self.data['close'] = np.array(closes).astype(np.float)
        self.data['volume'] = np.array(volumes).astype(np.float)
        self.data['rsi'] = RSIIndicator(close=self.data["close"], n=14).rsi()
        self.data["ema_9"] = EMAIndicator(close=self.data["close"], n=8).ema_indicator()
        self.data["ema_21"] = EMAIndicator(close=self.data["close"], n=21).ema_indicator()
        self.data["ema_55"] = EMAIndicator(close=self.data["close"], n=55).ema_indicator()
        print(F"Successfully loaded {len(self.data)} candles")
        self.define_trend()
Exemple #25
0
 def _rsi(self, df, close):
     rsi = RSIIndicator(close=close)
     df['rsi'] = rsi.rsi()
Exemple #26
0
    df = pd.DataFrame(data=ETH)

    kama_indicator = KAMAIndicator(close = df["Close"], window = 10, pow1 = 2, pow2 = 30, fillna = False)
    df['kama'] = kama_indicator.kama()

    ppo_indicator = PercentagePriceOscillator(close = df["Close"], window_slow = 20, window_fast = 10, window_sign = 9, fillna = False)
    df['ppo'] = ppo_indicator.ppo()

    roc_indicator = ROCIndicator(close = df["Close"], window = 12, fillna = False)
    df['roc'] = roc_indicator.roc()

    macd_indicator = MACD(close = df["Close"], window_slow = 20, window_fast = 12, window_sign = 9, fillna = False)
    df['macd'] = macd_indicator.macd()

    rsi_indicator = RSIIndicator(close = df["Close"], window = 14, fillna = False)
    df['rsi'] = rsi_indicator.rsi()

    aroon_indicator = AroonIndicator(close = df["Close"], window = 20, fillna = False)
    df['aroon'] = aroon_indicator.aroon_indicator()

    boll_indicator = BollingerBands(close = df["Close"], window = 20, window_dev = 2, fillna = False)
    df['boll_mavg'] = boll_indicator.bollinger_mavg()

    df.rename(columns = {"Close": "price"}, inplace=True)
    prices = df['price'].to_numpy()

    df['day_of_month'] = df.index.day
    df['day_of_week'] = df.index.dayofweek
    df['month'] = df.index.month
    def __init__(self, symbols):

        # data = json.loads(symbols)
        # df_stock = pd.json_normalize(symbols)
        # df_stock = pd.read_csv(fn,names = ['sym']).drop_duplicates()
        df_stock = pd.DataFrame(symbols)
        ls_stock = df_stock['sym'].to_list()

        df_stock = df_stock.reset_index()

        df_stock.columns = ['sort', 'sym']

        df_stock.head()

        # In[3]:

        start = dt.date.today() + relativedelta(days=-150)
        end = dt.date.today() + relativedelta(days=-0)

        ls_tickers = ls_stock

        ls_df = []
        for ticker in ls_tickers:
            try:
                df = web.DataReader(ticker, 'yahoo', start, end)
            except Exception as e:
                print(str(e))
                continue
            df['sym'] = ticker
            ls_df.append(df.copy())

        df_price = pd.concat(ls_df).reset_index()
        df_price.columns = [
            'dte', 'hgh', 'low', 'opn', 'cls', 'vol', 'cls_adj', 'sym'
        ]
        df_price.sort_values(['sym', 'dte'], inplace=True)

        df_price = df_price[['dte', 'sym', 'hgh', 'low', 'cls', 'vol']].copy()

        df_price['curr'] = end

        df_price['curr'] = pd.to_datetime(df_price['curr'])
        df_price['dte'] = pd.to_datetime(df_price['dte'])

        df_price['ndays'] = (df_price['curr'] - df_price['dte']).dt.days

        df_price['ndays'] = df_price.groupby(['sym'])['ndays'].rank()

        df_price[df_price['sym'] == 'SPY'].head()

        # In[4]:

        ls_df = []
        ls_tickers = ls_stock

        for ticker in ls_tickers:

            #df = dropna(df_price[df_price['sym']==ticker])
            df = df_price[df_price['sym'] == ticker].copy()

            indicator_bb = BollingerBands(close=df['cls'],
                                          window=20,
                                          window_dev=2)
            indicator_macd = MACD(close=df['cls'],
                                  window_fast=12,
                                  window_slow=26,
                                  window_sign=9)
            indicator_rsi14 = RSIIndicator(close=df['cls'], window=14)
            indicator_cci20 = cci(high=df['hgh'],
                                  low=df['low'],
                                  close=df['cls'],
                                  window=20,
                                  constant=0.015)
            indicator_obv = OnBalanceVolumeIndicator(close=df['cls'],
                                                     volume=df['vol'],
                                                     fillna=True)

            indicator_vol_sma20 = SMAIndicator(close=df['vol'], window=20)

            indicator_ema03 = EMAIndicator(close=df['cls'], window=3)
            indicator_ema05 = EMAIndicator(close=df['cls'], window=5)
            indicator_ema08 = EMAIndicator(close=df['cls'], window=8)
            indicator_ema10 = EMAIndicator(close=df['cls'], window=10)
            indicator_ema12 = EMAIndicator(close=df['cls'], window=12)
            indicator_ema15 = EMAIndicator(close=df['cls'], window=15)
            indicator_ema30 = EMAIndicator(close=df['cls'], window=30)
            indicator_ema35 = EMAIndicator(close=df['cls'], window=35)
            indicator_ema40 = EMAIndicator(close=df['cls'], window=40)
            indicator_ema45 = EMAIndicator(close=df['cls'], window=45)
            indicator_ema50 = EMAIndicator(close=df['cls'], window=50)
            indicator_ema60 = EMAIndicator(close=df['cls'], window=60)

            # Add Bollinger Band high indicator
            df['bb_bbhi'] = indicator_bb.bollinger_hband_indicator()

            # Add Bollinger Band low indicator
            df['bb_bbli'] = indicator_bb.bollinger_lband_indicator()

            #df['macd'] = indicator_macd.macd()
            df['macd'] = indicator_macd.macd_diff()
            #df['macd_signal'] = indicator_macd.macd_signal()

            df['obv'] = indicator_obv.on_balance_volume()

            df['vol_sma20'] = indicator_vol_sma20.sma_indicator()

            df['ema03'] = indicator_ema03.ema_indicator()
            df['ema05'] = indicator_ema05.ema_indicator()
            df['ema08'] = indicator_ema08.ema_indicator()
            df['ema10'] = indicator_ema10.ema_indicator()
            df['ema12'] = indicator_ema12.ema_indicator()
            df['ema15'] = indicator_ema15.ema_indicator()
            df['ema30'] = indicator_ema30.ema_indicator()
            df['ema35'] = indicator_ema35.ema_indicator()
            df['ema40'] = indicator_ema40.ema_indicator()
            df['ema45'] = indicator_ema45.ema_indicator()
            df['ema50'] = indicator_ema50.ema_indicator()
            df['ema60'] = indicator_ema60.ema_indicator()

            df['rsi14'] = indicator_rsi14.rsi()
            df['cci20'] = indicator_cci20

            ls_df.append(df.copy())

        df = pd.concat(ls_df)

        df['score_vol_sma20'] = df[['vol',
                                    'vol_sma20']].apply(lambda x: x[0] / x[1],
                                                        axis=1)

        df['emash_min'] = df[[
            'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15'
        ]].min(axis=1)
        df['emash_max'] = df[[
            'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15'
        ]].max(axis=1)
        df['emash_avg'] = df[[
            'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15'
        ]].mean(axis=1)

        #df['score_short'] = df[['cls','emash_min','emash_max','emash_min']].apply(lambda x: 100 * (x[0]-x[1])/(x[2]-x[3]),axis=1)

        df['emalg_min'] = df[[
            'ema30', 'ema35', 'ema40', 'ema45', 'ema50', 'ema60'
        ]].min(axis=1)
        df['emalg_max'] = df[[
            'ema30', 'ema35', 'ema40', 'ema45', 'ema50', 'ema60'
        ]].max(axis=1)
        df['emalg_avg'] = df[[
            'ema30', 'ema35', 'ema40', 'ema45', 'ema50', 'ema60'
        ]].mean(axis=1)

        #df['score_long'] = df[['cls','emalg_min','emalg_max','emalg_min']].apply(lambda x: 100 * (x[0]-x[1])/(x[2]-x[3]),axis=1)

        df['ema_min'] = df[[
            'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15', 'ema30',
            'ema35', 'ema40', 'ema45', 'ema50', 'ema60'
        ]].min(axis=1)
        df['ema_max'] = df[[
            'ema03', 'ema05', 'ema08', 'ema10', 'ema12', 'ema15', 'ema30',
            'ema35', 'ema40', 'ema45', 'ema50', 'ema60'
        ]].max(axis=1)

        df['score_ovlp_ema'] = df[[
            'emash_min', 'emalg_max', 'ema_max', 'ema_min'
        ]].apply(lambda x: 100 * (x[0] - x[1]) / (x[2] - x[3]), axis=1)

        df = pd.merge(df_stock, df, on=['sym'],
                      how='inner').sort_values(['sort', 'ndays'])

        decimals = pd.Series([1, 0, 0, 2, 0, 0, 2, 0, 0, 0, 0],
                             index=[
                                 'cls', 'ndays', 'vol', 'score_vol_sma20',
                                 'bb_bbhi', 'bb_bbli', 'macd', 'obv', 'rsi14',
                                 'cci20', 'score_ovlp_ema'
                             ])

        cols = [
            'ndays', 'dte', 'sort', 'sym', 'cls', 'vol', 'score_vol_sma20',
            'bb_bbhi', 'bb_bbli', 'macd', 'obv', 'rsi14', 'cci20',
            'score_ovlp_ema'
        ]

        df = df[df['ndays'] <= 10][cols].round(decimals).copy()

        print(df['score_ovlp_ema'].min(), df['score_ovlp_ema'].max())

        df[df['sym'] == 'QQQ'].head(50)
        self.df = df
Exemple #28
0
def get_stock_predictions():
    start = time.time()
    ticker = request.args.get('ticker')
    date = -1

    np.random.seed(312)

    try:
        

        df = stocks[ticker].copy()
        df['return'] = df['PRC'].pct_change()
        df.drop( columns = ['COMNAM'], inplace = True)
        df.set_index('date', inplace=True, drop=True)
        df['1_day_return'] = df['return'].shift(-1)
        df['1_day_return'] = np.where(df['1_day_return'] > 0, 1, 0)

        ewma = pd.Series.ewm

        df['Fast_Exp_Moving_Avg'] = df['PRC'].transform(lambda x: ewma(x, span = 12).mean())
        df['Slow_Exp_Moving_Avg'] = df['PRC'].transform(lambda x: ewma(x, span = 26).mean())
        df['Momentum_Factor'] = df['Fast_Exp_Moving_Avg']/df['Slow_Exp_Moving_Avg']

        df['Moving_Avg'] = df['PRC'].transform(lambda x: x.rolling(window=20).mean())
        df['Moving_Std_Deviation'] = df['PRC'].transform(lambda x: x.rolling(window=20).std())  
        
        df['Ultimate_Oscillator'] = UltimateOscillator(df['ASKHI'], df['BIDLO'], df['PRC'], fillna = True).uo()
        df['RSI_Indicator'] = RSIIndicator(df['PRC'], 14, False).rsi()
        df['Stochastic_Oscillator'] = StochasticOscillator(df['ASKHI'], df['BIDLO'], df['PRC'], 14, 3, True).stoch()

        # print("3")
        n_fast = 12
        n_slow = 26
        df['MACD'] = df['Slow_Exp_Moving_Avg'] - df['Fast_Exp_Moving_Avg']

        # Bollinger Bands
        df['BollingerB_UP'] =  df['Moving_Avg'] + df['Moving_Std_Deviation']*2
        df['BollingerB_DOWN'] = df['Moving_Avg'] - df['Moving_Std_Deviation']*2

        if stocks_industry.get(ticker) != None:
            industry = stocks_industry.get(ticker).lower().replace(" ", "_")

            industry_df = pd.read_csv(f'../database/industry_info/{industry}_returns.csv')
            industry_df.set_index('date', inplace=True, drop=True)
            df['avg_industry_return'] = industry_df['avg_return']

        df.dropna(inplace = True)
        X = df[df.columns[~df.columns.isin(['1_day_return','TICKER'])]]
        y = df.loc[:, '1_day_return']

    except:
        return jsonify({})

    xgb = XGBClassifier(random_state=0, seed = 312)

    xgb.fit(X.iloc[:-1], y.iloc[:-1])

    predict_for = pd.DataFrame(X.iloc[date]).T
    print(predict_for)

    # print(xgb.predict(X))
    answer = xgb.predict_proba(predict_for)[0]
    prediction = xgb.predict(predict_for)[0]
    confidence = max(answer) * 100

    feature_scores = xgb._Booster.get_score()
    
    descriptors = {'OPENPRC': 'The open price', 
               'SHROUT': 'The number of shares outstanding', 
               'Moving_Avg': 'The average price of the stock over a rolling window of 20 days', 
               'Ultimate_Oscillator': 'Larry Williams’ (1976) signal, a momentum oscillator designed to capture momentum across three different timeframes.',
               'VOL': 'The volume traded today',
               'Stochastic_Oscillator': 'Developed in the late 1950s by George Lane. The stochastic oscillator presents the location of the closing price of a stock in relation to the high and low range of the price of a stock over a period of time, typically a 14-day period.',
               'BIDLO': 'The lowest bid price today',
               'ASKHI': 'The highest asking price today',
               'Slow_Exp_Moving_Avg': 'This is a first-order infinite impulse response filter that applies weighting factors which decrease exponentially. Basically, a fancy moving average.',
               'return': 'The return of the stock today, i.e. perentage change from the price yesterday to the price today',
               'RSI_Indicator': 'Compares the magnitude of recent gains and losses over a specified time period to measure speed and change of price movements of a security. It is primarily used to attempt to identify overbought or oversold conditions in the trading of an asset.',
               'BollingerB_DOWN': 'Developed by John Bollinger, Bollinger Bands® are volatility bands placed above and below a moving average. Volatility is based on the standard deviation, which changes as volatility increases and decreases',
               'BollingerB_UP': 'Developed by John Bollinger, Bollinger Bands® are volatility bands placed above and below a moving average. Volatility is based on the standard deviation, which changes as volatility increases and decreases',
               'Momentum_Factor': 'Simple Momentum of the stock',
               'PRC': 'The closing price of the stock',
               'MACD': 'A trend-following momentum indicator that shows the relationship between two moving averages of prices. The MACD is calculated by subtracting the 26-day exponential moving average (EMA) from the 12-day EMA',
               'Fast_Exp_Moving_Avg': 'This is a first-order infinite impulse response filter that applies weighting factors which decrease exponentially. Basically, a fancy moving average.',
               'avg_industry_return': 'The Average returns of the industry the stock is a part of.',
               'Moving_Std_Deviation': 'The standard deviation over a period of 20-days'
               }

    links = {'OPENPRC': '', 
            'SHROUT': '', 
            'Moving_Avg': 'https://en.wikipedia.org/wiki/Moving_average', 
            'Ultimate_Oscillator': 'http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:ultimate_oscillator',
            'VOL': '',
            'Stochastic_Oscillator': 'https://school.stockcharts.com/doku.php?id=technical_indicators:stochastic_oscillator_fast_slow_and_full',
            'BIDLO': '',
            'ASKHI': '',
            'Slow_Exp_Moving_Avg': 'https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average',
            'return': '',
            'RSI_Indicator': 'https://www.investopedia.com/terms/r/rsi.asp',
            'BollingerB_DOWN': 'https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_bands',
            'BollingerB_UP': 'https://school.stockcharts.com/doku.php?id=technical_indicators:bollinger_bands',
            'Momentum_Factor': 'https://school.stockcharts.com/doku.php?id=technical_indicators:rate_of_change_roc_and_momentum',
            'PRC': '',
            'MACD': 'https://www.investopedia.com/terms/m/macd.asp',
            'Fast_Exp_Moving_Avg': 'https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average',
            'avg_industry_return': '',
            'Moving_Std_Deviation': 'https://en.wikipedia.org/wiki/Moving_average'
            }

    classes = ['High', 'High', 'High', 'Medium', 'Medium', 'Medium', 'Medium', 'Medium', 'Low', 'Low', 'Low', 'Low', 'Low', 'Low',  'Almost None', 'Almost None', 'Almost None', 'Almost None', 'Almost None', 'Almost None']

    scores = [[feature, weight]for feature, weight in feature_scores.items()]

    scores.sort(key = lambda x: x[1], reverse = True)

    for i, score in enumerate(scores):
        feature = score[0]
        score[1] = str(score[1])
        score.append(classes[i])
        score.append(descriptors[feature])
        score.append(links[feature])

    results = {
        'prediction' : str(prediction),
        'confidence' : str(confidence),
        'feature_importance': feature_scores,
        'descriptions' : scores 
    }
    end = time.time()

    print(end - start)
    
    return jsonify(results)
Exemple #29
0
def rsi(df):
    indicator_rsi = RSIIndicator(close=df["Close"])
    df['rsi'] = indicator_rsi.rsi()
Exemple #30
0
 def setUpClass(cls):
     cls._df = pd.read_csv(cls._filename, sep=',')
     cls._params = dict(close=cls._df['Close'], n=14, fillna=False)
     cls._indicator = RSIIndicator(**cls._params)