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:
parent
e688c3150f
commit
e2781e5b9f
1
backtesting/filter/__init__.py
Normal file
1
backtesting/filter/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
from .volatility_regime_filter import VolatilityRegimeFilter
|
36
backtesting/filter/volatility_regime_filter.py
Normal file
36
backtesting/filter/volatility_regime_filter.py
Normal 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
|
4
test/filter/volatility_regime_filter_test.py
Normal file
4
test/filter/volatility_regime_filter_test.py
Normal file
@ -0,0 +1,4 @@
|
||||
from backtesting.filter import VolatilityRegimeFilter
|
||||
|
||||
filter = VolatilityRegimeFilter()
|
||||
print(filter.backtest_filter)
|
Loading…
Reference in New Issue
Block a user