exceptions

exceptions

Custom exceptions and warnings for spotforecast2.

This module contains all the custom warnings and error classes used across spotforecast2.

Examples

import warnings
from spotforecast2_safe.exceptions import MissingValuesWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Missing values detected in input data.", MissingValuesWarning)

assert len(caught) == 1
assert issubclass(caught[0].category, MissingValuesWarning)
print(caught[0].category.__name__)
MissingValuesWarning

Classes

Name Description
CoverageError Exception raised when operational data-coverage requirements are violated.
DataTransformationWarning Warning for output data in transformed space.
DataTypeWarning Warning for incompatible data types in exogenous data.
ExogenousInterpretationWarning Warning about implications when using exogenous variables.
FeatureOutOfRangeWarning Warning for features out of training range.
IgnoredArgumentWarning Warning for ignored arguments.
InputTypeWarning Warning for inefficient input format.
LeakageError Exception raised when forbidden columns are detected in model inputs.
LongTrainingWarning Warning for potentially long training processes.
MissingExogWarning Warning for missing exogenous variables.
MissingValuesWarning Warning for missing values in data.
NotFittedError Exception class to raise if estimator is used before fitting.
OneStepAheadValidationWarning Warning for one-step-ahead validation usage.
PredictionPackageError Exception raised when building a prediction package fails.
ResidualsUsageWarning Warning for incorrect residuals usage.
SaveLoadSkforecastWarning Warning for save/load operations.
SpotforecastVersionWarning Warning for version mismatch.
TargetCorruptionError Exception raised when physically-impossible target corruption is detected.
UnknownLevelWarning Warning for unknown levels in prediction.

CoverageError

exceptions.CoverageError()

Exception raised when operational data-coverage requirements are violated.

Raised by the guards in spotforecast2_safe.preprocessing.coverage when a freshness, lag, or interior-gap invariant is broken and the pipeline cannot safely produce a forecast.

Inherits from RuntimeError so callers that catch RuntimeError keep working; the dedicated class lets safety-critical callers distinguish coverage violations from generic runtime errors.

Examples

import pandas as pd
from spotforecast2_safe.exceptions import CoverageError

try:
    raise CoverageError("Actual Load is stale: last published 2026-06-10 12:00 UTC")
except CoverageError as e:
    print(type(e).__name__, str(e))

assert issubclass(CoverageError, RuntimeError)
CoverageError Actual Load is stale: last published 2026-06-10 12:00 UTC

DataTransformationWarning

exceptions.DataTransformationWarning(message)

Warning for output data in transformed space.

Used to notify that the output data is in the transformed space.

Examples

import warnings
from spotforecast2_safe.exceptions import DataTransformationWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Output is in transformed space.", DataTransformationWarning)

assert len(caught) == 1
assert issubclass(caught[0].category, DataTransformationWarning)
print(caught[0].category.__name__)
DataTransformationWarning

DataTypeWarning

exceptions.DataTypeWarning(message)

Warning for incompatible data types in exogenous data.

Used to notify there are dtypes in the exogenous data that are not ‘int’, ‘float’, ‘bool’ or ‘category’. Most machine learning models do not accept other data types, therefore the forecaster fit and predict may fail.

Examples

import warnings
from spotforecast2_safe.exceptions import DataTypeWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Exogenous data contains unsupported dtypes.", DataTypeWarning)

assert len(caught) == 1
assert issubclass(caught[0].category, DataTypeWarning)
print(caught[0].category.__name__)
DataTypeWarning

ExogenousInterpretationWarning

exceptions.ExogenousInterpretationWarning(message)

Warning about implications when using exogenous variables.

Used to notify about important implications when using exogenous variables with models that use a two-step approach (e.g., regression + ARAR).

Examples

import warnings
from spotforecast2_safe.exceptions import ExogenousInterpretationWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn(
        "Exogenous variables may not be used as expected.",
        ExogenousInterpretationWarning,
    )

assert len(caught) == 1
assert issubclass(caught[0].category, ExogenousInterpretationWarning)
print(caught[0].category.__name__)
ExogenousInterpretationWarning

FeatureOutOfRangeWarning

exceptions.FeatureOutOfRangeWarning(message)

Warning for features out of training range.

Used to notify that a feature is out of the range seen during training.

Examples

import warnings
from spotforecast2_safe.exceptions import FeatureOutOfRangeWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Feature value exceeds training range.", FeatureOutOfRangeWarning)

assert len(caught) == 1
assert issubclass(caught[0].category, FeatureOutOfRangeWarning)
print(caught[0].category.__name__)
FeatureOutOfRangeWarning

