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)