<a id="skfolio-prior-timeseriesfactormodel"></a>

# skfolio.prior.TimeSeriesFactorModel

<a id="skfolio.prior.TimeSeriesFactorModel"></a>

### *class* skfolio.prior.TimeSeriesFactorModel(loading_matrix_estimator=None, factor_prior_estimator=None, factor_families=None, higham=False, max_iteration=100)

Time-series factor model estimator.

The purpose of factor models is to impose a structure on financial
variables and their covariance matrix by explaining them through a small
number of common factors. This reduces the number of free parameters in
the estimation problem, making portfolio optimization more robust against
noise. Factor models also provide a decomposition of risk into systematic
and idiosyncratic components.

This estimator implements a time-series regression approach: for each
asset $i$, the return is regressed on a common set of factor return
series:

$$
r_i(t) = a_i + B_i \, f(t) + \epsilon_i(t)
$$

where $B_i$ is the factor loadings (exposures), $f(t)$ is the
vector of factor returns, $a_i$ is the intercept of asset $i$’s
time-series regression, and $\epsilon_i(t)$ is the idiosyncratic return,
obtained as the regression residual.

The expected return vector is:

$$
\mu = B \, \mathbb{E}[f] + a
$$

and the covariance matrix is:

$$
\Sigma = B \, F \, B^\top + D
$$

where $F$ is the factor covariance matrix and $D$ is the
diagonal matrix of idiosyncratic variances.

#### NOTE
This formulation assumes that the factors are tradable assets or portfolios
(e.g. long-short equity factors or ETF returns), so that the
factor sample mean is a valid estimate of the factor risk premium.
When factors are non-tradable variables (e.g. macroeconomic series),
sometimes called a *macroeconomic factor model* in the literature,
the sample mean no longer equals the risk premium and a two-pass
procedure such as Fama-MacBeth (1973) is required to estimate the
cross-sectional price of risk $\lambda$. That procedure also
requires a large estimation universe in order to reliably identify the
factor risk premia.

