"""Exponentially weighted market beta descriptor."""
# Copyright (c) 2023-2026
# Author: Hugo Delatte <hugo.delatte@skfoliolabs.com>
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import Any
import numpy as np
from skfolio.containers import MISSING_CATEGORY_CODE, AssetPanel
from skfolio.descriptor._base import BaseDescriptor
from skfolio.descriptor._utils import (
_EWRegression,
_ReturnAverager,
_warn_deprecated_eps,
)
from skfolio.typing import FloatArray, IntArray
from skfolio.utils.stats import _market_returns
from skfolio.utils.tools import (
_validate_positive_integer,
_validate_positive_real,
half_life_to_decay_factor,
)
from skfolio.utils.validation import validate_asset_panel
_FITTED_ATTR = "market_beta_"
[docs]
class EWMarketBeta(BaseDescriptor):
r"""Exponentially weighted market beta descriptor.
Measures each asset's sensitivity to the market portfolio using exponentially
weighted covariance and variance estimates [1]_:
.. math::
\beta_i = \frac{\text{Cov}(r_i, r_m)}{\text{Var}(r_m)}
where :math:`r_i` is the return of asset :math:`i`, :math:`r_m` is the cap-weighted
market return computed on the estimation universe and the EWMA uses decay
:math:`\lambda = \exp(-\ln(2) / \text{half\_life})`.
Parameters
----------
half_life : float, default=60.0
EWMA half-life in observations after aggregation. For example, with
`aggregation_period=5` and `half_life=60`, the EWMA decays over 60 aggregated
periods, equivalent to 300 raw observations.
aggregation_period : int, default=1
Number of consecutive observations to aggregate before updating EWMA statistics.
Aggregation can reduce desynchronization effects. Asset and market returns are
averaged over the same observations, as described in Notes.
min_periods : int, optional
Minimum number of observations required before computing each asset's market
beta. With aggregation enabled, each average counts as one observation. Until
this count is reached, the asset's output is NaN. If `None`, defaults to
:math:`\lceil\text{half\_life}\rceil`, with a minimum of 1.
shrinkage_group : str, optional
Name of a categorical field containing group labels (e.g., `"industry"`) for
Bayesian shrinkage. When provided, raw betas are shrunk toward the cap-weighted
group mean using an empirical Bayes approach:
.. math::
\beta_i^{\text{shrunk}} = w_i \cdot \beta_i^{\text{raw}}
+ (1 - w_i) \cdot \mu_g
where :math:`w_i = \tau_g^2 / (\tau_g^2 + \sigma_i^2)`, :math:`\mu_g` is the
cap-weighted group mean, :math:`\tau_g^2` is the prior variance (cross-sectional
variance minus noise) and :math:`\sigma_i^2` is the estimation error variance.
Assets with missing category codes or non-positive market capitalization are
excluded from shrinkage. If `None` (default), no shrinkage is applied.
min_group_size : int, default=5
Minimum number of assets in a group to compute group-specific statistics.
Groups with fewer assets fall back to global (cross-sectional) statistics.
Only used when `shrinkage_group` is provided.
shrinkage_bounds : tuple of float, default=(0.0, 1.0)
Lower and upper bounds `(w_min, w_max)` for the raw-beta weight
:math:`w_i`. Lower values apply more shrinkage toward the group mean, while
higher values keep more of the raw beta. The coefficient is clipped to this
range after estimation.
For example, `(0.1, 0.9)` keeps at least 10% weight on the raw beta and at
least 10% weight on the group mean. Only used when `shrinkage_group` is
provided.
eps : float, optional
Deprecated and ignored. It will be removed in version 2.0.
Supplying a positive value emits a `FutureWarning`.
Attributes
----------
n_assets_ : int
Number of assets seen during fitting.
asset_names_ : ndarray of shape (n_assets,)
Asset names seen during fitting.
market_beta_ : ndarray of shape (n_assets,)
Last fitted market beta value for each asset.
Notes
-----
NaNs are allowed as missing observations. Non-missing `returns` values must be
finite. Covariance and market variance use the same observations for each asset,
with `X.active_mask=True` and non-missing returns. This is equivalent to regression
with an intercept. Missing returns do not reset estimates. Setting
`X.active_mask=False` resets estimates and sets output to NaN. Too little variation
in market returns also produces NaN.
Shrinkage assumes independent errors with constant variance. It requires at least
three observations and an estimable beta variance. Otherwise, assets subject to
shrinkage return NaN.
Market returns are the `X["market_cap"]`-weighted average of `X["returns"]` where
`X.estimation_mask=True` and both fields are finite. A `ValueError` is raised if
these assets have no positive total market capitalization at any observation.
References
----------
.. [1] "Capital asset prices: A theory of market equilibrium under conditions of
risk". The Journal of Finance. Sharpe, W. F. (1964).
"""
market_beta_: FloatArray
def __init__(
self,
half_life: float = 60.0,
aggregation_period: int = 1,
min_periods: int | None = None,
shrinkage_group: str | None = None,
min_group_size: int = 5,
shrinkage_bounds: tuple[float, float] = (0.0, 1.0),
eps: float | None = None,
) -> None:
self.half_life = half_life
self.aggregation_period = aggregation_period
self.min_periods = min_periods
self.shrinkage_group = shrinkage_group
self.min_group_size = min_group_size
self.shrinkage_bounds = shrinkage_bounds
self.eps = eps
def _reset(self) -> None:
"""Reset fitted state."""
if hasattr(self, _FITTED_ATTR):
delattr(self, _FITTED_ATTR)
def _validate_params(self) -> None:
"""Validate constructor parameters."""
_validate_positive_real(self.half_life, "half_life")
_validate_positive_integer(self.aggregation_period, "aggregation_period")
if self.min_periods is not None:
_validate_positive_integer(self.min_periods, "min_periods")
_validate_positive_integer(self.min_group_size, "min_group_size")
if (
len(self.shrinkage_bounds) != 2
or self.shrinkage_bounds[0] < 0
or self.shrinkage_bounds[1] > 1
or self.shrinkage_bounds[0] > self.shrinkage_bounds[1]
):
raise ValueError(
f"shrinkage_bounds must be (w_min, w_max) with "
f"0 <= w_min <= w_max <= 1, got {self.shrinkage_bounds}"
)
_warn_deprecated_eps(self.eps)
def _initialize(self) -> None:
"""Initialize regression statistics and return averaging."""
self._min_periods = (
max(1, int(np.ceil(self.half_life)))
if self.min_periods is None
else int(self.min_periods)
)
self._shrinkage_enabled = self.shrinkage_group is not None
self._regression = _EWRegression(
n_assets=self.n_assets_,
decay=half_life_to_decay_factor(self.half_life),
estimate_beta_variance=self._shrinkage_enabled,
)
# Reuse the last betas while collecting returns for the next average.
self._betas = np.full(self.n_assets_, np.nan)
self._averager = _ReturnAverager(
n_assets=self.n_assets_,
n_variables=2,
aggregation_period=int(self.aggregation_period),
)
def _apply_shrinkage(
self, raw_betas: FloatArray, group_labels: IntArray, market_cap: FloatArray
) -> FloatArray:
"""Apply Bayesian shrinkage to raw betas using group priors.
Uses Empirical Bayes (James-Stein) shrinkage where each asset's beta is pulled
toward the cap-weighted group mean. The shrinkage intensity depends on the ratio
of true cross-sectional variance to estimation noise.
Parameters
----------
raw_betas : ndarray of shape (n_assets,)
Raw EWMA betas.
group_labels : ndarray of shape (n_assets,)
Group label for each asset (e.g., industry).
market_cap : ndarray of shape (n_assets,)
Market capitalization for each asset.
Returns
-------
shrunk_betas : ndarray of shape (n_assets,)
Shrunk betas.
"""
shrunk_betas = raw_betas.copy()
# Estimate each raw beta's sampling variance from the same observations.
beta_error_variance = self._regression.beta_variance(raw_betas)
valid_beta = np.isfinite(raw_betas)
valid_group = group_labels != MISSING_CATEGORY_CODE
valid_mcap = np.isfinite(market_cap) & (market_cap > 0)
shrinkable = valid_beta & valid_group & valid_mcap
valid = shrinkable & np.isfinite(beta_error_variance)
# Shrinkage requires an available uncertainty estimate.
shrunk_betas[shrinkable & ~valid] = np.nan
if not valid.any():
return shrunk_betas
# Compute global statistics (used as fallback for small groups)
global_beta_mean = np.average(raw_betas[valid], weights=market_cap[valid])
global_observed_variance = np.average(
(raw_betas[valid] - global_beta_mean) ** 2, weights=market_cap[valid]
)
global_mean_error_variance = np.mean(beta_error_variance[valid])
# Prior variance = observed variance - estimation noise (floored at 0)
global_prior_variance = max(
global_observed_variance - global_mean_error_variance, 0.0
)
# Process each group
unique_groups = np.unique(group_labels[valid])
for group in unique_groups:
group_mask = valid & (group_labels == group)
group_size = group_mask.sum()
if group_size < self.min_group_size:
# Small group: fall back to global prior
group_beta_mean = global_beta_mean
group_prior_variance = global_prior_variance
else:
# Compute group-specific prior (cap-weighted)
group_beta_mean = np.average(
raw_betas[group_mask], weights=market_cap[group_mask]
)
group_observed_variance = np.average(
(raw_betas[group_mask] - group_beta_mean) ** 2,
weights=market_cap[group_mask],
)
mean_error_variance = np.mean(beta_error_variance[group_mask])
group_prior_variance = max(
group_observed_variance - mean_error_variance, 0.0
)
# Higher weight keeps more of the raw beta. Lower weight shrinks more
# toward the group mean
raw_beta_weight = (
group_prior_variance
/ (group_prior_variance + beta_error_variance[group_mask])
if group_prior_variance > 0
else np.zeros(group_size)
)
# Clip to bounds for robustness
w_min, w_max = self.shrinkage_bounds
raw_beta_weight = np.clip(raw_beta_weight, w_min, w_max)
# Apply shrinkage
shrunk_betas[group_mask] = (
raw_beta_weight * raw_betas[group_mask]
+ (1 - raw_beta_weight) * group_beta_mean
)
return shrunk_betas