module mlforecast.forecast

Global Variables

  • TYPE_CHECKING

class MLForecast

method __init__

__init__(
    models: Union[BaseEstimator, List[BaseEstimator], Dict[str, BaseEstimator]],
    freq: Union[int, str],
    lags: Optional[Iterable[int]] = None,
    lag_transforms: Optional[Dict[int, List[Union[Callable, Tuple[Callable, Any]]]]] = None,
    date_features: Optional[Iterable[Union[str, Callable]]] = None,
    num_threads: int = 1,
    target_transforms: Optional[List[Union[BaseTargetTransform, _BaseGroupedArrayTargetTransform]]] = None,
    lag_transforms_namer: Optional[Callable] = None
)
Forecasting pipeline Args:
  • models (regressor or list of regressors): Models that will be trained and used to compute the forecasts.
  • freq (str or int or pd.offsets.BaseOffset): Pandas offset, pandas offset alias, e.g. ‘D’, ‘W-THU’ or integer denoting the frequency of the series.
  • lags (list of int, optional): Lags of the target to use as features. Defaults to None.
  • lag_transforms (dict of int to list of functions, optional): Mapping of target lags to their transformations. Defaults to None.
  • date_features (list of str or callable, optional): Features computed from the dates. Can be pandas date attributes or functions that will take the dates as input. Defaults to None.
  • num_threads (int): Number of threads to use when computing the features. Defaults to 1.
  • target_transforms (list of transformers, optional): Transformations that will be applied to the target before computing the features and restored after the forecasting step. Defaults to None.
  • lag_transforms_namer (callable, optional): Function that takes a transformation (either function or class), a lag and extra arguments and produces a name. Defaults to None.

property freq


method cross_validation

cross_validation(
    df: ~DFType,
    n_windows: int,
    h: int,
    id_col: str = 'unique_id',
    time_col: str = 'ds',
    target_col: str = 'y',
    step_size: Optional[int] = None,
    static_features: Optional[List[str]] = None,
    dropna: bool = True,
    keep_last_n: Optional[int] = None,
    refit: Union[bool, int] = True,
    max_horizon: Optional[int] = None,
    before_predict_callback: Optional[Callable] = None,
    after_predict_callback: Optional[Callable] = None,
    prediction_intervals: Optional[PredictionIntervals] = None,
    level: Optional[List[Union[int, float]]] = None,
    input_size: Optional[int] = None,
    fitted: bool = False,
    as_numpy: bool = False,
    weight_col: Optional[str] = None
) → ~DFType
Perform time series cross validation. Creates n_windows splits where each window has h test periods, trains the models, computes the predictions and merges the actuals. Args:
  • df (pandas or polars DataFrame): Series data in long format.
  • n_windows (int): Number of windows to evaluate.
  • h (int): Forecast horizon.
  • id_col (str): Column that identifies each serie. Defaults to ‘unique_id’.
  • time_col (str): Column that identifies each timestep, its values can be timestamps or integers. Defaults to ‘ds’.
  • target_col (str): Column that contains the target. Defaults to ‘y’.
  • step_size (int, optional): Step size between each cross validation window. If None it will be equal to h. Defaults to None.
  • static_features (list of str, optional): Names of the features that are static and will be repeated when forecasting. Defaults to None.
  • dropna (bool): Drop rows with missing values produced by the transformations. Defaults to True.
  • keep_last_n (int, optional): Keep only these many records from each serie for the forecasting step. Can save time and memory if your features allow it. Defaults to None.
  • max_horizon (int, optional): Train this many models, where each model will predict a specific horizon. Defaults to None.
  • refit (bool or int): Retrain model for each cross validation window. If False, the models are trained at the beginning and then used to predict each window. If positive int, the models are retrained every refit windows. Defaults to True.
  • before_predict_callback (callable, optional): Function to call on the features before computing the predictions. This function will take the input dataframe that will be passed to the model for predicting and should return a dataframe with the same structure. The series identifier is on the index. Defaults to None.
  • after_predict_callback (callable, optional): Function to call on the predictions before updating the targets. This function will take a pandas Series with the predictions and should return another one with the same structure. The series identifier is on the index. Defaults to None.
  • prediction_intervals (PredictionIntervals, optional): Configuration to calibrate prediction intervals (Conformal Prediction). Defaults to None.
  • level (list of ints or floats, optional): Confidence levels between 0 and 100 for prediction intervals. Defaults to None.
  • input_size (int, optional): Maximum training samples per serie in each window. If None, will use an expanding window. Defaults to None.
  • fitted (bool): Store the in-sample predictions. Defaults to False.
  • as_numpy (bool): Cast features to numpy array. Defaults to False.
  • weight_col (str, optional): Column that contains the sample weights. Defaults to None.