* **Parameters:**
  **loading_matrix_estimator** *LoadingMatrixEstimator, optional*
  : Estimator of the loading matrix (betas) of the factors.
    The default (`None`) is to use [`LoadingMatrixRegression`](https://skfolio.org/generated/skfolio.prior.LoadingMatrixRegression.html.md#skfolio.prior.LoadingMatrixRegression)
    which fits the factors using `LassoCV` on each asset separately.

  **factor_prior_estimator** *BasePrior, optional*
  : Estimator of the factor return distribution. It is used to estimate
    the [`ReturnDistribution`](https://skfolio.org/generated/skfolio.prior.ReturnDistribution.html.md#skfolio.prior.ReturnDistribution) containing expected factor
    returns and the factor covariance matrix.
    The default (`None`) is to use [`EmpiricalPrior`](https://skfolio.org/generated/skfolio.prior.EmpiricalPrior.html.md#skfolio.prior.EmpiricalPrior).

  **factor_families** *array-like of shape (n_factors,), optional*
  : Family label for each factor. When provided, the labels are stored in the
    [`FactorModel`](https://skfolio.org/generated/skfolio.prior.FactorModel.html.md#skfolio.prior.FactorModel) and can be used by downstream diagnostics,
    plots and optimization constraints referencing factor families. The default
    (`None`) means that no family labels are attached to the factors.

  **higham** *bool, default=False*
  : If this is set to True, the Higham (2002) algorithm is used to find
    the nearest positive semi-definite covariance matrix. It is more
    accurate but slower than the default clipping method. For more
    information see [`cov_nearest`](https://skfolio.org/generated/skfolio.utils.stats.cov_nearest.html.md#skfolio.utils.stats.cov_nearest).

  **max_iteration** *int, default=100*
  : Only used when `higham` is set to True. Maximum number of iterations
    of the Higham (2002) algorithm.
* **Attributes:**
  **return_distribution_** *ReturnDistribution*
  : Fitted [`ReturnDistribution`](https://skfolio.org/generated/skfolio.prior.ReturnDistribution.html.md#skfolio.prior.ReturnDistribution) containing the
    asset distribution and moments estimation based on the factor model.

  **factor_prior_estimator_** *BasePrior*
  : Fitted `factor_prior_estimator`.

  **loading_matrix_estimator_** *BaseLoadingMatrix*
  : Fitted `loading_matrix_estimator`.

  **n_features_in_** *int*
  : Number of assets seen during `fit`.

  **feature_names_in_** *ndarray of shape (`n_features_in_`,)*
  : Names of features seen during `fit`. Defined only when `X`
    has feature names that are all strings.

### Methods

| [`fit`](#skfolio.prior.TimeSeriesFactorModel.fit)(X[, y])                    | Fit the Time-series factor model estimator.                                      |
|---------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| [`get_metadata_routing`](#skfolio.prior.TimeSeriesFactorModel.get_metadata_routing)()         | Get metadata routing of this object.                                             |
| [`get_params`](#skfolio.prior.TimeSeriesFactorModel.get_params)([deep])             | Get parameters for this estimator.                                               |
| [`set_fit_request`](#skfolio.prior.TimeSeriesFactorModel.set_fit_request)(\*[, factors]) | Configure whether metadata should be requested to be passed to the `fit` method. |
| [`set_params`](#skfolio.prior.TimeSeriesFactorModel.set_params)(\*\*params)         | Set the parameters of this estimator.                                            |

<a id="skfolio.prior.TimeSeriesFactorModel.fit"></a>

#### fit(X, y=None, \*, factors, \*\*fit_params)

Fit the Time-series factor model estimator.

* **Parameters:**
  **X** *array-like of shape (n_observations, n_assets)*
  : Price returns of the assets.

  **y** *None*
  : Not used, present for scikit-learn compatibility.

  **factors** *array-like of shape (n_observations, n_factors)*
  : Factors’ returns.

  **\*\*fit_params** *dict*
  : Parameters to pass to the underlying estimators.
    Only available if `enable_metadata_routing=True`, which can be
    set by using `sklearn.set_config(enable_metadata_routing=True)`.
    See [Metadata Routing User Guide](https://skfolio.org/user_guide/metadata_routing.html.md#metadata-routing) for
    more details.
* **Returns:**
  **self** *TimeSeriesFactorModel*
  : Fitted estimator.

<a id="skfolio.prior.TimeSeriesFactorModel.get_metadata_routing"></a>

#### get_metadata_routing()

Get metadata routing of this object.

Please check [User Guide](https://skfolio.org/user_guide/metadata_routing.html.md#metadata-routing) on how the routing
mechanism works.

* **Returns:**
  **routing** *MetadataRequest*
  : A `MetadataRequest` encapsulating
    routing information.

<a id="skfolio.prior.TimeSeriesFactorModel.get_params"></a>

#### get_params(deep=True)

Get parameters for this estimator.

* **Parameters:**
  **deep** *bool, default=True*
  : If True, will return the parameters for this estimator and
    contained subobjects that are estimators.
* **Returns:**
  **params** *dict*
  : Parameter names mapped to their values.

<a id="skfolio.prior.TimeSeriesFactorModel.set_fit_request"></a>

#### set_fit_request(\*, factors='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the `fit` method.

Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with `enable_metadata_routing=True` (see `sklearn.set_config`).
Please check the [User Guide](https://skfolio.org/user_guide/metadata_routing.html.md#metadata-routing) on how the routing
mechanism works.

The options for each parameter are:

- `True`: metadata is requested, and passed to `fit` if provided. The request is ignored if metadata is not provided.
- `False`: metadata is not requested and the meta-estimator will not pass it to `fit`.
- `None`: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
- `str`: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (`sklearn.utils.metadata_routing.UNCHANGED`) retains the
existing request. This allows you to change the request for some
parameters and not others.

#### Versionadded
Added in version 1.3.

* **Parameters:**
  **factors** *str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED*
  : Metadata routing for `factors` parameter in `fit`.
* **Returns:**
  **self** *object*
  : The updated object.

<a id="skfolio.prior.TimeSeriesFactorModel.set_params"></a>

#### set_params(\*\*params)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects
(such as `Pipeline`). The latter have
parameters of the form `<component>__<parameter>` so that it’s
possible to update each component of a nested object.

* **Parameters:**
  **\*\*params** *dict*
  : Estimator parameters.
* **Returns:**
  **self** *estimator instance*
  : Estimator instance.

