Пример #1
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()
Пример #2
0
    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
Пример #3
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
Пример #4
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()
Пример #5
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
Пример #6
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)
Пример #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
Пример #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()
Пример #9
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
Пример #10
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)
Пример #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']
Пример #12
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()
Пример #13
0
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
Пример #14
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')
Пример #15
0
 def _rsi(self, df, close):
     rsi = RSIIndicator(close=close)
     df['rsi'] = rsi.rsi()
Пример #16
0
def calculate_Momentum_Indicators():

    JSON_sent = request.get_json()
    df = pd.DataFrame(JSON_sent[0])

    _, RSI, TSI, UO, STOCH, STOCH_SIGNAL, WR, AO, KAMA, ROC = JSON_sent

    indicator_RSI = RSIIndicator(close=df["close"], n=RSI['N'])
    df['rsi'] = indicator_RSI.rsi()

    if TSI['displayTSI']:
        indicator_TSI = TSIIndicator(close=df["close"],
                                     r=TSI['rTSI'],
                                     s=TSI['sTSI'])
        df['tsi'] = indicator_TSI.tsi()

    if UO['displayUO']:
        indicator_UO = uo(high=df['high'],
                          low=df['low'],
                          close=df['close'],
                          s=UO['sForUO'],
                          m=UO['mForUO'],
                          len=UO['lenForUO'],
                          ws=UO['wsForUO'],
                          wm=UO['wmForUO'],
                          wl=UO['wlForUO'])
        df['uo'] = indicator_UO

    if STOCH['displaySTOCH']:
        indicator_Stoch = stoch(high=df['high'],
                                low=df['low'],
                                close=df['close'],
                                n=STOCH['nForSTOCH'],
                                d_n=STOCH['dnForSTOCH'])
        df['stoch'] = indicator_Stoch

    if STOCH_SIGNAL['displayStochSignal']:
        indicator_StochSignal = stoch_signal(
            high=df['high'],
            low=df['low'],
            close=df['close'],
            n=STOCH_SIGNAL['nForStochSignal'],
            d_n=STOCH_SIGNAL['dnForStochSignal'])
        df['stoch_signal'] = indicator_StochSignal

    if WR['displayWR']:
        indicator_wr = wr(high=df['high'],
                          low=df['low'],
                          close=df['close'],
                          lbp=WR['lbpForWR'])
        df['wr'] = indicator_wr

    if AO['displayAO']:
        indicator_ao = ao(high=df['high'],
                          low=df['low'],
                          s=AO['sForAO'],
                          len=AO['lenForAO'])
        df['ao'] = indicator_ao

    if KAMA['displayKama']:
        indicator_kama = kama(close=df['close'],
                              n=KAMA['nForKama'],
                              pow1=KAMA['pow1ForKama'],
                              pow2=KAMA['pow2ForKama'])
        df['kama'] = indicator_kama

    if ROC['displayROC']:
        indicator_roc = roc(close=df['close'], n=ROC['nForROC'])
        df['roc'] = indicator_roc

    df.fillna(0, inplace=True)
    export_df = df.drop(columns=['open', 'high', 'low', 'close', 'volume'])
    return (json.dumps(export_df.to_dict('records')))
Пример #17
0
from keras.models import Sequential
from keras.layers import Conv1D, MaxPool1D, Bidirectional, LSTM, Dropout, TimeDistributed
from keras.layers import Dense, GlobalAveragePooling2D
from ta.trend import IchimokuIndicator
from sklearn.linear_model import LinearRegression
from ta import add_all_ta_features
from ta.utils import dropna
import matplotlib.pyplot as plt
filename = 'AAPL'
stock = pd.read_csv('Data/' + filename + '.csv')
indicator_bb = BollingerBands(close=stock["Close"], n=20, ndev=2)
macd = MACD(close=stock["Close"])
rsi = RSIIndicator(close=stock["Close"])
ichi = IchimokuIndicator(high=stock["High"], low=stock["Low"])
stock['macd'] = macd.macd()
stock['rsi'] = rsi.rsi()
stock['bb_bbm'] = indicator_bb.bollinger_mavg()
stock['bb_bbh'] = indicator_bb.bollinger_hband()
stock['bb_bbl'] = indicator_bb.bollinger_lband()
stock['ichi_a'] = ichi.ichimoku_a()
stock['ichi_b'] = ichi.ichimoku_b()
stock['ichi_base'] = ichi.ichimoku_base_line()
stock['ichi_conv'] = ichi.ichimoku_conversion_line()
stock = stock.fillna(0)
print(stock)
scaler = preprocessing.MinMaxScaler()
scaled_values = scaler.fit_transform(stock.iloc[:, 1:4])
stock.iloc[:, 1:4] = scaled_values

