From 3fe9b7aa5904bd625f256cd5d193949428da1e2d Mon Sep 17 00:00:00 2001 From: moshferatu Date: Sat, 26 Oct 2024 08:02:36 -0700 Subject: [PATCH] Add script for calculating the 2-period RSI and generating signals --- strategies/2_period_rsi.py | 41 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 strategies/2_period_rsi.py diff --git a/strategies/2_period_rsi.py b/strategies/2_period_rsi.py new file mode 100644 index 0000000..78b6ddb --- /dev/null +++ b/strategies/2_period_rsi.py @@ -0,0 +1,41 @@ +import pandas as pd +import numpy as np + +from datetime import datetime, timedelta +from ohlc import ohlc + +symbol = 'SPY' +today = datetime.today() +data = ohlc(symbol = symbol, start_date = today - timedelta(days = 365), end_date = today) + +def calculate_moving_average(data, window = 200): + data['200_MA'] = data['Close'].rolling(window = window).mean() + return data + +def calculate_rsi(data, period = 2): + 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 + rsi = 100 - (100 / (1 + rs)) + data['RSI_2'] = rsi + return data + +def generate_signals(data): + conditions = (data['Close'] > data['200_MA']) & (data['RSI_2'] < 5) + data['Signal'] = np.where(conditions, 'Long', 'None') + return data + +data['Date'] = pd.to_datetime(data['Date']) + +data = calculate_moving_average(data) +data = calculate_rsi(data) +data = generate_signals(data) + +print(data)