futureish 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- futureish/__init__.py +13 -0
- futureish/_internal/__init__.py +1 -0
- futureish/_internal/constants.py +7 -0
- futureish/_internal/dummy.py +30 -0
- futureish/_internal/repr.py +257 -0
- futureish/catboost/__init__.py +12 -0
- futureish/catboost/model.py +141 -0
- futureish/datapoints/__init__.py +5 -0
- futureish/datapoints/base.py +24 -0
- futureish/datapoints/recorded.py +23 -0
- futureish/datapoints/time.py +12 -0
- futureish/datasets/__init__.py +19 -0
- futureish/datasets/base.py +322 -0
- futureish/datasets/config.py +394 -0
- futureish/datasets/dataset.py +69 -0
- futureish/datasets/forecast.py +109 -0
- futureish/datasets/online.py +73 -0
- futureish/datasets/online_training.py +69 -0
- futureish/datasets/predict.py +118 -0
- futureish/datasets/test.py +21 -0
- futureish/datasets/train.py +32 -0
- futureish/features/__init__.py +19 -0
- futureish/features/base.py +95 -0
- futureish/features/bucket.py +154 -0
- futureish/features/businessday.py +56 -0
- futureish/features/input_base.py +130 -0
- futureish/features/modular.py +91 -0
- futureish/features/recorded.py +86 -0
- futureish/features/recorded_base.py +68 -0
- futureish/features/sincos_time.py +93 -0
- futureish/features/sparse.py +95 -0
- futureish/features/target.py +78 -0
- futureish/forecasting/__init__.py +6 -0
- futureish/forecasting/forecaster.py +126 -0
- futureish/forecasting/inference.py +389 -0
- futureish/gpr/__init__.py +22 -0
- futureish/gpr/gpytorch/__init__.py +15 -0
- futureish/gpr/gpytorch/backends/__init__.py +4 -0
- futureish/gpr/gpytorch/backends/gpytorch_model.py +136 -0
- futureish/gpr/gpytorch/backends/gpytorch_sgp.py +52 -0
- futureish/gpr/gpytorch/backends/gpytorch_vgp.py +46 -0
- futureish/gpr/gpytorch/backends/online_pep/__init__.py +5 -0
- futureish/gpr/gpytorch/backends/online_pep/gpytorch_online_pep.py +113 -0
- futureish/gpr/gpytorch/backends/online_pep/osgpr_pep.py +276 -0
- futureish/gpr/gpytorch/backends/online_pep/pep_compute_base.py +171 -0
- futureish/gpr/gpytorch/backends/online_pep/sgpr_pep.py +107 -0
- futureish/gpr/gpytorch/gpytorch_model_trainer.py +242 -0
- futureish/modeling/__init__.py +7 -0
- futureish/modeling/base.py +153 -0
- futureish/modeling/config.py +21 -0
- futureish/scaling/__init__.py +13 -0
- futureish/scaling/base.py +38 -0
- futureish/scaling/chained.py +142 -0
- futureish/scaling/data.py +54 -0
- futureish/scaling/difference.py +37 -0
- futureish/scaling/noop.py +35 -0
- futureish/scaling/z_score.py +35 -0
- futureish/utils/__init__.py +8 -0
- futureish/utils/polars.py +246 -0
- futureish/utils/timedelta.py +285 -0
- futureish-0.1.0.dist-info/METADATA +225 -0
- futureish-0.1.0.dist-info/RECORD +63 -0
- futureish-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
from ..utils.timedelta import TimeDeltaOperator
|
|
2
|
+
|
|
3
|
+
from .config import DataConfig
|
|
4
|
+
from .._internal.constants import CONTIGUOUS_GROUP, TIME_CL
|
|
5
|
+
from ..features.base import FeaturesBase
|
|
6
|
+
from ..utils.polars import AnyFrame, FrameT, add_contiguous_group
|
|
7
|
+
from .._internal.repr import ReprMixin
|
|
8
|
+
from ..features.input_base import InputFeatureBase
|
|
9
|
+
from ..features.target import TargetFeature
|
|
10
|
+
|
|
11
|
+
import polars as pl
|
|
12
|
+
|
|
13
|
+
from datetime import datetime, timedelta
|
|
14
|
+
from typing import Any, Generator, Optional, Self, Sequence, TypeVar, Union
|
|
15
|
+
import warnings
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
TDatasetbase = TypeVar("TDatasetbase", bound="DatasetBase")
|
|
19
|
+
|
|
20
|
+
class DatasetBase(ReprMixin):
|
|
21
|
+
"""
|
|
22
|
+
Underlying base class for a dataset. This class is not meant to be used directly, but rather through a more specific subclass.
|
|
23
|
+
"""
|
|
24
|
+
expects_future_data_known: bool = False
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
raw_data: AnyFrame,
|
|
28
|
+
input_features: Sequence[InputFeatureBase],
|
|
29
|
+
target_features: Sequence[TargetFeature],
|
|
30
|
+
*,
|
|
31
|
+
debug: bool = False,
|
|
32
|
+
):
|
|
33
|
+
raise NotImplementedError("DatasetBase is an abstract class and cannot be instantiated directly. Use a create with config or use a subclass of DatasetBase instead.")
|
|
34
|
+
|
|
35
|
+
def _initialize(self, raw_data: AnyFrame, input_features: Sequence[InputFeatureBase], target_features: Sequence[TargetFeature], debug: bool = False):
|
|
36
|
+
time_column_dtype = raw_data.collect_schema().get("time")
|
|
37
|
+
if time_column_dtype is None:
|
|
38
|
+
raise ValueError("Raw data must contain a 'time' column")
|
|
39
|
+
if not isinstance(time_column_dtype, pl.Datetime):
|
|
40
|
+
raise ValueError("Raw data 'time' column must be of type pl.Datetime")
|
|
41
|
+
config = DataConfig(input_features, target_features, time_column_dtype, debug=debug)
|
|
42
|
+
self._initialize_with_config(raw_data, config)
|
|
43
|
+
|
|
44
|
+
def _initialize_with_config(self, raw_data: AnyFrame, config: DataConfig) -> None:
|
|
45
|
+
self._valid_t0: Optional[pl.DataFrame] = None
|
|
46
|
+
self.config = config
|
|
47
|
+
self._data = self._prepare_raw_data(raw_data)
|
|
48
|
+
self._raw_data_len = self._data.height
|
|
49
|
+
|
|
50
|
+
@classmethod
|
|
51
|
+
def create_with_config(cls: type[Self], raw_data: AnyFrame, config: DataConfig) -> Self:
|
|
52
|
+
instance = cls.__new__(cls)
|
|
53
|
+
instance._initialize_with_config(raw_data, config)
|
|
54
|
+
|
|
55
|
+
return instance
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def _init_with_t0(cls: type[Self], raw_data: AnyFrame, config: DataConfig, valid_t0: pl.DataFrame) -> Self:
|
|
59
|
+
instance = cls.create_with_config(raw_data=raw_data, config=config)
|
|
60
|
+
assert valid_t0.columns == ["t0"], "valid_t0 DataFrame must have a single column named 't0'"
|
|
61
|
+
instance._valid_t0 = valid_t0
|
|
62
|
+
return instance
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def _repr_fields(self) -> dict[str, Any]:
|
|
66
|
+
return {
|
|
67
|
+
"config": self.config,
|
|
68
|
+
"raw_data_len": self._raw_data_len,
|
|
69
|
+
"valid_t0_len": self.valid_t0.height,
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def data(self) -> pl.DataFrame:
|
|
74
|
+
return self._data
|
|
75
|
+
|
|
76
|
+
def _create_contiguous_group_features(self, df: FrameT) -> FrameT:
|
|
77
|
+
recorded_datapoints = [f.base_datapoint for f in self.config.input_features] + [f.base_datapoint for f in self.config.target_features]
|
|
78
|
+
df_reduced = add_contiguous_group(df, recorded_datapoints)
|
|
79
|
+
return df_reduced
|
|
80
|
+
|
|
81
|
+
def data_with_contiguous_group(self) -> pl.LazyFrame:
|
|
82
|
+
return self._create_contiguous_group_features(self.data.lazy())
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def valid_t0(self) -> pl.DataFrame:
|
|
86
|
+
if self._valid_t0 is None:
|
|
87
|
+
self._valid_t0 = self._calc_valid_t0()
|
|
88
|
+
if self._valid_t0.height <= 0:
|
|
89
|
+
raise ValueError("No valid prediction times found. Check your input data and step size.")
|
|
90
|
+
return self._valid_t0
|
|
91
|
+
|
|
92
|
+
def has_valid_t0(self) -> bool:
|
|
93
|
+
if not self._valid_t0 is None:
|
|
94
|
+
return self._valid_t0.height > 0
|
|
95
|
+
|
|
96
|
+
_valid_t0 = self._calc_valid_t0()
|
|
97
|
+
if _valid_t0.height > 0:
|
|
98
|
+
self._valid_t0 = _valid_t0
|
|
99
|
+
return True
|
|
100
|
+
else:
|
|
101
|
+
return False
|
|
102
|
+
|
|
103
|
+
def data_with_valid_t0(self) -> pl.LazyFrame:
|
|
104
|
+
return self.data.lazy().join(
|
|
105
|
+
self.valid_t0.lazy(),
|
|
106
|
+
left_on="time",
|
|
107
|
+
right_on="t0",
|
|
108
|
+
how="left",
|
|
109
|
+
coalesce=False
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
def _prepare_raw_data(self, raw_data: AnyFrame) -> pl.DataFrame:
|
|
113
|
+
if isinstance(raw_data, pl.LazyFrame):
|
|
114
|
+
raw_data = raw_data.collect()
|
|
115
|
+
|
|
116
|
+
if "time" not in raw_data.columns:
|
|
117
|
+
raise ValueError("Raw data must contain a 'time' column")
|
|
118
|
+
|
|
119
|
+
if CONTIGUOUS_GROUP in raw_data.columns:
|
|
120
|
+
raise ValueError(f"Raw data already contains '{CONTIGUOUS_GROUP}' column, which is reserved for internal use")
|
|
121
|
+
|
|
122
|
+
if raw_data.height <= 0:
|
|
123
|
+
raise ValueError("Raw data is empty")
|
|
124
|
+
|
|
125
|
+
all_features_base_names = self.config.all_features_base_names
|
|
126
|
+
|
|
127
|
+
if not all(f in raw_data.columns for f in all_features_base_names):
|
|
128
|
+
missing_features = [f for f in all_features_base_names if f not in raw_data.columns]
|
|
129
|
+
raise ValueError(f"Raw data is missing required feature columns: {missing_features}")
|
|
130
|
+
|
|
131
|
+
raw_data = raw_data.select(
|
|
132
|
+
"time",
|
|
133
|
+
*[pl.col(c).cast(pl.Float64) for c in all_features_base_names if c != "time"]
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
raw_data = raw_data.sort("time")
|
|
137
|
+
|
|
138
|
+
return raw_data
|
|
139
|
+
|
|
140
|
+
def _calc_valid_t0(self) -> pl.DataFrame:
|
|
141
|
+
if self.expects_future_data_known or self.config.input_uses_future_data():
|
|
142
|
+
return self._calc_valid_t_start(self.config.step_size.to_string()).collect()
|
|
143
|
+
else:
|
|
144
|
+
return self._calc_valid_t_start().collect()
|
|
145
|
+
|
|
146
|
+
def _calc_valid_t_start(self, pred_len: Optional[str] = None) -> pl.LazyFrame:
|
|
147
|
+
pred_len_op = TimeDeltaOperator(pred_len)
|
|
148
|
+
times = (
|
|
149
|
+
self
|
|
150
|
+
.data_with_contiguous_group()
|
|
151
|
+
.drop_nulls([f.base_datapoint.name for f in self.config.target_features])
|
|
152
|
+
.select(
|
|
153
|
+
TIME_CL.filter(
|
|
154
|
+
pl.all_horizontal(
|
|
155
|
+
TIME_CL >= self.config.longest_input_length.offset_column_forward(TIME_CL.min()),
|
|
156
|
+
TIME_CL <= pred_len_op.offset_column_backward(TIME_CL.max()),
|
|
157
|
+
).over(CONTIGUOUS_GROUP)
|
|
158
|
+
).alias("t0")
|
|
159
|
+
)
|
|
160
|
+
.sort("t0")
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
return times
|
|
164
|
+
|
|
165
|
+
def _init_scaling(self, scale_df: AnyFrame) -> None:
|
|
166
|
+
self.config = self.config.fitted(scale_df)
|
|
167
|
+
|
|
168
|
+
def split(self: TDatasetbase, split_expr: Union[float, str, timedelta, int]) -> tuple[TDatasetbase, TDatasetbase]:
|
|
169
|
+
split_time = self._split_expr_to_time(split_expr)
|
|
170
|
+
before_data, after_data = self._split(split_time)
|
|
171
|
+
|
|
172
|
+
before_dataset = self.__class__.create_with_config(
|
|
173
|
+
raw_data=before_data,
|
|
174
|
+
config=self.config,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
after_dataset = self.__class__.create_with_config(
|
|
178
|
+
raw_data=after_data,
|
|
179
|
+
config=self.config,
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
return before_dataset, after_dataset
|
|
183
|
+
|
|
184
|
+
def _split(self, split_time: int, before_data_is_train: bool = False) -> tuple[pl.DataFrame, pl.DataFrame]:
|
|
185
|
+
if self.expects_future_data_known or self.config.input_uses_future_data() or before_data_is_train:
|
|
186
|
+
before_data = self.data.filter(TIME_CL.dt.offset_by("-" + self.config.step_size.to_string()).to_physical() <= pl.lit(split_time))
|
|
187
|
+
else:
|
|
188
|
+
before_data = self.data.filter(TIME_CL.to_physical() <= pl.lit(split_time))
|
|
189
|
+
|
|
190
|
+
after_data = self.data.filter(TIME_CL.dt.offset_by(self.config.longest_input_length.to_string()).to_physical() > pl.lit(split_time))
|
|
191
|
+
|
|
192
|
+
return before_data, after_data
|
|
193
|
+
|
|
194
|
+
def _split_expr_to_time(self, split_expr: Union[float, str, timedelta, int, TimeDeltaOperator]) -> int:
|
|
195
|
+
if isinstance(split_expr, float):
|
|
196
|
+
if not 0 < split_expr <= 1:
|
|
197
|
+
raise ValueError("split must be between 0 and 1")
|
|
198
|
+
data_len = self._raw_data_len
|
|
199
|
+
train_end_idx = int(data_len * split_expr)
|
|
200
|
+
train_end_idx = min(train_end_idx, data_len - 1)
|
|
201
|
+
train_end_idx = max(train_end_idx, 0)
|
|
202
|
+
train_end_time = self.data.select(TIME_CL.get(train_end_idx))
|
|
203
|
+
elif isinstance(split_expr, int): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
204
|
+
if split_expr < 0:
|
|
205
|
+
raise ValueError("split must be a non-negative integer")
|
|
206
|
+
if split_expr >= self._raw_data_len:
|
|
207
|
+
split_expr = self._raw_data_len - 1
|
|
208
|
+
|
|
209
|
+
train_end_time = self.data.select(
|
|
210
|
+
TIME_CL.get(split_expr)
|
|
211
|
+
)
|
|
212
|
+
else:
|
|
213
|
+
try:
|
|
214
|
+
split_expr = TimeDeltaOperator(split_expr)
|
|
215
|
+
except Exception as e:
|
|
216
|
+
raise ValueError("training_split must be a float, str, or timedelta or TimeDeltaOperator") from e
|
|
217
|
+
train_end_time = self.data.select(
|
|
218
|
+
split_expr.offset_column_forward(TIME_CL.min())
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
if train_end_time.height <= 0:
|
|
222
|
+
raise ValueError("No valid training split time found. Check your input data and step size.")
|
|
223
|
+
if train_end_time.height > 1:
|
|
224
|
+
raise ValueError("Multiple training split times found. Check your input data and step size.")
|
|
225
|
+
|
|
226
|
+
train_end_time = train_end_time.select(TIME_CL.to_physical()).item()
|
|
227
|
+
|
|
228
|
+
return train_end_time
|
|
229
|
+
|
|
230
|
+
def iter(self: TDatasetbase, step_size: Union[str, timedelta, int, TimeDeltaOperator]) -> Generator[TDatasetbase, None, None]:
|
|
231
|
+
return self._iter(step_size, self.__class__)
|
|
232
|
+
|
|
233
|
+
def _iter(self, step_size: Union[str, timedelta, int, TimeDeltaOperator], cls: type[TDatasetbase]) -> Generator[TDatasetbase, None, None]:
|
|
234
|
+
if isinstance(step_size, float):
|
|
235
|
+
raise ValueError(f"step_size must be a str, timedelta, or int, not a {type(step_size).__name__}")
|
|
236
|
+
|
|
237
|
+
while True:
|
|
238
|
+
end_time = self._split_expr_to_time(step_size)
|
|
239
|
+
chunk, remainder = self._split(end_time)
|
|
240
|
+
|
|
241
|
+
chunk_dataset = cls.create_with_config(
|
|
242
|
+
raw_data=chunk,
|
|
243
|
+
config=self.config,
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
# maybe a chunk without any valid t0
|
|
247
|
+
if chunk_dataset.has_valid_t0():
|
|
248
|
+
yield chunk_dataset
|
|
249
|
+
|
|
250
|
+
if remainder.height <= 0:
|
|
251
|
+
break
|
|
252
|
+
|
|
253
|
+
self = self.__class__.create_with_config(
|
|
254
|
+
raw_data=remainder,
|
|
255
|
+
config=self.config,
|
|
256
|
+
)
|
|
257
|
+
|
|
258
|
+
#no valid t0 left in the remainder, so we can stop iterating
|
|
259
|
+
if not self.has_valid_t0():
|
|
260
|
+
break
|
|
261
|
+
|
|
262
|
+
def random_subset(self: TDatasetbase, t0_count: int, pred_len: Optional[str] = None, random_seed: int = 42) -> TDatasetbase:
|
|
263
|
+
if t0_count <= 0:
|
|
264
|
+
raise ValueError("t0_count must be a positive integer")
|
|
265
|
+
|
|
266
|
+
if pred_len is None:
|
|
267
|
+
all_t0 = self.valid_t0 # pred_len would be set equal to self.config.step_size, so we can just use the cached valid_t0
|
|
268
|
+
else:
|
|
269
|
+
all_t0 = self._calc_valid_t_start(pred_len).collect()
|
|
270
|
+
|
|
271
|
+
if all_t0.height <= t0_count:
|
|
272
|
+
warnings.warn(f"t0_count {t0_count} is larger than the number of valid t0 {all_t0.height}")
|
|
273
|
+
t0_count = all_t0.height
|
|
274
|
+
|
|
275
|
+
subset_t0 = all_t0.sample(n=t0_count, with_replacement=False, seed=random_seed)
|
|
276
|
+
|
|
277
|
+
subset = self.__class__._init_with_t0(
|
|
278
|
+
raw_data=self.data,
|
|
279
|
+
config=self.config,
|
|
280
|
+
valid_t0=subset_t0,
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
return subset
|
|
284
|
+
|
|
285
|
+
def evaluate_corr(self) -> pl.DataFrame:
|
|
286
|
+
df = self.data_with_valid_t0()
|
|
287
|
+
|
|
288
|
+
features = self.config.create_XY(df)
|
|
289
|
+
|
|
290
|
+
if self.config.sub_features_names is None:
|
|
291
|
+
raise ValueError("sub_features_names must be set in the config to evaluate correlation")
|
|
292
|
+
|
|
293
|
+
corr = (
|
|
294
|
+
features
|
|
295
|
+
.select(
|
|
296
|
+
pl.col("X").arr.to_struct(self.config.sub_features_names).struct.unnest(),
|
|
297
|
+
*[
|
|
298
|
+
pl.col(f.feature_name).arr.first()
|
|
299
|
+
for f in self.config.target_features
|
|
300
|
+
]
|
|
301
|
+
)
|
|
302
|
+
.corr()
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
corr = (
|
|
306
|
+
corr
|
|
307
|
+
.select(
|
|
308
|
+
pl.Series("feature_name", corr.columns),
|
|
309
|
+
*[
|
|
310
|
+
pl.col(f.feature_name)
|
|
311
|
+
for f in self.config.target_features
|
|
312
|
+
]
|
|
313
|
+
)
|
|
314
|
+
.filter(
|
|
315
|
+
*[
|
|
316
|
+
pl.col("feature_name") != f.feature_name for f in self.config.target_features
|
|
317
|
+
]
|
|
318
|
+
)
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
return corr
|
|
322
|
+
|