y_scaler = preprocessing.MinMaxScaler()
scaled_values = y_scaler.fit_transform(
Пример #18
0
            indicator_ema_100 = EMAIndicator(close=df["adj_close"], window=100)
            df['ema_100'] = indicator_ema_100.ema_indicator()
            indicator_ema_50 = EMAIndicator(close=df["adj_close"], window=50)
            df['ema_50'] = indicator_ema_50.ema_indicator()

            # SMA Indicator
            indicator_sma_200 = SMAIndicator(close=df["adj_close"], window=200)
            df['sma_200'] = indicator_sma_200.sma_indicator()
            indicator_sma_100 = SMAIndicator(close=df["adj_close"], window=100)
            df['sma_100'] = indicator_sma_100.sma_indicator()
            indicator_sma_50 = SMAIndicator(close=df["adj_close"], window=50)
            df['sma_50'] = indicator_sma_50.sma_indicator()

            # RSI Indicator
            indicator_rsi_6 = RSIIndicator(close=df["adj_close"], window=6)
            df['rsi_6'] = indicator_rsi_6.rsi()
            indicator_rsi_14 = RSIIndicator(close=df["adj_close"], window=14)
            df['rsi_14'] = indicator_rsi_14.rsi()

            # MACD Indicator
            indicator_macd = MACD(close=df["adj_close"])
            df['macd'] = indicator_macd.macd()
            # df = df.dropna(how='all)
            df.set_index('trading_date', inplace=True)

            # Filter the latest ones
            df = df[df.index > last_entry_dict[equity_id]]

            for idx, row in df.iterrows():
                trade_date = row['trading_date']
                bb_bbh = row['bb_bbh']
Пример #19
0
    else:
        pass

# Run the macd line inflection point trigger function

# ------- THIS IS WORK IN PROGRESS -------------------------------------------------------------------------------------

#MACD_inflection_trigger = MACD_inflection_trigger(EURUSD_T_FX.Last, EURUSD_T_FX['MACD'])

# ----------------------------------------------------------------------------------------------------------------------

# Set up RSI calculation

EURUSD_T_FX_RSI = RSIIndicator(close = EURUSD_T_FX["Last"])

RSI_line = EURUSD_T_FX_RSI.rsi()

#print(RSI_line.tolist())

RSI_indicator_buy_trigger = RSI_indicator_trigger(RSI_line)[0]
RSI_indicator_sell_trigger = RSI_indicator_trigger(RSI_line)[1]

# Set up a restricted buy signal that considers the RSI and the MACD cross-over triggers

buy_prices = []
sell_prices = []

#SOMETHING IS WRONG HERE - NOT WORKING ON CHART.....
count = 0

for i in zip(RSI_indicator_buy_trigger, RSI_indicator_sell_trigger, MACD_buy_sig, MACD_sell_sig):
Пример #20
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

    df.dropna(inplace=True)
Пример #21
0
def scan(file_path,start_date,end_date):

    buys = pd.DataFrame()
    sells = pd.DataFrame()
    buy_list = []
    buy_list_sl = []
    buy_list_tp = []
    sell_list = []
    sell_list_tp = []
    sell_list_sl = []
    buy_list_sq = []
    sell_list_sq = []
    on_squeeze = []

    with open(file_path) as f:
        lines = f.read().splitlines()
        for symbol in lines:
            print(symbol)
            data = yf.download(symbol, start=start_date, end=end_date)
            df = pd.DataFrame(data)

            if df.empty:
                continue

            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)

            if df["squeeze_on"].iloc[-1]==True:
                on_squeeze.append(symbol)

            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"

            if df["Signal"].iloc[-1] == "Buy" and (df["Signal"].iloc[-2] != "Buy"):
                buy_list.append(symbol)
                buy_list_sl.append(df["Close"].iloc[-1]-(df["ATR"].iloc[-1]*1.4))
                buy_list_tp.append(df["Close"].iloc[-1]+(df["ATR"].iloc[-1]*2.8))
                buy_list_sq.append(df['squeeze_on'].iloc[-1])
            elif df["Signal"].iloc[-1] == "Sell" and (df["Signal"].iloc[-2] != "Sell"):
                sell_list.append(symbol)
                sell_list_sl.append(df["Close"].iloc[-1]+(df["ATR"].iloc[-1]*1.4))
                sell_list_tp.append(df["Close"].iloc[-1]-(df["ATR"].iloc[-1]*2.8))
                sell_list_sq.append(df['squeeze_on'].iloc[-1])
            else:
                continue

            buys = pd.DataFrame({
                "Symbol" : buy_list,
                "SL" : buy_list_sl,
                "TP" : buy_list_tp,
                "Squeeze" : buy_list_sq
            })

            sells = pd.DataFrame({
                "Symbol" : sell_list,
                "SL" : sell_list_sl,
                "TP" : sell_list_tp,
                "Squeeze" : sell_list_sq
            })
                
    return buys, sells, on_squeeze
