code: def bayesian_search_forecaster(
      forecaster,
      y: pd.Series,
      search_space: Callable,
      steps: int,
      metric: Union[str, Callable, list],
      initial_train_size: int,
      fixed_train_size: bool = True,
      gap: int = 0,
      allow_incomplete_fold: bool = True,
      exog: Optional[Union[pd.Series, pd.DataFrame]] = None,
      lags_grid: Optional[Union[list, dict]] = None,
      refit: Optional[Union[bool, int]] = False,
      n_trials: int = 10,
      random_state: int = 123,
      return_best: bool = True,
      n_jobs: Optional[Union[int, str]] = "auto",
      verbose: bool = True,
      show_progress: bool = True,
      engine: str = "optuna",
      kwargs_create_study: dict = {},
      kwargs_study_optimize: dict = {},
  ) -> Tuple[pd.DataFrame, object]:
      """
      Bayesian optimization for a Forecaster object using time series backtesting and
      optuna library.
  
      Parameters
      ----------
      forecaster : ForecasterAutoreg, ForecasterAutoregCustom, ForecasterAutoregDirect
          Forecaster model.
      y : pandas Series
          Training time series.
      search_space : Callable (optuna)
          Function with argument `trial` which returns a dictionary with parameters names
          (`str`) as keys and Trial object from optuna (trial.suggest_float,
          trial.suggest_int, trial.suggest_categorical) as values.
      steps : int
          Number of steps to predict.
      metric : str, Callable, list
          Metric used to quantify the goodness of fit of the model.
  
          - If `string`: {'mean_squared_error', 'mean_absolute_error',
          'mean_absolute_percentage_error', 'mean_squared_log_error'}
          - If `Callable`: Function with arguments y_true, y_pred that returns
          a float.
          - If `list`: List containing multiple strings and/or Callables.
      initial_train_size : int
          Number of samples in the initial train split.
      fixed_train_size : bool, default `True`
          If True, train size doesn't increase but moves by `steps` in each iteration.
      gap : int, default `0`
          Number of samples to be excluded after the end of each training set and
          before the test set.
      allow_incomplete_fold : bool, default `True`
          Last fold is allowed to have a smaller number of samples than the
          `test_size`. If `False`, the last fold is excluded.
      exog : pandas Series, pandas DataFrame, default `None`
          Exogenous variable/s included as predictor/s. Must have the same
          number of observations as `y` and should be aligned so that y[i] is
          regressed on exog[i].
      lags_grid : list, dict, default `None`
          Lists of lags to try, containing int, lists, numpy ndarray, or range
          objects. If `dict`, the keys are used as labels in the `results`
          DataFrame, and the values are used as the lists of lags to try. Ignored
          if the forecaster is an instance of `ForecasterAutoregCustom` or
          `ForecasterAutoregMultiSeriesCustom`.
      refit : bool, int, default `False`
          Whether to re-fit the forecaster in each iteration. If `refit` is an integer,
          the Forecaster will be trained every that number of iterations.
      n_trials : int, default `10`
          Number of parameter settings that are sampled in each lag configuration.
      random_state : int, default `123`
          Sets a seed to the sampling for reproducible output.
      return_best : bool, default `True`
          Refit the `forecaster` using the best found parameters on the whole data.
      n_jobs : int, 'auto', default `'auto'`
          The number of jobs to run in parallel. If `-1`, then the number of jobs is
          set to the number of cores. If 'auto', `n_jobs` is set using the function
          skforecast.utils.select_n_jobs_backtesting.
          **New in version 0.9.0**
      verbose : bool, default `True`
          Print number of folds used for cv or backtesting.
      show_progress: bool, default `True`
          Whether to show a progress bar.
      engine : str, default `'optuna'`
          Bayesian optimization runs through the optuna library.
      kwargs_create_study : dict, default `{'direction': 'minimize', 'sampler': TPESampler(seed=123)}`
          Only applies to engine='optuna'. Keyword arguments (key, value mappings)
          to pass to optuna.create_study.
      kwargs_study_optimize : dict, default `{}`
          Only applies to engine='optuna'. Other keyword arguments (key, value mappings)
          to pass to study.optimize().
  
      Returns
      -------
      results : pandas DataFrame
          Results for each combination of parameters.
  
          - column lags: lags configuration for each iteration.
          - column params: parameters configuration for each iteration.
          - column metric: metric value estimated for each iteration.
          - additional n columns with param = value.
      results_opt_best : optuna object
          The best optimization result returned as a FrozenTrial optuna object.
  
      """
  
      if return_best and exog is not None and (len(exog) != len(y)):
          raise ValueError(
              (
                  f"`exog` must have same number of samples as `y`. "
                  f"length `exog`: ({len(exog)}), length `y`: ({len(y)})"
              )
          )
  
      if engine == "skopt":
          warnings.warn(
              (
                  "The engine 'skopt' for `bayesian_search_forecaster` is deprecated "
                  "in favor of 'optuna' engine. To continue using it, use skforecast "
                  "0.6.0. The optimization will be performed using the 'optuna' engine."
              )
          )
          engine = "optuna"
  
      if engine not in ["optuna"]:
          raise ValueError(
              f"`engine` only allows 'optuna', got {engine}."
          )
  
      results, results_opt_best = _bayesian_search_optuna(
          forecaster=forecaster,
          y=y,
          exog=exog,
          lags_grid=lags_grid,
          search_space=search_space,
          steps=steps,
          metric=metric,
          refit=refit,
          initial_train_size=initial_train_size,
          fixed_train_size=fixed_train_size,
          gap=gap,
          allow_incomplete_fold=allow_incomplete_fold,
          n_trials=n_trials,
          random_state=random_state,
          return_best=return_best,
          n_jobs=n_jobs,
          verbose=verbose,
          show_progress=show_progress,
          kwargs_create_study=kwargs_create_study,
          kwargs_study_optimize=kwargs_study_optimize,
      )
  
      return results, results_opt_best
  
imports: from typing import Union, Tuple, Optional, Callable
  import numpy
  import pandas
  import warnings
  import logging
  from copy import deepcopy
  from joblib import Parallel, delayed, cpu_count
  from tqdm.auto import tqdm
  from sklearn.metrics import mean_squared_error, mean_absolute_error, mean_absolute_percentage_error, mean_squared_log_error
  from sklearn.model_selection import ParameterGrid
  from sklearn.model_selection import ParameterSampler
  import optuna
  from optuna.samplers import TPESampler, RandomSampler
  from ..exceptions import LongTrainingWarning
  from ..utils import check_backtesting_input
  from ..utils import initialize_lags_grid
  from ..utils import select_n_jobs_backtesting
label_desc: Use image node_id 8 for calling a global function with example usage: bayesian_search_forecaster(forecaster, y, search_space, steps, metric, initial_train_size, fixed_train_size, gap, allow_incomplete_fold, exog, lags_grid, refit, n_trials, random_state, return_best, n_jobs, verbose, show_progress, engine, kwargs_create_study, kwargs_study_optimize) and returns: results,  results_opt_best