Returns:
  • pandas or polars DataFrame: Predictions for each window with the series id, timestamp, last train date, target value and predictions from each model.

method cross_validation_fitted_values

cross_validation_fitted_values()

method fit

fit(
    df: Union[DataFrame, DataFrame],
    id_col: str = 'unique_id',
    time_col: str = 'ds',
    target_col: str = 'y',
    static_features: Optional[List[str]] = None,
    dropna: bool = True,
    keep_last_n: Optional[int] = None,
    max_horizon: Optional[int] = None,
    prediction_intervals: Optional[PredictionIntervals] = None,
    fitted: bool = False,
    as_numpy: bool = False,
    weight_col: Optional[str] = None
) → MLForecast
Apply the feature engineering and train the models. Args:
  • df (pandas or polars DataFrame): Series data in long format.
  • id_col (str): Column that identifies each serie. Defaults to ‘unique_id’.
  • time_col (str): Column that identifies each timestep, its values can be timestamps or integers. Defaults to ‘ds’.
  • target_col (str): Column that contains the target. Defaults to ‘y’.
  • static_features (list of str, optional): Names of the features that are static and will be repeated when forecasting. If None, will consider all columns (except id_col and time_col) as static. Defaults to None.
  • dropna (bool): Drop rows with missing values produced by the transformations. Defaults to True.
  • keep_last_n (int, optional): Keep only these many records from each serie for the forecasting step. Can save time and memory if your features allow it. Defaults to None.
  • max_horizon (int, optional): Train this many models, where each model will predict a specific horizon. Defaults to None.
  • prediction_intervals (PredictionIntervals, optional): Configuration to calibrate prediction intervals (Conformal Prediction). Defaults to None.
  • fitted (bool): Save in-sample predictions. Defaults to False.
  • as_numpy (bool): Cast features to numpy array. Defaults to False.
  • weight_col (str, optional): Column that contains the sample weights. Defaults to None.
Returns:
  • MLForecast: Forecast object with series values and trained models.

method fit_models

fit_models(X: Union[DataFrame, DataFrame, ndarray], y: ndarray) → MLForecast
Manually train models. Use this if you called MLForecast.preprocess beforehand. Args:
  • X (pandas or polars DataFrame or numpy array): Features.
  • y (numpy array): Target.
Returns:
  • MLForecast: Forecast object with trained models.

method forecast_fitted_values

forecast_fitted_values(
    level: Optional[List[Union[int, float]]] = None
) → Union[DataFrame, DataFrame]
Access in-sample predictions. Args:
  • level (list of ints or floats, optional): Confidence levels between 0 and 100 for prediction intervals. Defaults to None.
Returns:
  • pandas or polars DataFrame: Dataframe with predictions for the training set

classmethod from_cv

from_cv(cv: 'LightGBMCV') → MLForecast

method get_missing_future

get_missing_future(h: int, X_df: ~DFType) → ~DFType
Get the missing id and time combinations in X_df. Args:
  • h (int): Number of periods to predict.
  • X_df (pandas or polars DataFrame): Dataframe with the future exogenous features. Should have the id column and the time column.
Returns:
  • pandas or polars DataFrame: DataFrame with expected ids and future times missing in X_df

