# RSI
![[rsi-example-apple.png]]
RSI, or ==Relative Strength Index== (상대강도지수), is a popular technical analysis indicator used in the financial markets to measure the speed and change of price movements. It was developed by J. Welles Wilder Jr. and introduced in his 1978 book, "New Concepts in Technical Trading Systems."
## Key Points About RSI:
1. **Calculation**:
- RSI is calculated using the formula:
$
\begin{align}
RSI = 100 - \frac{100}{1 + RS}
\end{align}
$
where \( RS \) (Relative Strength) is the average of x days' up closes divided by the average of x days' down closes. Typically, a 14-day period is used for calculation.
2. **Values**:
- RSI values range from 0 to 100.
- A reading above 70 is generally considered overbought, suggesting that the asset might be due for a price correction or pullback.
- A reading below 30 is considered oversold, indicating that the asset might be undervalued and could be due for a price bounce.
3. **Divergences**:
- Bullish divergence occurs when the price of an asset is making new lows while the RSI is making higher lows. This can signal a potential upward reversal.
- Bearish divergence happens when the price is making new highs but the RSI is making lower highs, suggesting a potential downward reversal.
4. **Trend Confirmation**:
- RSI can also be used to confirm trends. For instance, during a strong uptrend, RSI tends to stay above 30 and often hits 70. Conversely, during a strong downtrend, RSI typically remains below 70 and frequently hits 30.
5. **Usage**:
- Traders use RSI to identify potential buy and sell signals. An asset is often considered a buy signal when RSI moves below 30 and then rises back above it. Conversely, it is considered a sell signal when RSI moves above 70 and then falls back below it.
## Practical Example:
Let's consider a stock with the following closing prices over 14 days:
- Days 1-7: Prices rise from $100 to $107
- Days 8-14: Prices fall from $107 to $101
1. **Calculate the average gain**:
- Sum of gains over 14 days / 14
- (7/14) = 0.5 per day
2. **Calculate the average loss**:
- Sum of losses over 14 days / 14
- (6/14) = 0.4286 per day
3. **Calculate RS**:
- RS = Average Gain / Average Loss
- RS = 0.5 / 0.4286 = 1.1667
4. **Calculate RSI**:
- RSI = 100 - (100 / (1 + RS))
- RSI = 100 - (100 / (1 + 1.1667)) = 100 - 46.15 ≈ 53.85
In this example, the RSI of approximately 53.85 indicates that the stock is neither overbought nor oversold.
RSI is a versatile tool used by traders and investors to help make informed decisions about market entry and exit points based on the momentum of price movements.
## In Python
```python
import pandas as pd
# Sample closing prices
closing_prices = [44, 45, 46, 45, 44, 43, 44, 45, 46, 47, 48, 47, 46, 45]
# Convert closing prices to a pandas DataFrame
data = pd.DataFrame(closing_prices, columns=['Close'])
# Calculate the daily price changes
data['Change'] = data['Close'].diff()
# Separate gains and losses
data['Gain'] = data['Change'].apply(lambda x: x if x > 0 else 0)
data['Loss'] = data['Change'].apply(lambda x: -x if x < 0 else 0)
# Calculate the average gain and loss over the period (14 days)
period = 14
data['Avg_Gain'] = data['Gain'].rolling(window=period, min_periods=1).mean()
data['Avg_Loss'] = data['Loss'].rolling(window=period, min_periods=1).mean()
# Calculate the RS (Relative Strength)
data['RS'] = data['Avg_Gain'] / data['Avg_Loss']
# Calculate the RSI
data['RSI'] = 100 - (100 / (1 + data['RS']))
# Print the resulting DataFrame
print(data)
# Get the latest RSI value
latest_rsi = data['RSI'].iloc[-1]
print(f"The latest RSI value is: {latest_rsi:.2f}")
```
```
Close Change Gain Loss Avg_Gain Avg_Loss RS RSI
0 44 NaN 0.0 0.0 0.000000 0.000000 NaN NaN
1 45 1.0 1.0 0.0 0.500000 0.000000 inf 100.000000
2 46 1.0 1.0 0.0 0.666667 0.000000 inf 100.000000
3 45 -1.0 0.0 1.0 0.500000 0.250000 2.000000 66.666667
4 44 -1.0 0.0 1.0 0.400000 0.400000 1.000000 50.000000
5 43 -1.0 0.0 1.0 0.333333 0.500000 0.666667 40.000000
6 44 1.0 1.0 0.0 0.428571 0.428571 1.000000 50.000000
7 45 1.0 1.0 0.0 0.500000 0.375000 1.333333 57.142857
8 46 1.0 1.0 0.0 0.555556 0.333333 1.666667 62.500000
9 47 1.0 1.0 0.0 0.600000 0.300000 2.000000 66.666667
10 48 1.0 1.0 0.0 0.636364 0.272727 2.333333 70.000000
11 47 -1.0 0.0 1.0 0.583333 0.333333 1.750000 63.636364
12 46 -1.0 0.0 1.0 0.538462 0.384615 1.400000 58.333333
13 45 -1.0 0.0 1.0 0.500000 0.428571 1.166667 53.846154
The latest RSI value is: 53.85
```
```python
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# Sample closing prices and RSI values
closing_prices = data['Close']
rsi_values = data['RSI']
dates = pd.date_range(start='2023-01-01', periods=len(closing_prices), freq='D')
# Convert closing prices and RSI values to a pandas DataFrame
data = pd.DataFrame({'Date': dates, 'Close': closing_prices, 'RSI': rsi_values})
data.set_index('Date', inplace=True)
# Create figure and gridspec
fig = plt.figure(figsize=(10, 8))
gs = gridspec.GridSpec(2, 1, height_ratios=[8, 2])
# Plot Closing Prices
ax0 = plt.subplot(gs[0])
ax0.plot(data.index, data['Close'], marker='o', linestyle='-', color='b', label='Closing Prices')
ax0.set_title('Stock Closing Prices Over Time', fontsize=16)
ax0.set_ylabel('Closing Price', fontsize=14)
ax0.grid(True, linestyle='--', alpha=0.6)
ax0.legend(fontsize=12)
ax0.tick_params(axis='both', which='major', labelsize=12)
# Annotate specific points if needed
max_price = data['Close'].max()
max_date = data['Close'].idxmax()
ax0.annotate(f'Max Price: {max_price}', xy=(max_date, max_price), xytext=(max_date, max_price + 1),
arrowprops=dict(facecolor='black', shrink=0.05), fontsize=12)
# Plot RSI
ax1 = plt.subplot(gs[1], sharex=ax0)
ax1.plot(data.index, data['RSI'], marker='o', linestyle='-', color='r', label='RSI')
ax1.set_title('Relative Strength Index (RSI)', fontsize=16)
ax1.set_xlabel('Date', fontsize=14)
ax1.set_ylabel('RSI', fontsize=14)
ax1.axhline(70, color='gray', linestyle='--', alpha=0.7) # Overbought line
ax1.axhline(30, color='gray', linestyle='--', alpha=0.7) # Oversold line
ax1.grid(True, linestyle='--', alpha=0.6)
ax1.legend(fontsize=12)
ax1.tick_params(axis='both', which='major', labelsize=12)
# Adjust layout
plt.tight_layout()
# Save the figure
plt.savefig('publication_ready_plot_with_rsi.png', dpi=300)
# Show the plot
plt.show()
```
![[price-rsi-plot.png]]
## Q&A
### RSI > 70
**Q:** **If the RSI is above 70, doesn’t that indicate high demand?** Shouldn’t the price continue to rise if demand is strong? Why is it more likely for the price to decline when the RSI is over 70?
**A:**
When the RSI (Relative Strength Index) is above 70, it indeed indicates that the stock has experienced significant buying pressure, which is often associated with high demand. However, this also means the stock is in an "overbought" condition. While high demand usually drives prices up, an RSI above 70 suggests that the price may have risen too quickly and could be overextended. At this point, the stock might be seen as overvalued, leading some traders to start taking profits, which can introduce selling pressure.
As a result, even though demand was strong enough to push the RSI above 70, the market could shift towards a pullback or consolidation. This is because after a period of intense buying, there may be fewer new buyers willing to enter at these higher prices, while sellers might dominate as they seek to lock in gains. Therefore, the high RSI signals that the stock might be more vulnerable to a price decline rather than continuing its upward trend.