Skip to content

Commit 94eec36

Browse files
authored
Create Relative Strength Index (RSI).py
1 parent 59ff87d commit 94eec36

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
from typing import List
2+
3+
def calculate_rsi(prices: List[float], period: int = 14) -> List[float]:
4+
"""
5+
Calculate the Relative Strength Index (RSI) for a given list of prices.
6+
7+
RSI is a momentum oscillator that measures the speed and change of price movements.
8+
It is typically used to identify overbought or oversold conditions in a market.
9+
10+
Args:
11+
prices (List[float]): A list of prices for a financial asset.
12+
period (int): The number of periods to use in the calculation (default is 14).
13+
14+
Returns:
15+
List[float]: A list of RSI values corresponding to the input price data.
16+
17+
Example:
18+
>>> calculate_rsi([44.0, 44.15, 44.09, 44.20, 44.30, 44.25, 44.40], 14)
19+
[100.0, 100.0, 100.0, 100.0, 100.0, 100.0]
20+
21+
Reference:
22+
https://en.wikipedia.org/wiki/Relative_strength_index
23+
"""
24+
25+
# Validate that there are enough prices to calculate RSI
26+
if len(prices) < period:
27+
raise ValueError("Not enough price data to calculate RSI.")
28+
29+
# Initialize lists to store gains and losses
30+
gains = []
31+
losses = []
32+
33+
# Calculate price changes between consecutive days
34+
for i in range(1, len(prices)):
35+
delta = prices[i] - prices[i - 1]
36+
37+
# Gain if delta is positive, otherwise it's a loss
38+
gains.append(max(0, delta))
39+
losses.append(max(0, -delta))
40+
41+
# Calculate the initial average gain and average loss (Simple Moving Average)
42+
avg_gain = sum(gains[:period]) / period
43+
avg_loss = sum(losses[:period]) / period
44+
45+
# Initialize the RSI list with the first calculated RSI value
46+
rsi_values = []
47+
48+
# First RSI value calculation
49+
if avg_loss == 0:
50+
rsi = 100 # No loss means RSI is 100 (overbought)
51+
else:
52+
rs = avg_gain / avg_loss # Relative Strength
53+
rsi = 100 - (100 / (1 + rs)) # RSI formula
54+
55+
rsi_values.append(rsi)
56+
57+
# Calculate the rest of the RSI values using smoothed moving averages
58+
for i in range(period, len(prices)):
59+
delta = prices[i] - prices[i - 1]
60+
61+
# Update gains and losses
62+
gain = max(0, delta)
63+
loss = max(0, -delta)
64+
65+
# Calculate smoothed averages
66+
avg_gain = (avg_gain * (period - 1) + gain) / period
67+
avg_loss = (avg_loss * (period - 1) + loss) / period
68+
69+
# Compute RSI
70+
if avg_loss == 0:
71+
rsi = 100
72+
else:
73+
rs = avg_gain / avg_loss
74+
rsi = 100 - (100 / (1 + rs))
75+
76+
# Append RSI value to list
77+
rsi_values.append(rsi)
78+
79+
return rsi_values
80+
81+
82+
# Example usage:
83+
if __name__ == "__main__":
84+
prices = [44.0, 44.15, 44.09, 44.20, 44.30, 44.25, 44.40, 44.35, 44.50, 44.60, 44.55, 44.75, 44.80, 44.70, 44.85]
85+
rsi = calculate_rsi(prices, 14)
86+
print("RSI Values:", rsi)

0 commit comments

Comments
 (0)