Пример #22
0
    def get_signal(self, input_df, ticker, run_id):
        df = input_df.copy()

        indicator_rsi = RSIIndicator(
            close=df["Close"],
            window=self.indicator["window"],
            fillna=self.indicator["fillna"],
        )

        # Add Bollinger Bands features
        df["rsi"] = indicator_rsi.rsi()

        previous_row = df.iloc[-2]
        row = df.iloc[-1]

        if row.rsi.item() > self.indicator["high"]:
            sell_signal = {
                "ticker":
                ticker,
                "datetime":
                row.Date,
                "indicator":
                self.name,
                "param":
                self.param,
                "reason":
                "High RSI Value - currently at {:2f}%".format(
                    int(row.rsi.item())),
                "image":
                self.draw_image(df, ticker, run_id),
            }
        elif (row.rsi.item() < self.indicator["high"]) and (
                previous_row.rsi.item() > self.indicator["high"]):
            sell_signal = {
                "ticker":
                ticker,
                "datetime":
                row.Date,
                "indicator":
                self.name,
                "param":
                self.param,
                "reason":
                "RSI Crossover High - previous at {:2f}& and currently at {:2f}%"
                .format(int(previous_row.rsi.item()), int(row.rsi.item())),
                "image":
                self.draw_image(df, ticker, run_id),
            }
        else:
            sell_signal = None

        if row.rsi.item() < self.indicator["low"]:
            buy_signal = {
                "ticker":
                ticker,
                "datetime":
                row.Date,
                "indicator":
                self.name,
                "param":
                self.param,
                "reason":
                "Low RSI Value - currently at {:2f}%".format(
                    int(row.rsi.item())),
                "image":
                self.draw_image(df, ticker, run_id),
            }
        elif (row.rsi.item() > self.indicator["low"]) and (
                previous_row.rsi.item() < self.indicator["low"]):
            buy_signal = {
                "ticker":
                ticker,
                "datetime":
                row.Date,
                "indicator":
                self.name,
                "param":
                self.param,
                "reason":
                "RSI Crossover Low - previous at {:2f}& and currently at {:2f}%"
                .format(int(previous_row.rsi.item()), int(row.rsi.item())),
                "image":
                self.draw_image(df, ticker, run_id),
            }
        else:
            buy_signal = None

        return buy_signal, sell_signal
Пример #23
0
    if str(MACD_buy_sig[i]) == 'nan':
        MACD_buy_sig[i] = 0
    else:
        pass

    if str(MACD_sell_sig[i]) == 'nan':
        MACD_sell_sig[i] = 0
    else:
        pass

# Set up RSI calculation

FX_data_RSI = RSIIndicator(close = FX_data["Last"])

RSI_line = FX_data_RSI.rsi()

RSI_indicator_buy_trigger = RSI_indicator_trigger(RSI_line)[0]
RSI_indicator_sell_trigger = RSI_indicator_trigger(RSI_line)[1]

# Set up a restricted buy signal that considers the RSI and the MACD cross-over triggers

buy_prices = []
buy_sell_signal = []
sell_prices = []

for i in range(0, len(RSI_indicator_buy_trigger)):

    # Classify buy and sell signals

    if MACD_buy_sig[i] != 0 and RSI_indicator_buy_trigger[i] == 1:
Пример #24
0
def rsi(df):
    indicator_rsi = RSIIndicator(close=df["Close"])
    df['rsi'] = indicator_rsi.rsi()
Пример #25
0
    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)