IgnoredArgumentWarning

exceptions.IgnoredArgumentWarning(message)

Warning for ignored arguments.

Used to notify that an argument is ignored when using a method or a function.

Examples

import warnings
from spotforecast2_safe.exceptions import IgnoredArgumentWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Argument 'x' is ignored in this context.", IgnoredArgumentWarning)

assert len(caught) == 1
assert issubclass(caught[0].category, IgnoredArgumentWarning)
print(caught[0].category.__name__)
IgnoredArgumentWarning

InputTypeWarning

exceptions.InputTypeWarning(message)

Warning for inefficient input format.

Used to notify that input format is not the most efficient or recommended for the forecaster.

Examples

import warnings
from spotforecast2_safe.exceptions import InputTypeWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn(
        "Input format is not optimal for this forecaster.", InputTypeWarning
    )

assert len(caught) == 1
assert issubclass(caught[0].category, InputTypeWarning)
print(caught[0].category.__name__)
InputTypeWarning

LeakageError

exceptions.LeakageError()

Exception raised when forbidden columns are detected in model inputs.

Raised by spotforecast2_safe.multitask.guards.assert_no_leakage when a forbidden column name appears in the training frame, the selected exogenous feature set, or the fitted model’s feature list.

Inherits from RuntimeError so callers that catch RuntimeError keep working; the dedicated class lets safety-critical callers distinguish data-governance violations from generic runtime errors.

Examples

from spotforecast2_safe.exceptions import LeakageError

try:
    raise LeakageError(
        "Forbidden column 'Forecasted Load' found in training frame"
    )
except LeakageError as e:
    print(type(e).__name__, str(e))

assert issubclass(LeakageError, RuntimeError)
LeakageError Forbidden column 'Forecasted Load' found in training frame

LongTrainingWarning

exceptions.LongTrainingWarning(message)

Warning for potentially long training processes.

Used to notify that a large number of models will be trained and the the process may take a while to run.

Examples

import warnings
from spotforecast2_safe.exceptions import LongTrainingWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Training may take a long time.", LongTrainingWarning)

assert len(caught) == 1
assert issubclass(caught[0].category, LongTrainingWarning)
print(caught[0].category.__name__)
LongTrainingWarning

MissingExogWarning

exceptions.MissingExogWarning(message)

Warning for missing exogenous variables.

Used to indicate that there are missing exogenous variables in the data. Most machine learning models do not accept missing values, so the Forecaster’s fit' andpredict’ methods may fail.

Examples

import warnings
from spotforecast2_safe.exceptions import MissingExogWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Missing exogenous variables detected.", MissingExogWarning)

assert len(caught) == 1
assert issubclass(caught[0].category, MissingExogWarning)
print(caught[0].category.__name__)
MissingExogWarning

MissingValuesWarning

exceptions.MissingValuesWarning(message)

Warning for missing values in data.

Used to indicate that there are missing values in the data. This warning occurs when the input data contains missing values, or the training matrix generates missing values. Most machine learning models do not accept missing values, so the Forecaster’s fit' andpredict’ methods may fail.

Parameters

Name Type Description Default
message str The message to display. required

Examples

import warnings
from spotforecast2_safe.exceptions import MissingValuesWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Missing values detected in input data.", MissingValuesWarning)

assert len(caught) == 1
assert issubclass(caught[0].category, MissingValuesWarning)
print(caught[0].category.__name__)
MissingValuesWarning

NotFittedError

exceptions.NotFittedError()

Exception class to raise if estimator is used before fitting.

This class inherits from both ValueError and AttributeError to help with exception handling and backward compatibility.

Examples

from spotforecast2_safe.exceptions import NotFittedError

try:
    raise NotFittedError("Forecaster not fitted")
except NotFittedError as e:
    print(type(e).__name__, str(e))

assert issubclass(NotFittedError, ValueError)
assert issubclass(NotFittedError, AttributeError)
NotFittedError Forecaster not fitted

OneStepAheadValidationWarning

exceptions.OneStepAheadValidationWarning(message)

Warning for one-step-ahead validation usage.

Used to notify that the one-step-ahead validation is being used.

Examples

import warnings
from spotforecast2_safe.exceptions import OneStepAheadValidationWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn(
        "Using one-step-ahead validation.", OneStepAheadValidationWarning
    )

assert len(caught) == 1
assert issubclass(caught[0].category, OneStepAheadValidationWarning)
print(caught[0].category.__name__)
OneStepAheadValidationWarning

PredictionPackageError

exceptions.PredictionPackageError()

Exception raised when building a prediction package fails.

