diff --git a/strategies/trin.py b/strategies/trin.py new file mode 100644 index 0000000..2916fbc --- /dev/null +++ b/strategies/trin.py @@ -0,0 +1,46 @@ +import numpy as np + +from pandas import DataFrame, Series + +from ohlc import ohlc + +def calculate_rsi(data: DataFrame, period: int = 2) -> Series: + """ + Calculate the 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: + """ + Generate long signals based on the TRIN strategy with the following rules: + 1. SPY is above its 200-day moving average + 2. 2-period RSI is below 50 + 3. TRIN closes above 1 + + Returns a Series with 'L' for long signals and 'N' for no signal. + """ + ma_200 = data['Close'].rolling(window = 200).mean() + + rsi_2 = calculate_rsi(data, period = 2) + + start_date = data['Date'].min() + end_date = data['Date'].max() + trin_data = ohlc(symbol = 'RINT.Z', start_date = start_date, end_date = end_date) + + trin_above_1 = trin_data['Close'] > 1 + + above_200_ma = data['Close'] > ma_200 + rsi_below_50 = rsi_2 < 50 + + signals = Series('N', index = data.index) + signals[above_200_ma & rsi_below_50 & trin_above_1] = 'L' + return signals \ No newline at end of file