2022-03-02 00:26:33 +01:00
|
|
|
from data_loader.types import ReturnSeries
|
2022-01-26 23:22:43 +01:00
|
|
|
from ..types import EventLabeller, EventsDataFrame
|
|
|
|
|
import pandas as pd
|
2022-03-15 14:43:16 +01:00
|
|
|
from .utils import create_forward_returns, discretize_threeway_threshold
|
2022-03-03 17:40:17 +01:00
|
|
|
from typing import Callable
|
2022-01-26 23:22:43 +01:00
|
|
|
|
2022-02-17 19:22:17 +01:00
|
|
|
|
2022-01-26 23:22:43 +01:00
|
|
|
class FixedTimeHorionThreeClassBalancedEventLabeller(EventLabeller):
|
|
|
|
|
|
|
|
|
|
time_horizon: int
|
|
|
|
|
|
2022-02-17 16:36:35 +01:00
|
|
|
def __init__(self, time_horizon: int):
|
2022-01-26 23:22:43 +01:00
|
|
|
self.time_horizon = time_horizon
|
|
|
|
|
|
2022-02-17 19:22:17 +01:00
|
|
|
def label_events(
|
|
|
|
|
self, event_start_times: pd.DatetimeIndex, returns: ReturnSeries
|
2022-03-02 00:26:33 +01:00
|
|
|
) -> EventsDataFrame:
|
2022-01-26 23:22:43 +01:00
|
|
|
|
2022-02-17 16:36:35 +01:00
|
|
|
forward_returns = create_forward_returns(returns, self.time_horizon)
|
|
|
|
|
cutoff_point = returns.index[-self.time_horizon]
|
2022-03-12 13:27:44 +01:00
|
|
|
event_start_times = event_start_times[event_start_times < cutoff_point]
|
2022-01-26 23:22:43 +01:00
|
|
|
event_candidates = forward_returns[event_start_times]
|
|
|
|
|
|
|
|
|
|
def get_bins_threeway(x):
|
2022-02-17 19:22:17 +01:00
|
|
|
bins = pd.qcut(event_candidates, 3, retbins=True, duplicates="drop")[1]
|
2022-01-26 23:22:43 +01:00
|
|
|
|
|
|
|
|
if len(bins) != 4:
|
|
|
|
|
# if we don't have enough data for the quantiles, we'll need to add hard-coded values
|
|
|
|
|
lower_bound = bins[0]
|
|
|
|
|
upper_bound = bins[-1]
|
|
|
|
|
bins = [lower_bound] + [-0.02, 0.02] + [upper_bound]
|
|
|
|
|
return bins
|
2022-02-17 19:22:17 +01:00
|
|
|
|
2022-01-26 23:22:43 +01:00
|
|
|
bins = get_bins_threeway(event_candidates)
|
|
|
|
|
|
|
|
|
|
def map_class_threeway(current_value):
|
|
|
|
|
lower_threshold = bins[1]
|
|
|
|
|
upper_threshold = bins[2]
|
|
|
|
|
if current_value <= lower_threshold:
|
|
|
|
|
return -1
|
|
|
|
|
elif current_value > lower_threshold and current_value < upper_threshold:
|
|
|
|
|
return 0
|
|
|
|
|
else:
|
|
|
|
|
return 1
|
2022-02-17 19:22:17 +01:00
|
|
|
|
2022-01-26 23:22:43 +01:00
|
|
|
labels = event_candidates.map(map_class_threeway)
|
2022-03-02 00:26:33 +01:00
|
|
|
events = pd.DataFrame(
|
|
|
|
|
{
|
|
|
|
|
"start": event_start_times,
|
|
|
|
|
"end": event_start_times + pd.Timedelta(minutes=self.time_horizon * 5),
|
|
|
|
|
"label": labels,
|
|
|
|
|
"returns": forward_returns[event_start_times],
|
|
|
|
|
}
|
2022-02-17 19:22:17 +01:00
|
|
|
)
|
2022-03-02 00:26:33 +01:00
|
|
|
return events
|
2022-03-03 17:40:17 +01:00
|
|
|
|
|
|
|
|
def get_labels(self) -> list[int]:
|
|
|
|
|
return [-1, 0, 1]
|
|
|
|
|
|
|
|
|
|
def get_discretize_function(self) -> Callable:
|
2022-03-15 14:43:16 +01:00
|
|
|
return discretize_threeway_threshold(0.02)
|