HAN's BLOG

Relative strength index (RSI)

Relative Strength index (RSI)

It’s famouse for secondary indicator of stock’s market. This is presented by variance for changing upper and down.

It has tendency if it decrease, it is creasing and also if it crease, it is decresing.

Recently it should have been not true surely. However, it has been importnat index for advance afterwards.

Class code

Anyway, this is presented how to calculate the RSI.

# classRSI.py
 
import numpy as np
import pandas as pd
import pandas_datareader as pdr

class Stocks:
    def __init__(self, symbol, start_day, end_day):
        self.symbol = symbol
        self.start_day = start_day
        self.end_day = end_day

    def calcRSI(self, period=14):
        df = pdr.DataReader(self.symbol, 'yahoo',self.start_day, self.end_day)
        date_index = df.index.astype('str')
        U = np.where(df.diff(1)['Adj Close'] > 0, df.diff(1)['Adj Close'], 0)
        D = np.where(df.diff(1)['Adj Close'] < 0, df.diff(1)['Adj Close'] * (-1), 0)
        AU = pd.DataFrame(U, index=date_index).rolling(window=period, min_periods=1).mean()
        AD = pd.DataFrame(D, index=date_index).rolling(window=period, min_periods=1).mean()
        RSI = AU/ (AD+AU) * 100

        df.insert(len(df.columns), 'RSI', RSI)
        df.insert(len(df.columns), 'RSI signal', df['RSI'].rolling(window=9, min_periods=1).mean())

        return df

RSI needs variance of upper and down with average of this. And It is calculated

RSI = Average of Upper / (Average of Upper + Average of Down) * 100

Caculating RSI signal which is calculated moving avereage for RSI, it’s comparing with two indexs.

Main code of plotting

 # PlotRSI.py
  
 import numpy as np
 import pandas as pd
 import pandas_datareader as pdr
 import datetime
 import matplotlib.pyplot as plt
 import matplotlib.ticker as ticker

 from classRSI import Stocks

 def main():
     td_1y = datetime.timedelta(weeks=52/2)
     today = datetime.datetime.now()
     start_day = today - td_1y

     symbol = input('Write ticker name like aapl: ') #^IXIC

     stock = Stocks(symbol, start_day, today)

     df= stock.calcRSI()

     index = df.index.astype('str')

     fig = plt.figure(figsize=(10,10))

     ax_main = plt.subplot(1,1,1)

     def x_date(x,pos):
         try:
             return index[int(x-0.5)][:7]
         except IndexError:
             return ''

     # For figure
     ax_main.xaxis.set_major_locator(ticker.MaxNLocator(10))
     ax_main.xaxis.set_major_formatter(ticker.FuncFormatter(x_date))

     ax_main.plot(index, df['RSI'], label='RSI')
     ax_main.plot(index, df['RSI signal'], label='RSI signal')

     plt.grid()
     plt.show()

 if __name__ == "__main__":
     main()

It is simply calculating for start day to today and plot

Example figure

image info

Typical ticker is AAPL(Apple). This figure is presented at 2021-06-26.

you just know that this plot what is mean :)

Model, Selection

For using RSI, we can make model and select ticker in index (Dow, S&P500 etc) ?

I have simple idea to use RSI value of down to up and up to down.

  • It is true that RSI value is under 30?

In my case, I have choose selected data by Bollinger band’s model. This model is explained this post which is also important finance index.

 # modelRSI.py
  
 import numpy as np
 import pandas as pd
 import datetime
 from tqdm import tqdm

 from classRSI import Stocks

 def main(stock_list, day_init=datetime.datetime(2020,1,1), today=datetime.datetime.now()):
     print(stock_list)

     selected_ticker = []
     for ticker in tqdm(stock_list):
         stock = Stocks(ticker, start_day, today)
         df = stock.calcRSI()
         df_recent = df.iloc[-1:]
         value_RSI = float(df_recent['RSI'])
         value_RSI_signal = float(df_recent['RSI signal'])
         down = 40
         if value_RSI < down:
             if value_RSI < value_RSI_signal:
                 selected_ticker.append(ticker)

     print(selected_ticker)

     url = '/Users/hanseopark/Work/stock/data_ForTrading/selected_ticker.json'
     df = pd.DataFrame(selected_ticker, columns=['Ticker'])
     df.to_json(url)

 if __name__ == '__main__':
     td_1y = datetime.timedelta(weeks=52/2)
     today = datetime.datetime.now()
     start_day = today - td_1y

     url = '/Users/hanseopark/Work/stock/data_ForTrading/{0}_TickerList.json'.format(today.date())
     s_list = pd.read_json(url)['Ticker'].values.tolist()
     main(stock_list = s_list, day_init = start_day)

If you change var of down like 30 to 40, you should get many ticker beyond hard condition.

Conclusion

Let us know what is RSI and how to caclulate with figure. And then we are going to find ticker using this model :)

If you want to use this code, I’m very sorry that you should change code and make directory for data a little bit.

I should appreciate and refer for many blog on google. Thanks a lot.

If you satisfied this post you should check Github and please Star :)