Raised by ForecasterRecursiveModel.package_prediction() (and propagated by callers such as manager.predictor.get_model_prediction()) when the underlying prediction pipeline cannot produce a complete result. Inherits from RuntimeError so callers that catch RuntimeError keep working; the dedicated class lets safety-critical callers distinguish a prediction-pipeline failure from generic runtime errors.

Examples

from spotforecast2_safe.exceptions import PredictionPackageError

try:
    raise PredictionPackageError("Predict step returned no rows")
except PredictionPackageError as e:
    print(type(e).__name__, str(e))

assert issubclass(PredictionPackageError, RuntimeError)
PredictionPackageError Predict step returned no rows

ResidualsUsageWarning

exceptions.ResidualsUsageWarning(message)

Warning for incorrect residuals usage.

Used to notify that a residual are not correctly used in the probabilistic forecasting process.

Examples

import warnings
from spotforecast2_safe.exceptions import ResidualsUsageWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Residuals are not properly used.", ResidualsUsageWarning)

assert len(caught) == 1
assert issubclass(caught[0].category, ResidualsUsageWarning)
print(caught[0].category.__name__)
ResidualsUsageWarning

SaveLoadSkforecastWarning

exceptions.SaveLoadSkforecastWarning(message)

Warning for save/load operations.

Used to notify any issues that may arise when saving or loading a forecaster.

Examples

import warnings
from spotforecast2_safe.exceptions import SaveLoadSkforecastWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn(
        "Issues detected when saving forecaster.", SaveLoadSkforecastWarning
    )

assert len(caught) == 1
assert issubclass(caught[0].category, SaveLoadSkforecastWarning)
print(caught[0].category.__name__)
SaveLoadSkforecastWarning

SpotforecastVersionWarning

exceptions.SpotforecastVersionWarning(message)

Warning for version mismatch.

Used to notify that the version installed in the environment differs from the version used to initialize the forecaster.

Examples

import warnings
from spotforecast2_safe.exceptions import SpotforecastVersionWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Version mismatch detected.", SpotforecastVersionWarning)

assert len(caught) == 1
assert issubclass(caught[0].category, SpotforecastVersionWarning)
print(caught[0].category.__name__)
SpotforecastVersionWarning

TargetCorruptionError

exceptions.TargetCorruptionError()

Exception raised when physically-impossible target corruption is detected.

Raised by spotforecast2_safe.preprocessing.target_corruption.apply_target_corruption_policy when target_corruption_policy="abort" and the detector fires, or when the "heal" policy is requested but cannot be applied safely (e.g. the corrupt span touches the anchor zone, or exceeds the heal budget).

Inherits from RuntimeError so callers that catch RuntimeError keep working; the dedicated class lets safety-critical callers distinguish target-corruption aborts from generic runtime errors.

Examples

from spotforecast2_safe.exceptions import TargetCorruptionError

try:
    raise TargetCorruptionError("Corrupt target tail detected")
except TargetCorruptionError as e:
    print(type(e).__name__, str(e))

assert issubclass(TargetCorruptionError, RuntimeError)
TargetCorruptionError Corrupt target tail detected

UnknownLevelWarning

exceptions.UnknownLevelWarning(message)

Warning for unknown levels in prediction.

Used to notify that a level being predicted was not part of the training data.

Examples

import warnings
from spotforecast2_safe.exceptions import UnknownLevelWarning

with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Predicting for an unknown level.", UnknownLevelWarning)

assert len(caught) == 1
assert issubclass(caught[0].category, UnknownLevelWarning)
print(caught[0].category.__name__)
UnknownLevelWarning

Functions

Name Description
format_warning_handler Custom warning handler to format warnings in a box.
rich_warning_handler Custom handler for warnings that uses rich to display formatted panels.
set_skforecast_warnings Suppress or configure spotforecast warning filters.
set_warnings_style Set the warning handler based on the provided style.

format_warning_handler

exceptions.format_warning_handler(
    message,
    category,
    filename,
    lineno,
    file=None,
    line=None,
)

Custom warning handler to format warnings in a box.

Parameters

Name Type Description Default
message str Warning message. required
category str Warning category. required
filename str Filename where the warning was raised. required
lineno str Line number where the warning was raised. required
file object File where the warning was raised. None
line str Line where the warning was raised. None

Returns

Name Type Description
None None

Examples

import warnings
from spotforecast2_safe.exceptions import (
    MissingValuesWarning,
    set_warnings_style,
)

# Activate the custom box-formatted handler, then emit one warning.
set_warnings_style("skforecast")
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Missing values in test data.", MissingValuesWarning)