method load

load(path: Union[str, Path]) → MLForecast
Load forecast object Args:
  • path (str or pathlib.Path): Directory with saved artifacts.

method make_future_dataframe

make_future_dataframe(h: int) → Union[DataFrame, DataFrame]
Create a dataframe with all ids and future times in the forecasting horizon. Args:
  • h (int): Number of periods to predict.
Returns:
  • pandas or polars DataFrame: DataFrame with expected ids and future times

method predict

predict(
    h: int,
    before_predict_callback: Optional[Callable] = None,
    after_predict_callback: Optional[Callable] = None,
    new_df: Optional[~DFType] = None,
    level: Optional[List[Union[int, float]]] = None,
    X_df: Optional[~DFType] = None,
    ids: Optional[List[str]] = None
) → ~DFType
Compute the predictions for the next h steps. Args:
  • h (int): Number of periods to predict.
  • before_predict_callback (callable, optional): Function to call on the features before computing the predictions. This function will take the input dataframe that will be passed to the model for predicting and should return a dataframe with the same structure. The series identifier is on the index. Defaults to None.
  • after_predict_callback (callable, optional): Function to call on the predictions before updating the targets. This function will take a pandas Series with the predictions and should return another one with the same structure. The series identifier is on the index. Defaults to None.
  • new_df (pandas or polars DataFrame, optional): Series data of new observations for which forecasts are to be generated. This dataframe should have the same structure as the one used to fit the model, including any features and time series data. If new_df is not None, the method will generate forecasts for the new observations. Defaults to None.
  • level (list of ints or floats, optional): Confidence levels between 0 and 100 for prediction intervals. Defaults to None.
  • X_df (pandas or polars DataFrame, optional): Dataframe with the future exogenous features. Should have the id column and the time column. Defaults to None.
  • ids (list of str, optional): List with subset of ids seen during training for which the forecasts should be computed. Defaults to None.
Returns:
  • pandas or polars DataFrame: Predictions for each serie and timestep, with one column per model.

method preprocess

preprocess(
    df: ~DFType,
    id_col: str = 'unique_id',
    time_col: str = 'ds',
    target_col: str = 'y',
    static_features: Optional[List[str]] = None,
    dropna: bool = True,
    keep_last_n: Optional[int] = None,
    max_horizon: Optional[int] = None,
    return_X_y: bool = False,
    as_numpy: bool = False,
    weight_col: Optional[str] = None
) → Union[~DFType, Tuple[~DFType, ndarray]]
Add the features to data. Args:
  • df (pandas DataFrame): Series data in long format.
  • id_col (str): Column that identifies each serie. Defaults to ‘unique_id’.
  • time_col (str): Column that identifies each timestep, its values can be timestamps or integers. Defaults to ‘ds’.
  • target_col (str): Column that contains the target. Defaults to ‘y’.
  • static_features (list of str, optional): Names of the features that are static and will be repeated when forecasting. Defaults to None.
  • dropna (bool): Drop rows with missing values produced by the transformations. Defaults to True.
  • keep_last_n (int, optional): Keep only these many records from each serie for the forecasting step. Can save time and memory if your features allow it. Defaults to None.
  • max_horizon (int, optional): Train this many models, where each model will predict a specific horizon. Defaults to None.
  • return_X_y (bool): Return a tuple with the features and the target. If False will return a single dataframe. Defaults to False.
  • as_numpy (bool): Cast features to numpy array. Only works for return_X_y=True. Defaults to False.
  • weight_col (str, optional): Column that contains the sample weights. Defaults to None.
Returns:
  • DataFrame or tuple of pandas Dataframe and a numpy array: df plus added features and target(s).

method save

save(path: Union[str, Path]) → None
Save forecast object Args:
  • path (str or pathlib.Path): Directory where artifacts will be stored.

method update

update(df: Union[DataFrame, DataFrame]) → None
Update the values of the stored series. Args:
  • df (pandas or polars DataFrame): Dataframe with new observations.