From 2e3ed927da281d1c89a16bea369c8d37d2b17181 Mon Sep 17 00:00:00 2001 From: moshferatu Date: Mon, 28 Oct 2024 11:27:03 -0700 Subject: [PATCH] Add new 2-Period RSI signal generation script which follows the new expected strategy template --- strategies/two_period_rsi.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 strategies/two_period_rsi.py diff --git a/strategies/two_period_rsi.py b/strategies/two_period_rsi.py new file mode 100644 index 0000000..a55a3b4 --- /dev/null +++ b/strategies/two_period_rsi.py @@ -0,0 +1,35 @@ +import numpy as np + +from pandas import DataFrame, Series + +def calculate_moving_average(data: DataFrame, window: int = 200) -> Series: + """ + Calculate the 200-period moving average and return it as a Series without modifying the original DataFrame. + """ + return data['Close'].rolling(window = window).mean() + +def calculate_rsi(data: DataFrame, period: int = 2) -> Series: + """ + Calculate the 2-period RSI and return it as a Series without modifying the original DataFrame. + """ + delta = data['Close'].diff() + gain = np.where(delta > 0, delta, 0) + loss = np.where(delta < 0, -delta, 0) + + alpha = 1 / period + avg_gain = Series(gain).ewm(alpha = alpha, adjust = False).mean() + avg_loss = Series(loss).ewm(alpha = alpha, adjust = False).mean() + + rs = avg_gain / avg_loss + return 100 - (100 / (1 + rs)) + +def signals(data: DataFrame) -> Series: + """ + Calculate signals based on the 200-period MA and 2-period RSI. + Returns a Series with 'Long' for signals and 'None' otherwise, without modifying the original DataFrame. + """ + ma_200 = calculate_moving_average(data) + rsi_2 = calculate_rsi(data) + + conditions = (data['Close'] > ma_200) & (rsi_2 < 5) + return Series(np.where(conditions, 'Long', 'None'), index = data.index) \ No newline at end of file