source

ml_forecaster


def ml_forecaster(
    model:Any, # A regression model object (e.g. LGBMRegressor(), XGBRegressor(), CatBoostRegressor(), LinearRegression(), etc.)
    target_col:str, # Name of the target variable column in the input DataFrame.
    lags:Optional[Union[int, List[int]]]=None, # Lags to include as features. If an integer is provided, lags from 1 to that integer will be included. If a list of integers is provided, those specific lags will be included. Default is None (no lag features).
    lag_transform:Optional[list]=None, # List of lag-transform function objects to apply to the target variable (e.g. [expanding_mean(shift=1), rolling_std(window_size=3, shift=1)]). Each function should take a pandas Series as input and return a Series of the same length. Default is None (no lag transforms).
    difference:Optional[int]=None, # Order of ordinary differencing to apply to the target variable (e.g. 1 for first difference). Default is None (no differencing).
    seasonal_diff:Optional[int]=None, # Seasonal period for seasonal differencing (e.g. 12 for monthly data with yearly seasonality). Default is None (no seasonal differencing).
    trend:Optional[str]=None, # Trend strategy to use. Options are 'linear' for linear trend removal, 'ets' for ETS-based trend removal, 'feature_lr' for using linear trend components as features, and 'feature_ets' for using ETS trend components as features. Default is None (no trend handling).
    pol_degree:int=1, # Degree of polynomial trend to fit when using 'linear' or 'feature_lr' trend strategy. Default is 1 (linear trend).
    ets_params:Optional[Dict[str, Any]]=None, # Dictionary of parameters for the ExponentialSmoothing model when using 'ets' trend strategy. The keys should be the parameter names and the values should be the parameter values. Default is None (use default ETS parameters).
    change_points:Optional[List[int]]=None, # List of indices in the time series where change points occur for piecewise linear trend fitting. Only used when trend strategy is 'linear' or 'feature_lr'. Default is None (no change points, fit a single linear trend).
    box_cox:Union[bool, float, int]=False, # Whether to apply Box-Cox transformation to the target variable. If a float or int value is provided, it will be used as the lambda parameter for the Box-Cox transformation. If True, the lambda parameter will be estimated from the data.
    box_cox_biasadj:bool=False, # Whether to apply bias adjustment when inverting the Box-Cox transformation on forecasts. Default is False.
    cat_variables:Optional[List[str]]=None, # List of categorical feature column names. If provided, these columns will be treated as categorical variables and encoded accordingly. Default is None (no categorical variables).
    categorical_encoder:Optional[Any]=None, # Categorical encoder object (e.g. OneHotEncoder(), MeanEncoder(), etc.) to apply to the categorical variables specified in cat_variables. The encoder should have fit() and transform() methods that can be applied to the input DataFrame. Default is None (no categorical encoding) and if None, categorical variables can only be used if the model can handle them natively (e.g. LGBM or CatBoost).
)->None:

Initialize the ml_forecaster with the specified model and preprocessing options.

