From f4c6fcd295dfa4ae847f61e86c274eb1b645daec Mon Sep 17 00:00:00 2001 From: moshferatu Date: Tue, 26 Nov 2024 07:51:47 -0800 Subject: [PATCH] Add script for generating IBS + RSI strategy signals --- strategies/ibs_rsi.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 strategies/ibs_rsi.py diff --git a/strategies/ibs_rsi.py b/strategies/ibs_rsi.py new file mode 100644 index 0000000..7873278 --- /dev/null +++ b/strategies/ibs_rsi.py @@ -0,0 +1,35 @@ +import numpy as np +import pandas as pd + +def calculate_rsi(data: pd.DataFrame, period: int = 21) -> pd.Series: + """ + Calculate the RSI for a given period and return it as a Series. + """ + delta = data['Close'].diff() + gain = np.where(delta > 0, delta, 0) + loss = np.where(delta < 0, -delta, 0) + + alpha = 1 / period + avg_gain = pd.Series(gain).ewm(alpha = alpha, adjust = False).mean() + avg_loss = pd.Series(loss).ewm(alpha = alpha, adjust = False).mean() + + rs = avg_gain / avg_loss + return 100 - (100 / (1 + rs)) + +def calculate_ibs(data: pd.DataFrame) -> pd.Series: + """ + Calculate the IBS and return it as a Series. + """ + return (data['Close'] - data['Low']) / (data['High'] - data['Low']) + +def signals(data: pd.DataFrame) -> pd.Series: + """ + Generate swing trading signals based on the IBS + RSI strategy. + + Returns a Series with 'L' for long signals and 'N' otherwise. + """ + ibs = calculate_ibs(data) + rsi_21 = calculate_rsi(data, period = 21) + + conditions = (ibs < 0.25) & (rsi_21 < 45) + return pd.Series(np.where(conditions, 'L', 'N'), index = data.index) \ No newline at end of file