July 27, 2026

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 t be given by P_{t}. The stock price change \Delta P_{t} is defined by:

(1)   \begin{align*}\Delta P_{t} = P_t - P_{t-1}\end{align*}

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

(2)   \begin{align*}G_{t} = \max(\Delta P_{t}, 0) \\L_{t} = \max(-\Delta P_{t}, 0)\end{align*}

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

(3)   \begin{align*}\alpha = \frac{1}{N}\end{align*}



where N is the time interval over which the relative strength index is defined and time series are smoothed. Then, the smoothed (average) gain, denoted by \bar{G}_{t} and smoothed (average) loss \bar{L}_t are calculated recursively as:

(4)   \begin{align*} \bar{G}_t = \frac{1}{N} G_{t} + \left(1 - \frac{1}{N}\right) \bar{G}_{t-1} = \alpha G_{t} + \left(1 - \alpha \right) \bar{G}_{t-1} \\\bar{L}_{t} = \frac{1}{N} L_{t} + \left(1 - \frac{1}{N}\right) \bar{L}_{t-1} = \alpha L_{t} + \left(1 - \alpha \right) \bar{L}_{t-1}\end{align*}

The Relative Strength is defined by

(5)   \begin{align*}R_{t} = \frac{\bar{G}_{t}}{\bar{L}_{t}}\end{align*}

The Relative Strength Index (RSI) is defined by

(6)   \begin{align*}S_{t} = 100 - \frac{100}{1 + R_{t}} = 100 \left( \frac{\bar{G}_{t}}{\bar{G}_{t} + \bar{L}_{t}} \right)\end{align*}