spotforecast2 0.1.0__py3-none-any.whl → 0.1.1__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.
@@ -1,43 +1,308 @@
1
+ """
2
+ End-to-end baseline forecasting using equivalent date method.
3
+
4
+ This module provides a complete forecasting pipeline using the ForecasterEquivalentDate
5
+ baseline model. It handles data preparation, outlier detection, imputation, model
6
+ training, and prediction in a single integrated function.
7
+
8
+ Model persistence follows scikit-learn conventions using joblib for efficient
9
+ serialization and deserialization of trained forecasters.
10
+
11
+ Examples:
12
+ Basic usage with default parameters:
13
+
14
+ >>> from spotforecast2.processing.n2n_predict import n2n_predict
15
+ >>> predictions = n2n_predict(forecast_horizon=24, verbose=True)
16
+
17
+ Using cached models:
18
+
19
+ >>> # Load existing models if available, or train new ones
20
+ >>> predictions = n2n_predict(
21
+ ... forecast_horizon=24,
22
+ ... force_train=False,
23
+ ... model_dir="./models",
24
+ ... verbose=True
25
+ ... )
26
+
27
+ Force retraining and update cache:
28
+
29
+ >>> predictions = n2n_predict(
30
+ ... forecast_horizon=24,
31
+ ... force_train=True,
32
+ ... model_dir="./models",
33
+ ... verbose=True
34
+ ... )
35
+ """
36
+
37
+ from pathlib import Path
38
+ from typing import Dict, List, Optional, Tuple, Union
39
+
1
40
  import pandas as pd
2
- from typing import List, Optional
3
41
  from spotforecast2.forecaster.recursive import ForecasterEquivalentDate
4
42
  from spotforecast2.data.fetch_data import fetch_data
5
43
  from spotforecast2.preprocessing.curate_data import basic_ts_checks
6
44
  from spotforecast2.preprocessing.curate_data import agg_and_resample_data
7
45
  from spotforecast2.preprocessing.outlier import mark_outliers
8
-
9
46
  from spotforecast2.preprocessing.split import split_rel_train_val_test
10
47
  from spotforecast2.forecaster.utils import predict_multivariate
11
48
  from spotforecast2.preprocessing.curate_data import get_start_end
12
49
 
50
+ try:
51
+ from joblib import dump, load
52
+ except ImportError:
53
+ raise ImportError("joblib is required. Install with: pip install joblib")
54
+
13
55
  try:
14
56
  from tqdm.auto import tqdm
15
57
  except ImportError: # pragma: no cover - fallback when tqdm is not installed
16
58
  tqdm = None
17
59
 
18
60
 