Пример #26
0
def get_stock_data(ticker, startDate, endDate):

    # Managing the date format has been a challenge due to sending Javascript
    # and Python date objects via JSON I've chosen to send dates as MM-DD-YYY
    # string and then create date objects in python on the backend and JS
    # on the frontend
    startDateForAPItemp = startDate.split('-')
    startDateForAPI = datetime(
        int(startDateForAPItemp[0]), int(startDateForAPItemp[1]),
        int(startDateForAPItemp[2])) - timedelta(days=90)

    # the API call prefers to choose a date that aligns with a stock market
    # trading period (i.e. M-F), therefore Saturday and Sundays are changed
    # to the previous Friday
    if startDateForAPI.weekday() == 5:
        startDateForAPI += timedelta(days=2)
    elif startDateForAPI.weekday() == 6:
        startDateForAPI += timedelta(days=1)

    # The same logic applies to the end date.
    endDateForAPItemp = endDate.split('-')
    endDateForAPI = datetime(int(endDateForAPItemp[0]),
                             int(endDateForAPItemp[1]),
                             int(endDateForAPItemp[2]))

    currentTime = datetime.utcnow()
    if str(currentTime.date()) == str(endDateForAPI.date()):
        endDateForAPI -= timedelta(days=1)

    if endDateForAPI.weekday() == 5:
        endDateForAPI -= timedelta(days=1)
    elif endDateForAPI.weekday() == 6:
        endDateForAPI -= timedelta(days=2)

    # the data returned by IEXcloud api is nested where the outer dictionary has nested dictionary based on date
    # This flatten_json function creates a signal dictionary where date is a key/value pair along with the corresponding stock data
    # This flattened format is better for providing a flattened array to D3.js
    def flatten_json(stockData):
        out = []
        for i in stockData:
            out2 = {}
            out2['date'] = i
            for j in stockData[i]:
                out2[j] = stockData[i][j]
            out.append(out2)
        return out

    # make the API to IEXcloud, using Addison Lynch's IEXfinance python package
    historicalData = get_historical_data(ticker,
                                         start=startDateForAPI.date(),
                                         end=endDateForAPI.date(),
                                         token=IEX_api_key)
    Historical_Data = flatten_json(historicalData)

    # using pandas for clean data manipulation using dataframes
    df = pd.DataFrame(Historical_Data)
    df = ta.utils.dropna(df)

    # we add the RSI indicator, regardless, to show on the initial charts
    indicator_RSI = RSIIndicator(close=df["close"], n=10)
    df['rsi'] = indicator_RSI.rsi()
    df = ta.utils.dropna(df)
    return (json.dumps(df.to_dict('records')))
Пример #27
0
    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
Пример #28
0
import yahoo_fin.stock_info as si
from ta import add_all_ta_features
from ta.momentum import RSIIndicator

# pull data from Yahoo Finance
data = si.get_data("aapl")

data = add_all_ta_features(
    data,
    open="open",
    high="high",
    low="low",
    close="adjclose",
    volume="volume",
)

rsi_21 = RSIIndicator(close=data.adjclose, window=21)
data["rsi_21"] = rsi_21.rsi()

