diff --git a/backtesting/filter/__init__.py b/backtesting/filter/__init__.py new file mode 100644 index 0000000..17eb721 --- /dev/null +++ b/backtesting/filter/__init__.py @@ -0,0 +1 @@ +from .volatility_regime_filter import VolatilityRegimeFilter \ No newline at end of file diff --git a/backtesting/filter/volatility_regime_filter.py b/backtesting/filter/volatility_regime_filter.py new file mode 100644 index 0000000..1cc1b67 --- /dev/null +++ b/backtesting/filter/volatility_regime_filter.py @@ -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 \ No newline at end of file diff --git a/test/filter/volatility_regime_filter_test.py b/test/filter/volatility_regime_filter_test.py new file mode 100644 index 0000000..75fa8fd --- /dev/null +++ b/test/filter/volatility_regime_filter_test.py @@ -0,0 +1,4 @@ +from backtesting.filter import VolatilityRegimeFilter + +filter = VolatilityRegimeFilter() +print(filter.backtest_filter) \ No newline at end of file