# Restore default style so subsequent examples are unaffected.
set_warnings_style("default")
assert len(caught) == 1
print("handler demo: warning category =", caught[0].category.__name__)
handler demo: warning category = MissingValuesWarning

rich_warning_handler

exceptions.rich_warning_handler(
    message,
    category,
    filename,
    lineno,
    file=None,
    line=None,
)

Custom handler for warnings that uses rich to display formatted panels.

Parameters

Name Type Description Default
message str Warning message. required
category str Warning category. required
filename str Filename where the warning was raised. required
lineno str Line number where the warning was raised. required
file object File where the warning was raised. None
line str Line where the warning was raised. None

Returns

Name Type Description
None None

Examples

import warnings
from spotforecast2_safe.exceptions import (
    InputTypeWarning,
    set_warnings_style,
)

# Activate the rich (or box-formatted fallback) handler, emit one warning.
set_warnings_style("skforecast")
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Input format is suboptimal.", InputTypeWarning)

# Restore default style so subsequent examples are unaffected.
set_warnings_style("default")
assert len(caught) == 1
print("rich handler demo: warning category =", caught[0].category.__name__)
rich handler demo: warning category = InputTypeWarning

set_skforecast_warnings

exceptions.set_skforecast_warnings(suppress_warnings, action='ignore')

Suppress or configure spotforecast warning filters.

Iterates over all spotforecast warning categories and registers a warnings.simplefilter for each one.

Parameters

Name Type Description Default
suppress_warnings bool If True, apply action to all spotforecast warning categories. required
action str Filter action passed to warnings.simplefilter. Common values are 'ignore', 'always', and 'once'. Defaults to 'ignore'. 'ignore'

Examples

import warnings
from spotforecast2_safe.exceptions import (
    MissingValuesWarning,
    ResidualsUsageWarning,
    set_skforecast_warnings,
)

# Suppress all spotforecast warnings.
with warnings.catch_warnings(record=True) as caught_suppressed:
    warnings.simplefilter("always")   # baseline: catch everything first
    set_skforecast_warnings(suppress_warnings=True, action="ignore")
    warnings.warn("Missing values.", MissingValuesWarning)
    warnings.warn("Bad residuals.", ResidualsUsageWarning)

suppressed = [w for w in caught_suppressed
              if issubclass(w.category, (MissingValuesWarning, ResidualsUsageWarning))]
assert len(suppressed) == 0, f"Expected 0 suppressed warnings, got {len(suppressed)}"
print(f"suppressed warnings: {len(suppressed)}")

# Re-enable all spotforecast warnings with 'always'.
with warnings.catch_warnings(record=True) as caught_enabled:
    set_skforecast_warnings(suppress_warnings=True, action="always")
    warnings.warn("Missing values.", MissingValuesWarning)
    warnings.warn("Bad residuals.", ResidualsUsageWarning)

enabled = [w for w in caught_enabled
           if issubclass(w.category, (MissingValuesWarning, ResidualsUsageWarning))]
assert len(enabled) == 2, f"Expected 2 enabled warnings, got {len(enabled)}"
print(f"enabled warnings: {len(enabled)}")

# suppress_warnings=False is a no-op.
with warnings.catch_warnings(record=True) as caught_noop:
    warnings.simplefilter("always")
    set_skforecast_warnings(suppress_warnings=False)
    warnings.warn("Missing values.", MissingValuesWarning)

noop = [w for w in caught_noop if issubclass(w.category, MissingValuesWarning)]
assert len(noop) == 1
print(f"no-op (False) warnings: {len(noop)}")
suppressed warnings: 0
enabled warnings: 2
no-op (False) warnings: 1

set_warnings_style

exceptions.set_warnings_style(style='skforecast')

Set the warning handler based on the provided style.

Parameters

Name Type Description Default
style str The style of the warning handler. Either ‘skforecast’ or ‘default’. 'skforecast'

Returns

Name Type Description
None None

Examples

import warnings
from spotforecast2_safe.exceptions import (
    IgnoredArgumentWarning,
    set_warnings_style,
)

# Switch to skforecast box-formatted style and emit a warning.
set_warnings_style("skforecast")
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    warnings.warn("Argument 'verbose' is ignored here.", IgnoredArgumentWarning)
assert len(caught) == 1

# Switch back to Python default style.
set_warnings_style("default")
with warnings.catch_warnings(record=True) as caught2:
    warnings.simplefilter("always")
    warnings.warn("Argument 'verbose' is ignored here.", IgnoredArgumentWarning)
assert len(caught2) == 1
print("style toggle: both modes captured 1 warning each")
style toggle: both modes captured 1 warning each