Add volatility regime filter for filtering out trades on days when the prior close of VIX is in the 75th percentile

This commit is contained in:
moshferatu 2024-02-06 07:30:24 -08:00
parent e688c3150f
commit e2781e5b9f
3 changed files with 41 additions and 0 deletions

View File

@ -0,0 +1 @@
from .volatility_regime_filter import VolatilityRegimeFilter

View File

@ -0,0 +1,36 @@
from datetime import datetime, timedelta
from dotenv import load_dotenv
from os import getenv
from pandas import DataFrame, Series
from database.ohlc import ohlc
from .backtest_filter import BacktestFilter
load_dotenv()
class VolatilityRegimeFilter(BacktestFilter):
def __init__(self):
self.backtest_filter = self.filter()
def filter(self) -> DataFrame:
data_start_date = datetime.strptime(getenv('OPTION_DATA_START_DATE'), '%Y-%m-%d')
vix_data = ohlc(
symbol = 'VIX.XO',
timeframe = '1d',
start_date = data_start_date - timedelta(weeks = 52),
end_date = datetime.now()
)
vix_data.rename(columns = {'Timestamp': 'Date'}, inplace = True)
vix_data['Date'] = vix_data['Date']
percent_rank = lambda x: Series(x).rank(pct = True).iloc[-1]
vix_data['Percent Rank'] = vix_data['Close'].shift(1).rolling(window = 252).apply(percent_rank)
filtered_data = vix_data[vix_data['Date'] >= data_start_date].copy()
filtered_data['Trade Allowed'] = filtered_data['Percent Rank'] < 0.75
filtered_data = filtered_data[['Date', 'Trade Allowed']].reset_index(drop = True)
return filtered_data

View File

@ -0,0 +1,4 @@
from backtesting.filter import VolatilityRegimeFilter
filter = VolatilityRegimeFilter()
print(filter.backtest_filter)