Spaces:
Runtime error
Runtime error
Create rsi.py
Browse files- indicators/rsi.py +42 -0
indicators/rsi.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pandas as pd
|
2 |
+
|
3 |
+
def calculate_rsi(prices, length=14, oversold=30, overbought=70):
|
4 |
+
"""
|
5 |
+
Calculates the Relative Strength Index (RSI) and marks the oversold and overbought conditions.
|
6 |
+
|
7 |
+
Parameters:
|
8 |
+
- prices (pd.Series): A pandas Series containing the stock's closing prices.
|
9 |
+
- length (int): The length of the RSI period. Defaults to 14.
|
10 |
+
- oversold (int): The level at which the asset is considered oversold. Defaults to 30.
|
11 |
+
- overbought (int): The level at which the asset is considered overbought. Defaults to 70.
|
12 |
+
|
13 |
+
Returns:
|
14 |
+
- pd.DataFrame: A DataFrame containing the RSI values, and flags for oversold and overbought conditions.
|
15 |
+
"""
|
16 |
+
delta = prices.diff()
|
17 |
+
gain = (delta.where(delta > 0, 0)).rolling(window=length).mean()
|
18 |
+
loss = (-delta.where(delta < 0, 0)).rolling(window=length).mean()
|
19 |
+
|
20 |
+
rs = gain / loss
|
21 |
+
rsi = 100 - (100 / (1 + rs))
|
22 |
+
|
23 |
+
rsi_df = pd.DataFrame(data={'RSI': rsi})
|
24 |
+
rsi_df['Oversold'] = rsi_df['RSI'] < oversold
|
25 |
+
rsi_df['Overbought'] = rsi_df['RSI'] > overbought
|
26 |
+
|
27 |
+
return rsi_df
|
28 |
+
|
29 |
+
if __name__ == "__main__":
|
30 |
+
# Example usage
|
31 |
+
data = {'Close': [22, 24, 23, 25, 26, 28, 27, 29, 30, 32, 31, 33]}
|
32 |
+
prices = pd.Series(data['Close'])
|
33 |
+
|
34 |
+
# User-defined parameters for RSI
|
35 |
+
length = 14 # RSI period
|
36 |
+
oversold = 30 # Oversold threshold
|
37 |
+
overbought = 70 # Overbought threshold
|
38 |
+
|
39 |
+
# Calculate RSI
|
40 |
+
rsi_df = calculate_rsi(prices, length, oversold, overbought)
|
41 |
+
|
42 |
+
print(rsi_df)
|