61
+ # ============================================================================
62
+ # Model Persistence Functions
63
+ # ============================================================================
64
+
65
+
66
+ def _ensure_model_dir(model_dir: Union[str, Path]) -> Path:
67
+ """Ensure model directory exists.
68
+
69
+ Args:
70
+ model_dir: Directory path for model storage.
71
+
72
+ Returns:
73
+ Path: Validated Path object.
74
+
75
+ Raises:
76
+ OSError: If directory cannot be created.
77
+ """
78
+ model_path = Path(model_dir)
79
+ model_path.mkdir(parents=True, exist_ok=True)
80
+ return model_path
81
+
82
+
83
+ def _get_model_filepath(model_dir: Path, target: str) -> Path:
84
+ """Get filepath for a single model.
85
+
86
+ Args:
87
+ model_dir: Directory containing models.
88
+ target: Target variable name.
89
+
90
+ Returns:
91
+ Path: Full filepath for the model.
92
+
93
+ Examples:
94
+ >>> path = _get_model_filepath(Path("./models"), "power")
95
+ >>> str(path)
96
+ './models/forecaster_power.joblib'
97
+ """
98
+ return model_dir / f"forecaster_{target}.joblib"
99
+
100
+
101
+ def _save_forecasters(
102
+ forecasters: Dict[str, object],
103
+ model_dir: Union[str, Path],
104
+ verbose: bool = False,
105
+ ) -> Dict[str, Path]:
106
+ """Save trained forecasters to disk using joblib.
107
+
108
+ Follows scikit-learn persistence conventions using joblib for efficient
109
+ serialization of sklearn-compatible estimators.
110
+
111
+ Args:
112
+ forecasters: Dictionary mapping target names to trained ForecasterEquivalentDate objects.
113
+ model_dir: Directory to save models. Created if it doesn't exist.
114
+ verbose: Print progress messages. Default: False.
115
+
116
+ Returns:
117
+ Dict[str, Path]: Dictionary mapping target names to saved model filepaths.
118
+
119
+ Raises:
120
+ OSError: If models cannot be written to disk.
121
+ TypeError: If forecasters contain non-serializable objects.
122
+
123
+ Examples:
124
+ >>> forecasters = {"power": forecaster_obj}
125
+ >>> paths = _save_forecasters(forecasters, "./models", verbose=True)
126
+ >>> print(paths["power"])
127
+ models/forecaster_power.joblib
128
+ """
129
+ model_path = _ensure_model_dir(model_dir)
130
+ saved_paths = {}
131
+
132
+ for target, forecaster in forecasters.items():
133
+ filepath = _get_model_filepath(model_path, target)
134
+ try:
135
+ dump(forecaster, filepath, compress=3)
136
+ saved_paths[target] = filepath
137
+ if verbose:
138
+ print(f" ✓ Saved forecaster for {target} to {filepath}")
139
+ except Exception as e:
140
+ raise OSError(f"Failed to save model for {target}: {e}")
141
+
142
+ return saved_paths
143
+
144
+
145
+ def _load_forecasters(
146
+ target_columns: List[str],
147
+ model_dir: Union[str, Path],
148
+ verbose: bool = False,
149
+ ) -> Tuple[Dict[str, object], List[str]]:
150
+ """Load trained forecasters from disk using joblib.
151
+
152
+ Attempts to load all forecasters for given targets. Missing models
153
+ are indicated in the return value for selective retraining.
154
+
155
+ Args:
156
+ target_columns: List of target variable names to load.
157
+ model_dir: Directory containing saved models.
158
+ verbose: Print progress messages. Default: False.
159
+
160
+ Returns:
161
+ Tuple[Dict[str, object], List[str]]:
162
+ - forecasters: Dictionary of successfully loaded ForecasterEquivalentDate objects.
163
+ - missing_targets: List of target names without saved models.
164
+
165
+ Examples:
166
+ >>> forecasters, missing = _load_forecasters(
167
+ ... ["power", "energy"],
168
+ ... "./models",
169
+ ... verbose=True
170
+ ... )
171
+ >>> print(missing)
172
+ ['energy']
173
+ """
174
+ model_path = Path(model_dir)
175
+ forecasters = {}
176
+ missing_targets = []
177
+
178
+ for target in target_columns:
179
+ filepath = _get_model_filepath(model_path, target)
180
+ if filepath.exists():
181
+ try:
182
+ forecasters[target] = load(filepath)
183
+ if verbose:
184
+ print(f" ✓ Loaded forecaster for {target} from {filepath}")
185
+ except Exception as e:
186
+ if verbose:
187
+ print(f" ✗ Failed to load {target}: {e}")
188
+ missing_targets.append(target)
189
+ else:
190
+ missing_targets.append(target)
191
+
192
+ return forecasters, missing_targets
193
+
194
+
195
+ def _model_directory_exists(model_dir: Union[str, Path]) -> bool:
196
+ """Check if model directory exists.
197
+
198
+ Args:
199
+ model_dir: Directory path to check.
200
+
201
+ Returns:
202
+ bool: True if directory exists, False otherwise.
203
+ """
204
+ return Path(model_dir).exists()
205
+
206
+
207
+ # ============================================================================
208
+ # Main Function
209
+ # ============================================================================
210
+
211
+
19
212
  def n2n_predict(
20
213
  columns: Optional[List[str]] = None,
21
214
  forecast_horizon: int = 24,
22
215
  contamination: float = 0.01,
23
216
  window_size: int = 72,
217
+ force_train: bool = False,
218
+ model_dir: Union[str, Path] = "./models_baseline",
24
219
  verbose: bool = True,
25
220
  show_progress: bool = True,
26
- ) -> pd.DataFrame:
27
- """
28
- End-to-end prediction function replicating the workflow from 01_base_predictor combined with fetch_data.
221
+ ) -> Tuple[pd.DataFrame, Dict]:
222
+ """End-to-end baseline forecasting using equivalent date method.
223
+
224
+ This function implements a complete forecasting pipeline that:
225
+ 1. Loads and validates target data
226
+ 2. Detects and removes outliers
227
+ 3. Imputes missing values
228
+ 4. Splits into train/validation/test sets
229
+ 5. Trains or loads equivalent date forecasters
230
+ 6. Generates multi-step ahead predictions
231
+
232
+ Models are persisted to disk following scikit-learn conventions using joblib.
233
+ Existing models are reused for prediction unless force_train=True.
29
234
 