Type Default Details
model Any A regression model object (e.g. LGBMRegressor(), XGBRegressor(), CatBoostRegressor(), LinearRegression(), etc.)
target_col str Name of the target variable column in the input DataFrame.
lags Optional[Union[int, List[int]]] None Lags to include as features. If an integer is provided, lags from 1 to that integer will be included. If a list of integers is provided, those specific lags will be included. Default is None (no lag features).
lag_transform Optional[list] None List of lag-transform function objects to apply to the target variable (e.g. [expanding_mean(shift=1), rolling_std(window_size=3, shift=1)]). Each function should take a pandas Series as input and return a Series of the same length. Default is None (no lag transforms).
difference Optional[int] None Order of ordinary differencing to apply to the target variable (e.g. 1 for first difference). Default is None (no differencing).
seasonal_diff Optional[int] None Seasonal period for seasonal differencing (e.g. 12 for monthly data with yearly seasonality). Default is None (no seasonal differencing).
trend Optional[str] None Trend strategy to use. Options are ‘linear’ for linear trend removal, ‘ets’ for ETS-based trend removal, ‘feature_lr’ for using linear trend components as features, and ‘feature_ets’ for using ETS trend components as features. Default is None (no trend handling).
pol_degree int 1 Degree of polynomial trend to fit when using ‘linear’ or ‘feature_lr’ trend strategy. Default is 1 (linear trend).
ets_params Optional[Dict[str, Any]] None Dictionary of parameters for the ExponentialSmoothing model when using ‘ets’ trend strategy. The keys should be the parameter names and the values should be the parameter values. Default is None (use default ETS parameters).
change_points Optional[List[int]] None List of indices in the time series where change points occur for piecewise linear trend fitting. Only used when trend strategy is ‘linear’ or ‘feature_lr’. Default is None (no change points, fit a single linear trend).
box_cox Union[bool, float, int] False Whether to apply Box-Cox transformation to the target variable. If a float or int value is provided, it will be used as the lambda parameter for the Box-Cox transformation. If True, the lambda parameter will be estimated from the data.
box_cox_biasadj bool False Whether to apply bias adjustment when inverting the Box-Cox transformation on forecasts. Default is False.
cat_variables Optional[List[str]] None List of categorical feature column names. If provided, these columns will be treated as categorical variables and encoded accordingly. Default is None (no categorical variables).
categorical_encoder Optional[Any] None Categorical encoder object (e.g. OneHotEncoder(), MeanEncoder(), etc.) to apply to the categorical variables specified in cat_variables. The encoder should have fit() and transform() methods that can be applied to the input DataFrame. Default is None (no categorical encoding) and if None, categorical variables can only be used if the model can handle them natively (e.g. LGBM or CatBoost).
Returns None

source

ml_forecaster.fit


def fit(
    df:pd.DataFrame, # Training DataFrame containing the target and any feature columns.
)->None:

Fit the model to the training data after applying the specified data preparation steps.

Type Details
df pd.DataFrame Training DataFrame containing the target and any feature columns.
Returns None

source

ml_forecaster.forecast


def forecast(
    H:int, # Forecast horizon.
    exog:Optional[pd.DataFrame]=None, # Optional dataframe of future regressors.
)->np.ndarray: # Forecast values of length `H`.

Recursive multi-step forecast.

Type Default Details
H int Forecast horizon.
exog Optional[pd.DataFrame] None Optional dataframe of future regressors.
Returns np.ndarray Forecast values of length H.

source

ml_forecaster.cross_validate


def cross_validate(
    df:pd.DataFrame, # DataFrame containing the target and any feature columns.
    cv_split:int, # Number of cross-validation splits.
    test_size:int, # Number of periods in each test set.
    metrics:List[Callable], # Metric functions (e.g. ``[MAE, RMSE]``) used to evaluate forecast accuracy across folds. Call ``.cv_summary()`` after cross-validation to retrieve the aggregated scores.
    step_size:int=1, # Step size to move the test window forward in each split.
    h_split_point:Optional[int]=None, # Optional index to split the test set into two parts for separate evaluation (e.g. to evaluate short-term vs long-term performance). If None, no split is done.
)->Tuple[pd.DataFrame, pd.DataFrame]: # DataFrame containing overall performance metrics averaged across splits, and a DataFrame with predictions and true values for each split.

Run cross-validation using time series splits.

Type Default Details
df pd.DataFrame DataFrame containing the target and any feature columns.
cv_split int Number of cross-validation splits.
test_size int Number of periods in each test set.
metrics List[Callable] Metric functions (e.g. [MAE, RMSE]) used to evaluate forecast accuracy across folds. Call .cv_summary() after cross-validation to retrieve the aggregated scores.
step_size int 1 Step size to move the test window forward in each split.
h_split_point Optional[int] None Optional index to split the test set into two parts for separate evaluation (e.g. to evaluate short-term vs long-term performance). If None, no split is done.
Returns Tuple[pd.DataFrame, pd.DataFrame] DataFrame containing overall performance metrics averaged across splits, and a DataFrame with predictions and true values for each split.