Add script for generating TRIN swing trading strategy signals

This commit is contained in:
moshferatu 2024-10-30 00:23:40 -07:00
parent 47361429ad
commit 586a9ed607

46
strategies/trin.py Normal file
View File

@ -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