Optimizes forecaster hyperparameters using grid search, random search, or Bayesian search (Optuna). Covers single-series and multi-series search, cross-validation configuration, and search space definition.
Ships in skforecast. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Use hyperparameter search after establishing a baseline forecaster to improve prediction accuracy. Skforecast supports three strategies:
| Strategy | When to Use | Speed |
|---|---|---|
| Bayesian Search | Recommended default. Smart exploration via Optuna | Fastest to converge |
| Random Search | Large parameter space, limited compute budget | Medium |
| Grid Search | Small parameter space, exhaustive exploration | Slowest |
autocorrelation-and-lag-selection (narrow the lags search space to a statistically informed candidate set)baseline-forecasting (tune ForecasterEquivalentDate baselines with grid_search_equivalent_date)foundation-forecasting (tune zero-shot ForecasterFoundation inference parameters with bayesian_search_foundation)feature-selection (optional trim of the feature set afterwards; re-tune if the reduction is large)prediction-intervals (add uncertainty quantification once the configuration is fixed)Scan before writing code. Each row lists a rule, the symptom when it is broken, and the recovery. Full pitfall catalog: the troubleshooting-common-errors skill.
| Rule | Symptom | Recovery |
|---|---|---|
The search refits the forecaster in place with the best params when return_best=True (the default) | With return_best=False, the forecaster keeps its pre-search params | Rely on the default, or refit with the best params from the results table |
Use the *_multiseries / *_stats search variant matching the forecaster type | Search function raises on the wrong forecaster type | Call e.g. bayesian_search_forecaster_multiseries / grid_search_stats / grid_search_equivalent_date |
ForecasterFoundation is tuned only with bayesian_search_foundation and TimeSeriesFold | TypeError from the generic search functions, or from passing OneStepAheadFold | Call bayesian_search_foundation with a TimeSeriesFold |
Include lags in the Bayesian search_space() | Suboptimal search; the highest-impact parameter stays fixed | Add trial.suggest_categorical('lags', [...]) to the search space |
Always prefer Bayesian search as the default strategy. It uses Optuna to intelligently explore the search space.
from skforecast.recursive import ForecasterRecursive
from skforecast.model_selection import bayesian_search_forecaster, TimeSeriesFold
from lightgbm import LGBMRegressor
forecaster = ForecasterRecursive(
estimator=LGBMRegressor(random_state=123),
lags=24,
)
cv = TimeSeriesFold(
steps=12,
initial_train_size=len(data) - 100,
refit=False,
)
# Define search space as a function: lags CAN be included here
def search_space(trial):
return {
'lags': trial.suggest_categorical('lags', [12, 24, [1, 2, 3, 23, 24]]),
'n_estimators': trial.suggest_int('n_estimators', 50, 500),
'max_depth': trial.suggest_int('max_depth', 3, 15),
'learning_rate': trial.suggest_float('learning_rate', 0.01, 0.3, log=True),
'reg_alpha': trial.suggest_float('reg_alpha', 1e-8, 10.0, log=True),
}
# n_trials=20 is the default. Increase for better results (50-200 recommended).
results, study = bayesian_search_forecaster(
forecaster=forecaster,
y=data['target'],
exog=exog,
cv=cv,
search_space=search_space,
metric='mean_absolute_error',
n_trials=20,
random_state=123,
return_best=True, # Automatically updates forecaster with best params
n_jobs='auto',
show_progress=True,
output_file='search_results.csv', # Save results incrementally
)
# results is a DataFrame sorted by metric (best first)
# study is the full Optuna Study; access the best trial with study.best_trial
from skforecast.model_selection import grid_search_forecaster
# Different lag configurations to try
lags_grid = [3, 10, 24, [1, 2, 3, 23, 24]]
param_grid = {
'n_estimators': [50, 100, 200],
'max_depth': [5, 10, 15],
'learning_rate': [0.01, 0.1],
}
results = grid_search_forecaster(
forecaster=forecaster,
y=data['target'],
exog=exog,
cv=cv,
lags_grid=lags_grid,
param_grid=param_grid,
metric='mean_absolute_error',
return_best=True,
n_jobs='auto',
show_progress=True,
)
from skforecast.model_selection import random_search_forecaster
# Note: uses param_distributions (not param_grid) and n_iter
param_distributions = {
'n_estimators': [50, 100, 200, 500],
'max_depth': [3, 5, 10, 15],
'learning_rate': [0.01, 0.05, 0.1, 0.3],
}
results = random_search_forecaster(
forecaster=forecaster,
y=data['target'],
exog=exog,
cv=cv,
lags_grid=lags_grid,
param_distributions=param_distributions,
n_iter=10, # Number of random parameter combinations to try
random_state=123,
metric='mean_absolute_error',
return_best=True,
n_jobs='auto',
show_progress=True,
)
from skforecast.recursive import ForecasterRecursiveMultiSeries
from skforecast.model_selection import bayesian_search_forecaster_multiseries
forecaster = ForecasterRecursiveMultiSeries(
estimator=LGBMRegressor(random_state=123),
lags=24,
encoding='ordinal',
)
cv = TimeSeriesFold(
steps=12,
initial_train_size=len(series) - 100,
refit=False,
)
results, study = bayesian_search_forecaster_multiseries(
forecaster=forecaster,
series=series,
exog=exog,
cv=cv,
search_space=search_space,
metric='mean_absolute_error',
aggregate_metric=['weighted_average', 'average', 'pooling'], # Default
levels=None, # None = evaluate all series; or list of series names
n_trials=20,
return_best=True,
n_jobs='auto',
show_progress=True,
)
# Access the best trial with study.best_trial
# results includes `n_evaluated` after the metrics (points evaluated per candidate)
Each candidate is evaluated on the series and folds it can predict: a series
with window_size observations or fewer before a fold is not predicted by a
candidate with that window. Candidates with more lags (or longer window
features) can then compute their metric on fewer points, often the easy ones,
and win the ranking without being better.
n_evaluated of the results (and the user_attr n_evaluated of
each trial) is the number of points in the metrics of each candidate, summed
over the levels.MissingValuesWarning is raised at the end of the
search, saying whether the best candidate is one of them and which series
every candidate evaluates on the same points (the list, or the series to
leave out, when it is short).levels (for short
series, those with more observations than the largest window_size before
the first fold), or remove the candidates with larger windows.return_best=True, the refit of ForecasterRecursiveMultiSeries
leaves out the series with window_size observations or fewer for the best
candidate, with a RuntimeWarning: the forecaster returned is not trained
with them (they are not in series_names_in_).OneStepAheadFold,
dropna_from_series=True and gaps in y: larger windows drop more test
rows. Fill the gaps of y or remove the candidates with larger windows.from skforecast.recursive import ForecasterStats
from skforecast.stats import Arima
from skforecast.model_selection import grid_search_stats
forecaster = ForecasterStats(estimator=Arima(order=(1, 1, 1)))
param_grid = {
'order': [(1, 0, 0), (1, 1, 0), (1, 1, 1), (2, 1, 1)],
'seasonal_order': [(0, 0, 0), (1, 1, 1)],
'm': [12],
}
results = grid_search_stats(
forecaster=forecaster,
y=data['target'],
cv=cv,
param_grid=param_grid,
metric='mean_absolute_error',
return_best=True,
)
ForecasterFoundation is zero-shot: no weights are trained, so only the
inference-time configuration is tuned. The highest-impact parameter is
context_length (how many past observations are fed to the model). Use
bayesian_search_foundation, which evaluates each trial with
backtesting_foundation.
from skforecast.foundation import FoundationModel, ForecasterFoundation
from skforecast.model_selection import bayesian_search_foundation, TimeSeriesFold
forecaster = ForecasterFoundation(
estimator=FoundationModel(model_id='autogluon/chronos-2-small', device_map='auto')
)
# TimeSeriesFold only: OneStepAheadFold raises TypeError
cv = TimeSeriesFold(steps=24, initial_train_size=len(series) - 200, refit=False)
def search_space(trial):
return {
'context_length': trial.suggest_categorical('context_length', [512, 1024, 2048, 4096]),
'cross_learning': trial.suggest_categorical('cross_learning', [True, False]),
}
results, study = bayesian_search_foundation(
forecaster=forecaster,
series=series,
cv=cv,
search_space=search_space,
metric='mean_absolute_error',
n_trials=30,
return_best=True,
)
Differences from bayesian_search_forecaster: no lags in search_space, no
n_jobs, TimeSeriesFold only, and every search_space key must be a valid
adapter parameter. Search context_length and the adapter's quality-relevant
parameters; device/dtype and other runtime settings are accepted but cannot
improve accuracy, and several parameters force an expensive model reload per
trial. Per-adapter tunables and reload matrix: the foundation-forecasting
skill (references/adapter-parameters.md).
from skforecast.model_selection import OneStepAheadFold
# Much faster than TimeSeriesFold: no recursive predictions needed
cv_fast = OneStepAheadFold(
initial_train_size=len(data) - 100,
)
results, study = bayesian_search_forecaster(
forecaster=forecaster,
y=data['target'],
cv=cv_fast,
search_space=search_space,
metric='mean_absolute_error',
n_trials=100,
return_best=True,
)
# Access the best trial with study.best_trial
return_best=True: The forecaster is not updated with the best parameters unless this is True.OneStepAheadFold first for fast screening, then validate the top candidates with TimeSeriesFold.search_space(); this is often the most impactful parameter.lags in a foundation search_space: bayesian_search_foundation has no lag concept; any key that is not an adapter parameter raises ValueError.n_evaluated differs between candidates (MissingValuesWarning at the end of the search), their metrics are not comparable. Restrict levels or the range of windows as described in Series of different length.n_evaluated: it is the column with the points evaluated, so every search raises ValueError.y=data.loc[:end_validation]). With return_best=True the forecaster is refitted on everything the search receives, so keep the test set out and evaluate the refitted forecaster with backtesting_forecaster on it.initial_train_size, also with OneStepAheadFold) are left out of the results and reported in a single RuntimeWarning at the end of the search, grouped by error. Bayesian trials are marked as failed in the study and listed by number; an error in search_space stops the search. suppress_warnings=True does not hide it. The other warnings of the candidates (or trials) are also shown once, with the number of candidates in which they are raised and, if their texts differ, the details of the first one.See references/search-parameters.md for
the complete parameter comparison across all 9 search functions, function
routing by forecaster type, and lags_grid / search_space / param_grid
usage details.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
17 skills in this plugin
/autocorrelation-and-lag-selectionAnalyzes time series dynamics with the fast skforecast.stats functions acf, pacf and calculate_lag_autocorrelation. Covers reading ACF/PACF patterns to identify AR/MA orders and seasonality, ranking lags by partial autocorrelation, and feeding the result to the lags argument of any skforecast forecaster. Use when the user wants to understand the dynamics of a series, choose a candidate set of lags before hyperparameter tuning, or replace a slow statsmodels acf/pacf call.
/backtesting-configurationConfigures TimeSeriesFold parameters for backtesting based on deployment scenarios. Maps business requirements (retraining frequency, forecast horizon, data budget) to cross-validation strategy parameters. Use when the user describes how they plan to deploy or evaluate a model.
/baseline-forecastingBuilds and evaluates simple baseline forecasts with ForecasterEquivalentDate (equivalent-date / seasonal-naive / moving-average) to benchmark machine learning models. Covers offset (int vs pandas DateOffset), n_offsets with agg_func, backtesting a baseline, comparing against ML with MASE, conformal intervals, and grid_search_equivalent_date. Use when the user wants a baseline, a naive or seasonal reference, or to check whether a model beats a simple rule. Not for choosing among ML forecasters (see choosing-a-forecaster) or tuning ML hyperparameters (see hyperparameter-optimization).
/choosing-a-forecasterGuides selection of the appropriate skforecast forecaster based on the user's data characteristics and requirements. Provides a decision matrix mapping use cases to forecaster classes. Use when the user is unsure which forecaster to use or asks for a recommendation.
/complete-api-referenceProvides complete constructor and method signatures for all skforecast forecasters, backtesting functions, search functions, cross-validation classes, preprocessing, feature selection, and drift detection. Use when the user needs exact parameter names, types, or defaults for any skforecast class or function.
/deep-learning-forecastingForecasts time series using recurrent neural networks (RNN, LSTM, GRU) with ForecasterRnn and the create_and_compile_model helper. Covers model architecture, training, and multi-series deep learning. Use when the user wants to use deep learning / neural networks for time series forecasting.
/skforecast:hyperparameter-optimizationfrom skforecast
npx claudepluginhub skforecast/skforecast --plugin skforecastOther plugins' skills for the same job