Using Custom Function for Initial Window and Rolling Afterward to Calculate Relative Strength Index (RSI) with Pandas

Relative Strength Index in Pandas Using Different Calculation on First Row

Introduction

The Relative Strength Index (RSI) is a popular technical indicator used to measure the magnitude of recent price changes in an asset. It is widely used by traders and investors to gauge the strength of a stock, currency, or commodity. In this article, we will explore how to calculate the RSI in pandas using different calculations for the first row.

Understanding the Basics of RSI

The RSI calculation involves two main components: the average gain (up) and the average loss (down). The formula for calculating the RSI is as follows:

RSI = 100 - ((Average Gain / Average Loss) * 100)

where Average Gain is the average of the positive price changes, and Average Loss is the average of the negative price changes.

The RSI value ranges from 0 to 100. A reading above 70 indicates an overbought condition, while a reading below 30 indicates an oversold condition. The RSI can be used as a contrarian indicator, suggesting that when it reaches extreme levels, it may be due for a reversal.

Calculating the Average Gain and Average Loss

To calculate the average gain and average loss, we need to identify the positive and negative price changes in a given period. We can use pandas’ built-in functions to achieve this.

Step 1: Identify Positive and Negative Price Changes

We start by identifying the positive and negative price changes using pandas’ diff function. This function calculates the difference between consecutive elements in a series.

df['delta'] = df['price'].diff()

Next, we use pandas’ loc function to identify the rows where the delta is greater than 0 (positive price change) and less than 0 (negative price change).

df.loc[df['delta'] > 0, 'up'] = df['delta'].loc[df['delta'] > 0]
df.loc[df['delta'] < 0, 'down'] = abs(df['delta'].loc[df['delta'] < 0])

Step 2: Calculate the Average Gain and Average Loss

Now that we have identified the positive and negative price changes, we can calculate the average gain and average loss using pandas’ mean function.

df['avg_up'] = df['up'].rolling(window).mean()
df['avg_down'] = df['down'].rolling(window).mean()

However, in our case, we need to calculate the average gain and average loss differently for rows after the window. This is where rolling comes into play.

Using Rolling for the First Row

When using rolling functions, pandas calculates the mean from the beginning by default. To get around this limitation, we can use a custom function that takes into account both the current value and previous values when calculating the mean.

def meanf(x):
    if x.shape[0] > 14:
        res = x[:14].mean()
        for n in x[14:]:
            res = (res * (14 - 1) + n) / 14
        return res
    else:
        return x.mean()

df['avg_up'] = df.rolling(len(data), min_periods=window).apply(meanf)['up']
df['avg_down'] = df.rolling(len(data), min_periods=window).apply(meanf)['down']

This custom function calculates the mean by first taking the average of the initial 14 values, and then iteratively adding each new value to the previous sum with a decreasing weight.

Using Rolling for Rows After the Window

For rows after the window, we can use rolling functions without needing a custom function. This is because pandas calculates the mean using the current value by default when min_periods is set to the length of the series.

df['avg_up'] = df['up'].rolling(window).mean()
df['avg_down'] = df['down'].rolling(window).mean()

To calculate the RSI for rows after the window, we can use rolling functions without needing a custom function. This is because pandas calculates the mean using the current value by default when min_periods is set to the length of the series.

df['rs'] = df['avg_up'] / df['avg_down']
df['rsi'] = 100 - (100 / (1 + df['rs']))

Conclusion

In this article, we explored how to calculate the Relative Strength Index (RSI) in pandas using different calculations for the first row. We used rolling functions to calculate the average gain and average loss, including a custom function to handle the initial 14 values. Finally, we demonstrated how to use rolling functions without needing a custom function to calculate the RSI for rows after the window. By mastering these techniques, you can create powerful technical indicators in pandas that help you make informed investment decisions.


Last modified on 2024-01-03