30
235
  Args:
31
- columns: List of target columns to forecast. If None, uses a default set (defined internally or from data).
32
- Note: fetch_data supports None to return all columns.
33
- forecast_horizon: Number of steps to forecast.
34
- contamination: Contamination factor for outlier detection.
35
- window_size: Window size for weighting (not fully utilized in main flow but kept for consistency).
36
- verbose: Whether to print progress logs.
37
- show_progress: Show progress bar during training and prediction.
236
+ columns: List of target columns to forecast. If None, uses all available columns.
237
+ Default: None.
238
+ forecast_horizon: Number of time steps to forecast ahead. Default: 24.
239
+ contamination: Contamination parameter for outlier detection. Default: 0.01.
240
+ window_size: Rolling window size for gap detection. Default: 72.
241
+ force_train: Force retraining of all models, ignoring cached models.
242
+ Default: False.
243
+ model_dir: Directory for saving/loading trained models.
244
+ Default: "./models_baseline".
245
+ verbose: Print progress messages. Default: True.
246
+ show_progress: Show progress bar during training and prediction. Default: True.
38
247
 
39
248
  Returns:
40
- pd.DataFrame: The multi-output predictions.
249
+ Tuple containing:
250
+ - predictions: DataFrame with forecast values for each target variable.
251
+ - forecasters: Dictionary of trained ForecasterEquivalentDate objects keyed by target.
252
+
253
+ Raises:
254
+ ValueError: If data validation fails or required data cannot be retrieved.
255
+ ImportError: If required dependencies are not installed.
256
+ OSError: If models cannot be saved to disk.
257
+
258
+ Examples:
259
+ Basic usage with automatic model caching:
260
+
261
+ >>> predictions, forecasters = n2n_predict(
262
+ ... forecast_horizon=24,
263
+ ... verbose=True
264
+ ... )
265
+ >>> print(predictions.shape)
266
+ (24, 11)
267
+
268
+ Load cached models (if available):
269
+
270
+ >>> predictions, forecasters = n2n_predict(
271
+ ... forecast_horizon=24,
272
+ ... force_train=False,
273
+ ... model_dir="./saved_models",
274
+ ... verbose=True
275
+ ... )
276
+
277
+ Force retraining and update cache:
278
+
279
+ >>> predictions, forecasters = n2n_predict(
280
+ ... forecast_horizon=24,
281
+ ... force_train=True,
282
+ ... model_dir="./saved_models",
283
+ ... verbose=True
284
+ ... )
285
+
286
+ With specific target columns:
287
+
288
+ >>> predictions, forecasters = n2n_predict(
289
+ ... columns=["power", "energy"],
290
+ ... forecast_horizon=48,
291
+ ... force_train=False,
292
+ ... verbose=True
293
+ ... )
294
+
295
+ Notes:
296
+ - Trained models are saved to disk using joblib for fast reuse.
297
+ - When force_train=False, existing models are loaded and prediction
298
+ proceeds without retraining. This significantly speeds up prediction
299
+ for repeated calls with the same configuration.
300
+ - The model_dir directory is created automatically if it doesn't exist.
301
+
302
+ Performance Notes:
303
+ - First run: Full training (~2-5 minutes depending on data size)
304
+ - Subsequent runs (force_train=False): Model loading only (~1-2 seconds)
305
+ - Force retrain (force_train=True): Full training again (~2-5 minutes)
41
306
  """
42
307
  if columns is not None:
43
308
  TARGET = columns
@@ -98,20 +363,66 @@ def n2n_predict(
98
363
  end_validation = pd.concat([data_train, data_val]).index[-1]
99
364
 
100
365
  baseline_forecasters = {}
366
+ targets_to_train = list(data.columns)
367
+
368
+ # Attempt to load cached models if force_train=False
369
+ if not force_train and _model_directory_exists(model_dir):
370
+ if verbose:
371
+ print(" Attempting to load cached models...")
372
+ cached_forecasters, missing_targets = _load_forecasters(
373
+ target_columns=list(data.columns),
374
+ model_dir=model_dir,
375
+ verbose=verbose,
376
+ )
377
+ baseline_forecasters.update(cached_forecasters)
378
+ targets_to_train = missing_targets
379
+
380
+ if len(cached_forecasters) == len(data.columns):
381
+ if verbose:
382
+ print(f" ✓ All {len(data.columns)} forecasters loaded from cache")
383
+ elif len(cached_forecasters) > 0:
384
+ if verbose:
385
+ print(
386
+ f" ✓ Loaded {len(cached_forecasters)} forecasters, "
387
+ f"will train {len(targets_to_train)} new ones"
388
+ )
389
+
390
+ # Train missing or forced models
391
+ if len(targets_to_train) > 0:
392
+ if force_train and len(baseline_forecasters) > 0:
393
+ if verbose:
394
+ print(f" Force retraining all {len(data.columns)} forecasters...")
395
+ targets_to_train = list(data.columns)
396
+ baseline_forecasters.clear()
397
+
398
+ target_iter = targets_to_train
399
+ if show_progress and tqdm is not None:
400
+ target_iter = tqdm(
401
+ targets_to_train,
402
+ desc="Training forecasters",
403
+ unit="model",
404
+ )
101
405
 
102
- target_iter = data.columns
103
- if show_progress and tqdm is not None:
104
- target_iter = tqdm(data.columns, desc="Training forecasters", unit="model")
406
+ for target in target_iter:
407
+ forecaster = ForecasterEquivalentDate(
408
+ offset=pd.DateOffset(days=1), n_offsets=1
409
+ )
105
410
 
106
- for target in target_iter:
107
- forecaster = ForecasterEquivalentDate(offset=pd.DateOffset(days=1), n_offsets=1)
411
+ forecaster.fit(y=data.loc[:end_validation, target])
108
412
 
109
- forecaster.fit(y=data.loc[:end_validation, target])
413
+ baseline_forecasters[target] = forecaster
110
414
 
111
- baseline_forecasters[target] = forecaster
415
+ # Save newly trained models to disk
416
+ if verbose:
417
+ print(f" Saving {len(targets_to_train)} trained forecasters to disk...")
418
+ _save_forecasters(
419
+ forecasters={t: baseline_forecasters[t] for t in targets_to_train},
420
+ model_dir=model_dir,
421
+ verbose=verbose,
422
+ )
112
423
 
113
424
  if verbose:
114
- print("✓ Multi-output baseline system trained")
425
+ print(f" Total forecasters available: {len(baseline_forecasters)}")
115
426
 
116
427
  # --- Predict ---
117
428
  if verbose:
@@ -123,4 +434,4 @@ def n2n_predict(
123
434
  show_progress=show_progress,
124
435
  )
125
436
 
126
- return predictions
437
+ return predictions, baseline_forecasters
@@ -744,7 +744,7 @@ def n2n_predict_with_covariates(
744
744
  force_train: bool = False,
745
745
  model_dir: Union[str, Path] = "./forecaster_models",
746
746
  verbose: bool = True,
747
- show_progress: bool = True,
747
+ show_progress: bool = False,
748
748
  ) -> Tuple[pd.DataFrame, Dict, Dict]:
749
749
  """End-to-end recursive forecasting with exogenous covariates.