print(list(data.columns))
print(data.momentum_rsi.tail())
Пример #29
0
    def applyIndicator(self, full_company_price):
        self.data = full_company_price

        high = self.data['high']
        low = self.data['low']
        close = self.data['close']
        volume = self.data['volume']

        EMA12 = EMAIndicator(close, 12, fillna=False)
        EMA30 = EMAIndicator(close, 20, fillna=False)
        EMA60 = EMAIndicator(close, 60, fillna=False)
        MACD1226 = MACD(close, 26, 12, 9, fillna=False)
        MACD2452 = MACD(close, 52, 24, 18, fillna=False)
        ROC12 = ROCIndicator(close, 12, fillna=False)
        ROC30 = ROCIndicator(close, 30, fillna=False)
        ROC60 = ROCIndicator(close, 60, fillna=False)
        RSI14 = RSIIndicator(close, 14, fillna=False)
        RSI28 = RSIIndicator(close, 28, fillna=False)
        RSI60 = RSIIndicator(close, 60, fillna=False)
        AROON25 = AroonIndicator(close, 25, fillna=False)
        AROON50 = AroonIndicator(close, 50, fillna=False)
        AROON80 = AroonIndicator(close, 80, fillna=False)
        MFI14 = MFIIndicator(high, low, close, volume, 14, fillna=False)
        MFI28 = MFIIndicator(high, low, close, volume, 28, fillna=False)
        MFI80 = MFIIndicator(high, low, close, volume, 80, fillna=False)
        CCI20 = CCIIndicator(high, low, close, 20, 0.015, fillna=False)
        CCI40 = CCIIndicator(high, low, close, 40, 0.015, fillna=False)
        CCI100 = CCIIndicator(high, low, close, 100, 0.015, fillna=False)
        WILLR14 = WilliamsRIndicator(high, low, close, 14, fillna=False)
        WILLR28 = WilliamsRIndicator(high, low, close, 28, fillna=False)
        WILLR60 = WilliamsRIndicator(high, low, close, 60, fillna=False)
        BBANDS20 = BollingerBands(close, 20, 2, fillna=False)
        KC20 = KeltnerChannel(high, low, close, 20, 10, fillna=False)
        STOCH14 = StochasticOscillator(high, low, close, 14, 3, fillna=False)
        STOCH28 = StochasticOscillator(high, low, close, 28, 6, fillna=False)
        STOCH60 = StochasticOscillator(high, low, close, 60, 12, fillna=False)
        CMI20 = ChaikinMoneyFlowIndicator(high,
                                          low,
                                          close,
                                          volume,
                                          20,
                                          fillna=False)
        CMI40 = ChaikinMoneyFlowIndicator(high,
                                          low,
                                          close,
                                          volume,
                                          40,
                                          fillna=False)
        CMI100 = ChaikinMoneyFlowIndicator(high,
                                           low,
                                           close,
                                           volume,
                                           100,
                                           fillna=False)

        self.data['ema12'] = (close - EMA12.ema_indicator()) / close
        self.data['ema30'] = (close - EMA30.ema_indicator()) / close
        self.data['ema60'] = (close - EMA60.ema_indicator()) / close
        self.data['macd1226'] = MACD1226.macd() - MACD1226.macd_signal()
        self.data['macd2452'] = MACD2452.macd() - MACD2452.macd_signal()
        self.data['roc12'] = ROC12.roc()
        self.data['roc30'] = ROC30.roc()
        self.data['roc60'] = ROC60.roc()
        self.data['rsi14'] = RSI14.rsi()
        self.data['rsi28'] = RSI28.rsi()
        self.data['rsi60'] = RSI60.rsi()
        self.data['aroon25'] = AROON25.aroon_indicator()
        self.data['aroon50'] = AROON50.aroon_indicator()
        self.data['aroon80'] = AROON80.aroon_indicator()
        self.data['mfi14'] = MFI14.money_flow_index()
        self.data['mfi28'] = MFI28.money_flow_index()
        self.data['mfi80'] = MFI80.money_flow_index()
        self.data['cci20'] = CCI20.cci()
        self.data['cci40'] = CCI40.cci()
        self.data['cci100'] = CCI100.cci()
        self.data['willr14'] = WILLR14.wr()
        self.data['willr28'] = WILLR28.wr()
        self.data['willr60'] = WILLR60.wr()
        self.data['bband20up'] = (BBANDS20.bollinger_hband() - close) / close
        self.data['bband20down'] = (close - BBANDS20.bollinger_lband()) / close
        self.data['stoch14'] = STOCH14.stoch()
        self.data['stoch28'] = STOCH28.stoch()
        self.data['stoch60'] = STOCH60.stoch()
        self.data['cmi20'] = CMI20.chaikin_money_flow()
        self.data['cmi40'] = CMI40.chaikin_money_flow()
        self.data['cmi100'] = CMI100.chaikin_money_flow()
        self.data['kc20up'] = (KC20.keltner_channel_hband() - close) / close
        self.data['kc20down'] = (close - KC20.keltner_channel_lband()) / close
        return self.data
Пример #30
0
buy_list_osq = []
sell_list_osq = []
on_squeeze = []
outof_squeeze = []

with open('ticker.csv') as f:
    lines = f.read().splitlines()
    for symbol in lines:
        print(symbol)
        data = yf.download(symbol,
                           start="2020-01-01",
                           end=datetime.today().strftime('%Y-%m-%d'))
        df = pd.DataFrame(data)

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

        Stochk = stoch(high=df["High"], low=df["Low"],
                       close=df["Close"]).rolling(window=3).mean()
        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()