|
| 1 | +def calculate_rsi(prices: list[float], period: int = 14) -> list[float]: |
| 2 | + """ |
| 3 | + Calculate the Relative Strength Index (RSI) for a given list of prices. |
| 4 | +
|
| 5 | + RSI is a momentum oscillator that measures the speed and change of price movements. |
| 6 | + It is typically used to identify overbought or oversold conditions in a market. |
| 7 | +
|
| 8 | + Args: |
| 9 | + prices (list[float]): A list of prices for a financial asset. |
| 10 | + period (int): The number of periods to use in the calculation (default is 14). |
| 11 | +
|
| 12 | + Returns: |
| 13 | + list[float]: A list of RSI values corresponding to the input price data. |
| 14 | +
|
| 15 | + Example: |
| 16 | + >>> calculate_rsi([44.0, 44.15, 44.09, 44.20, 44.30, 44.25, 44.40], 14) |
| 17 | + [100.0, 100.0, 100.0, 100.0, 100.0, 100.0] |
| 18 | +
|
| 19 | + Reference: |
| 20 | + https://en.wikipedia.org/wiki/Relative_strength_index |
| 21 | + """ |
| 22 | + # Validate that there are enough prices to calculate RSI |
| 23 | + if len(prices) < period: |
| 24 | + raise ValueError("Not enough price data to calculate RSI.") |
| 25 | + |
| 26 | + gains = [] |
| 27 | + losses = [] |
| 28 | + |
| 29 | + # Calculate price changes between consecutive days |
| 30 | + for i in range(1, len(prices)): |
| 31 | + delta = prices[i] - prices[i - 1] |
| 32 | + gains.append(max(0, delta)) |
| 33 | + losses.append(max(0, -delta)) |
| 34 | + |
| 35 | + # Initial averages for gain and loss |
| 36 | + avg_gain = float(sum(gains[:period]) / period) |
| 37 | + avg_loss = float(sum(losses[:period]) / period) |
| 38 | + |
| 39 | + # Initialize RSI list and first RSI value |
| 40 | + rsi_values: list[float] = [] |
| 41 | + |
| 42 | + if avg_loss == 0: |
| 43 | + rsi = 100.0 |
| 44 | + else: |
| 45 | + rs = avg_gain / avg_loss |
| 46 | + rsi = 100.0 - (100.0 / (1.0 + rs)) |
| 47 | + |
| 48 | + rsi_values.append(rsi) |
| 49 | + |
| 50 | + # Calculate subsequent RSI values |
| 51 | + for i in range(period, len(prices)): |
| 52 | + delta = prices[i] - prices[i - 1] |
| 53 | + gain = max(0, delta) |
| 54 | + loss = max(0, -delta) |
| 55 | + |
| 56 | + avg_gain = (avg_gain * (period - 1) + gain) / period |
| 57 | + avg_loss = (avg_loss * (period - 1) + loss) / period |
| 58 | + |
| 59 | + if avg_loss == 0: |
| 60 | + rsi = 100.0 |
| 61 | + else: |
| 62 | + rs = avg_gain / avg_loss |
| 63 | + rsi = 100.0 - (100.0 / (1.0 + rs)) |
| 64 | + |
| 65 | + rsi_values.append(rsi) |
| 66 | + |
| 67 | + return rsi_values |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == "__main__": |
| 71 | + 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] |
| 72 | + rsi = calculate_rsi(prices, 14) |
| 73 | + print("RSI Values:", rsi) |
0 commit comments