750
750
 
@@ -781,9 +781,9 @@ def n2n_predict_with_covariates(
781
781
  force_train: Force retraining of all models, ignoring cached models.
782
782
  Default: False.
783
783
  model_dir: Directory for saving/loading trained models.
784
- Default: "./forecaster_models".
784
+ Default: "./models_covariates".
785
785
  verbose: Print progress messages. Default: True.
786
- show_progress: Show progress bar during training. Default: True.
786
+ show_progress: Show progress bar during training. Default: False.
787
787
 
788
788
  Returns:
789
789
  Tuple containing:
@@ -913,6 +913,10 @@ def n2n_predict_with_covariates(
913
913
  """Return sample weights for given index."""
914
914
  return custom_weights(index, weights_series)
915
915
 
916
+ # Note: weight_func is a local function and cannot be pickled.
917
+ # Model persistence is disabled when using weight_func.
918
+ use_model_persistence = False
919
+
916
920
  # ========================================================================
917
921
  # 4. EXOGENOUS FEATURES ENGINEERING
918
922
  # ========================================================================
@@ -1070,11 +1074,11 @@ def n2n_predict_with_covariates(
1070
1074
  window_features = RollingFeatures(stats=["mean"], window_sizes=window_size)
1071
1075
  end_validation = pd.concat([data_train, data_val]).index[-1]
1072
1076
 
1073
- # Attempt to load cached models if force_train=False
1077
+ # Attempt to load cached models if force_train=False and persistence is enabled
1074
1078
  recursive_forecasters = {}
1075
1079
  targets_to_train = target_columns
1076
1080
 
1077
- if not force_train and _model_directory_exists(model_dir):
1081
+ if use_model_persistence and not force_train and _model_directory_exists(model_dir):
1078
1082
  if verbose:
1079
1083
  print(" Attempting to load cached models...")
1080
1084
  cached_forecasters, missing_targets = _load_forecasters(
@@ -1132,14 +1136,20 @@ def n2n_predict_with_covariates(
1132
1136
  if verbose:
1133
1137
  print(f" ✓ Forecaster trained for {target}")
1134
1138
 
1135
- # Save newly trained models to disk
1136
- if verbose:
1137
- print(f" Saving {len(targets_to_train)} trained forecasters to disk...")
1138
- _save_forecasters(
1139
- forecasters={t: recursive_forecasters[t] for t in targets_to_train},
1140
- model_dir=model_dir,
1141
- verbose=verbose,
1142
- )
1139
+ # Save newly trained models to disk (only if persistence is enabled)
1140
+ if use_model_persistence:
1141
+ if verbose:
1142
+ print(
1143
+ f" Saving {len(targets_to_train)} trained forecasters to disk..."
1144
+ )
1145
+ _save_forecasters(
1146
+ forecasters={t: recursive_forecasters[t] for t in targets_to_train},
1147
+ model_dir=model_dir,
1148
+ verbose=verbose,
1149
+ )
1150
+ else:
1151
+ if verbose:
1152
+ print(" ⚠ Model persistence disabled (weight_func cannot be pickled)")
1143
1153
 
1144
1154
  if verbose:
1145
1155
  print(f" ✓ Total forecasters available: {len(recursive_forecasters)}")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: spotforecast2
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Forecasting with spot
5
5
  Author: bartzbeielstein
6
6
  Author-email: bartzbeielstein <32470350+bartzbeielstein@users.noreply.github.com>
@@ -31,8 +31,8 @@ spotforecast2/preprocessing/imputation.py,sha256=lmH-HumI_QLLm9aMESe_oZq84Axn60w
31
31
  spotforecast2/preprocessing/outlier.py,sha256=jZxAR870QtYner7b4gXk6LLGJw0juLq1VU4CGklYd3c,4208
32
32
  spotforecast2/preprocessing/split.py,sha256=mzzt5ltUZdVzfWtBBTQjp8E2MyqVdWUFtz7nN11urbU,5011
33
33
  spotforecast2/processing/agg_predict.py,sha256=VKlruB0x-eJKokkHyJxR87rZ4m53si3ODbrd0ibPlow,2378
34
- spotforecast2/processing/n2n_predict.py,sha256=Jkf-fMw2RSKY8-0UDc8D0yiiZxiF9s5DyfeRpfx90ks,4060
35
- spotforecast2/processing/n2n_predict_with_covariates.py,sha256=wnGSfwUjC5xKgaRyz0N80p4oW6sdbI1bgA1YyVQTA8I,39942
34
+ spotforecast2/processing/n2n_predict.py,sha256=dAj5yXD2JGXSqtl0VDkq0O_8FO_K9BCYG6osbJbWDFg,14494
35
+ spotforecast2/processing/n2n_predict_with_covariates.py,sha256=5a1lYIQE1d-t4ZvSQDoW87G705eiIZxtrCn4w7U2bVw,40420
36
36
  spotforecast2/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
37
37
  spotforecast2/utils/__init__.py,sha256=NrMt_xJLe4rbTFbsbgSQYeREohEOiYG5S-97e6Jj07I,1018
38
38
  spotforecast2/utils/convert_to_utc.py,sha256=hz8mJUHK9jDLUiN5LdNX5l3KZuOKlklyycB4zFdB9Ng,1405
@@ -42,6 +42,6 @@ spotforecast2/utils/generate_holiday.py,sha256=SHaPvPMt-abis95cChHf5ObyPwCTrzJ87
42
42
  spotforecast2/utils/validation.py,sha256=x9ypQzcneDhWJA_piiY4Q3_ogoGd1LTsZ7__MFeG9Fc,21618
43
43
  spotforecast2/weather/__init__.py,sha256=1Jco88pl0deNESgNATin83Nf5i9c58pxN7G-vNiOiu0,120
44
44
  spotforecast2/weather/weather_client.py,sha256=Ec_ywug6uoa71MfXM8RNbXEvtBtBzr-SUS5xq_HKtZE,9837
45
- spotforecast2-0.1.0.dist-info/WHEEL,sha256=5DEXXimM34_d4Gx1AuF9ysMr1_maoEtGKjaILM3s4w4,80
46
- spotforecast2-0.1.0.dist-info/METADATA,sha256=3odonjnM8q3No1KyboAF_Ta41X7LjUGLthDiavC2rMM,3481
47
- spotforecast2-0.1.0.dist-info/RECORD,,
45
+ spotforecast2-0.1.1.dist-info/WHEEL,sha256=5DEXXimM34_d4Gx1AuF9ysMr1_maoEtGKjaILM3s4w4,80
46
+ spotforecast2-0.1.1.dist-info/METADATA,sha256=TMwW-WMXSoNRVw7oDLU3Ys_8JXhODgvXxXjSeokWaXs,3481
47
+ spotforecast2-0.1.1.dist-info/RECORD,,