Fusion of Engineering, Control, Coding, Machine Learning, and Science

Download SPY Stocks Time Series and Compute the RSI in Python


In this Python, finance, and time series tutorial, we explain how to download the SPY stock time series and compute the Relative Strength Index (RSI) in Python. First, we briefly summarize the definition of the RSI value. The RSI value is used to identify oversold and overbought stocks and can be used to develop a simple trading algorithm.

Definition of RSI

Let the stock value at the discrete time instant be given by . The stock price change is defined by:

(1)  

The next step is to separate the positive gains, denoted by , and the absolute losses, denoted by :

(2)  

Next, we apply the Wilder’s exponential smoothing to gains and losses. First, we define the smoothing factor

(3)  



where is the time interval over which the relative strength index is defined and time series are smoothed. Then, the smoothed (average) gain, denoted by and smoothed (average) loss are calculated recursively as:

(4)  

The Relative Strength is defined by

(5)  

The Relative Strength Index (RSI) is defined by

(6)  

Exit mobile version