2024-10-29 19:57:38 +00:00
|
|
|
import numpy as np
|
|
|
|
|
|
|
|
from pandas import DataFrame, Series
|
|
|
|
|
2024-11-11 17:38:12 +00:00
|
|
|
from daily_data import get_daily_data
|
2024-10-29 19:57:38 +00:00
|
|
|
|
|
|
|
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 VIX RSI strategy.
|
|
|
|
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()
|
2024-11-11 17:38:12 +00:00
|
|
|
vix_data = get_daily_data(symbol = 'VIX.XO', start_date = start_date, end_date = end_date)
|
2024-10-29 19:57:38 +00:00
|
|
|
|
|
|
|
vix_rsi_2 = calculate_rsi(vix_data, period = 2)
|
|
|
|
|
|
|
|
above_200_ma = data['Close'] > ma_200
|
|
|
|
vix_rsi_above_90 = vix_rsi_2 > 90
|
|
|
|
vix_open_greater_than_prev_close = vix_data['Open'] > vix_data['Close'].shift(1)
|
|
|
|
rsi_below_30 = rsi_2 < 30
|
|
|
|
|
|
|
|
signals = Series('N', index = data.index)
|
|
|
|
signals[above_200_ma & vix_rsi_above_90 & vix_open_greater_than_prev_close & rsi_below_30] = 'L'
|
|
|
|
|
|
|
|
return signals
|