Skip to content

Finance API

Returns

price_returns

price_returns

price_returns(
    prices: ArrayLike,
    *,
    periods: int = 1,
    method: str = "log"
)

Compute simple or logarithmic returns while preserving time alignment.

Parameters

prices: One price series or a matrix whose rows are ordered observations and whose columns are assets. periods: Number of observations between consecutive prices. method: "log" for log returns or "simple" for arithmetic returns.

Returns

Same container type as prices when a pandas Series/DataFrame is used; otherwise a NumPy array. The first periods observations are NaN.

Source code in src/capacities_ml_fin/finance/returns.py
def price_returns(
    prices: ArrayLike,
    *,
    periods: int = 1,
    method: str = "log",
):
    """Compute simple or logarithmic returns while preserving time alignment.

    Parameters
    ----------
    prices:
        One price series or a matrix whose rows are ordered observations and
        whose columns are assets.
    periods:
        Number of observations between consecutive prices.
    method:
        ``"log"`` for log returns or ``"simple"`` for arithmetic returns.

    Returns
    -------
    Same container type as ``prices`` when a pandas Series/DataFrame is used;
    otherwise a NumPy array. The first ``periods`` observations are ``NaN``.
    """
    periods = _validate_positive_integer(periods, name="periods")
    method = _validate_return_method(method)

    if isinstance(prices, (pd.Series, pd.DataFrame)):
        values = prices.astype(float)
        if method == "log":
            if (values <= 0.0).any().any() if isinstance(values, pd.DataFrame) else (values <= 0.0).any():
                raise ValueError("Log returns require strictly positive prices.")
            return np.log(values).diff(periods)
        return values.pct_change(periods=periods, fill_method=None)

    array = _to_float_array(prices)
    if method == "log" and np.any(array[np.isfinite(array)] <= 0.0):
        raise ValueError("Log returns require strictly positive prices.")

    result = np.full(array.shape, np.nan, dtype=float)
    current = array[periods:]
    previous = array[:-periods]
    if method == "log":
        result[periods:] = np.log(current) - np.log(previous)
    else:
        with np.errstate(divide="ignore", invalid="ignore"):
            result[periods:] = current / previous - 1.0
    return result

to_losses

to_losses

to_losses(returns: ArrayLike)

Convert returns to losses using loss = -return.

Parameters

returns : array-like Return series or panel.

Returns

ndarray, Series, or DataFrame Negated values with the original container and labels preserved.

Source code in src/capacities_ml_fin/finance/returns.py
def to_losses(returns: ArrayLike):
    """Convert returns to losses using ``loss = -return``.

    Parameters
    ----------
    returns : array-like
        Return series or panel.

    Returns
    -------
    ndarray, Series, or DataFrame
        Negated values with the original container and labels preserved.
    """
    if isinstance(returns, pd.Series):
        name = None if returns.name is None else f"{returns.name}_loss"
        return -returns.rename(name)
    if isinstance(returns, pd.DataFrame):
        return -returns
    return -_to_float_array(returns)

aggregate_returns

Trailing historical return aggregation.

aggregate_returns

aggregate_returns(
    returns: ArrayLike, *, horizon: int, method: str = "log"
)

Aggregate returns over a trailing historical horizon.

Parameters

returns : array-like Equally spaced return observations ordered through time. horizon : int Positive number of observations in each trailing window. method : {"log", "simple"}, default="log" Sum log returns or compound simple returns.

Returns

ndarray, Series, or DataFrame Trailing returns aligned at each window end. The first horizon - 1 rows are missing.

Notes

The value at time t contains no observation after t.

Source code in src/capacities_ml_fin/finance/returns.py
def aggregate_returns(
    returns: ArrayLike,
    *,
    horizon: int,
    method: str = "log",
):
    """Aggregate returns over a trailing historical horizon.

    Parameters
    ----------
    returns : array-like
        Equally spaced return observations ordered through time.
    horizon : int
        Positive number of observations in each trailing window.
    method : {"log", "simple"}, default="log"
        Sum log returns or compound simple returns.

    Returns
    -------
    ndarray, Series, or DataFrame
        Trailing returns aligned at each window end. The first
        ``horizon - 1`` rows are missing.

    Notes
    -----
    The value at time ``t`` contains no observation after ``t``.
    """
    horizon = _validate_positive_integer(horizon, name="horizon")
    method = _validate_return_method(method)

    if isinstance(returns, (pd.Series, pd.DataFrame)):
        values = returns.astype(float)
        if method == "log":
            return values.rolling(horizon, min_periods=horizon).sum()
        return (1.0 + values).rolling(horizon, min_periods=horizon).apply(
            np.prod,
            raw=True,
        ) - 1.0

    array = _to_float_array(returns)
    result = np.full(array.shape, np.nan, dtype=float)
    if array.shape[0] < horizon:
        return result

    for end in range(horizon - 1, array.shape[0]):
        window = array[end - horizon + 1 : end + 1]
        if np.any(~np.isfinite(window), axis=0).any() if window.ndim == 2 else np.any(~np.isfinite(window)):
            if window.ndim == 1:
                continue
            valid = np.all(np.isfinite(window), axis=0)
            if method == "log":
                result[end, valid] = np.sum(window[:, valid], axis=0)
            else:
                result[end, valid] = np.prod(1.0 + window[:, valid], axis=0) - 1.0
            continue
        if method == "log":
            result[end] = np.sum(window, axis=0)
        else:
            result[end] = np.prod(1.0 + window, axis=0) - 1.0
    return result

forward_returns

Forward supervised target construction.

forward_returns

forward_returns(
    returns: ArrayLike, *, horizon: int, method: str = "log"
)

Construct forward aggregate-return targets.

Parameters

returns : array-like Equally spaced returns ordered through time. horizon : int Number of future observations in each target. method : {"log", "simple"}, default="log" Sum log returns or compound simple returns.

Returns

ndarray, Series, or DataFrame Target at t formed from t + 1 through t + horizon. The final horizon rows are missing.

Notes

These values are supervised targets and must not be included among predictors available at time t.

Source code in src/capacities_ml_fin/finance/returns.py
def forward_returns(
    returns: ArrayLike,
    *,
    horizon: int,
    method: str = "log",
):
    """Construct forward aggregate-return targets.

    Parameters
    ----------
    returns : array-like
        Equally spaced returns ordered through time.
    horizon : int
        Number of future observations in each target.
    method : {"log", "simple"}, default="log"
        Sum log returns or compound simple returns.

    Returns
    -------
    ndarray, Series, or DataFrame
        Target at ``t`` formed from ``t + 1`` through ``t + horizon``.
        The final ``horizon`` rows are missing.

    Notes
    -----
    These values are supervised targets and must not be included among
    predictors available at time ``t``.
    """
    horizon = _validate_positive_integer(horizon, name="horizon")
    method = _validate_return_method(method)

    array = _to_float_array(returns)
    result = np.full(array.shape, np.nan, dtype=float)
    n_obs = array.shape[0]

    for position in range(max(0, n_obs - horizon)):
        window = array[position + 1 : position + horizon + 1]
        if window.ndim == 1:
            if not np.all(np.isfinite(window)):
                continue
            result[position] = (
                np.sum(window)
                if method == "log"
                else np.prod(1.0 + window) - 1.0
            )
            continue

        valid = np.all(np.isfinite(window), axis=0)
        if method == "log":
            result[position, valid] = np.sum(window[:, valid], axis=0)
        else:
            result[position, valid] = np.prod(1.0 + window[:, valid], axis=0) - 1.0

    return _wrap_like(returns, result)

forward_losses

forward_losses

forward_losses(
    returns: ArrayLike, *, horizon: int, method: str = "log"
)

Construct forward losses as negative forward aggregate returns.

Parameters

returns : array-like Return observations ordered through time. horizon : int Number of future observations per target. method : {"log", "simple"}, default="log" Return aggregation convention.

Returns

ndarray, Series, or DataFrame Forward targets under the loss = -return convention.

Source code in src/capacities_ml_fin/finance/returns.py
def forward_losses(
    returns: ArrayLike,
    *,
    horizon: int,
    method: str = "log",
):
    """Construct forward losses as negative forward aggregate returns.

    Parameters
    ----------
    returns : array-like
        Return observations ordered through time.
    horizon : int
        Number of future observations per target.
    method : {"log", "simple"}, default="log"
        Return aggregation convention.

    Returns
    -------
    ndarray, Series, or DataFrame
        Forward targets under the ``loss = -return`` convention.
    """
    future = forward_returns(returns, horizon=horizon, method=method)
    return to_losses(future)

excess_returns

excess_returns

excess_returns(
    returns: ArrayLike, risk_free: ArrayLike | float
)

Subtract an aligned risk-free return from asset returns.

Parameters

returns : array-like Asset returns. risk_free : float or array-like Scalar or aligned risk-free returns.

Returns

ndarray, Series, or DataFrame Arithmetic excess returns with pandas labels aligned when present.

Source code in src/capacities_ml_fin/finance/returns.py
def excess_returns(returns: ArrayLike, risk_free: ArrayLike | float):
    """Subtract an aligned risk-free return from asset returns.

    Parameters
    ----------
    returns : array-like
        Asset returns.
    risk_free : float or array-like
        Scalar or aligned risk-free returns.

    Returns
    -------
    ndarray, Series, or DataFrame
        Arithmetic excess returns with pandas labels aligned when present.
    """
    return _binary_pandas_operation(returns, risk_free, lambda x, y: x - y)

wealth_index

wealth_index

wealth_index(
    returns: ArrayLike,
    *,
    method: str = "simple",
    initial_value: float = 1.0
)

Convert returns into a cumulative wealth index.

Parameters

returns : array-like Simple or logarithmic returns ordered through time. method : {"simple", "log"}, default="simple" Compounding convention. initial_value : float, default=1.0 Positive initial wealth.

Returns

ndarray, Series, or DataFrame Cumulative wealth with the original shape and labels.

Source code in src/capacities_ml_fin/finance/returns.py
def wealth_index(
    returns: ArrayLike,
    *,
    method: str = "simple",
    initial_value: float = 1.0,
):
    """Convert returns into a cumulative wealth index.

    Parameters
    ----------
    returns : array-like
        Simple or logarithmic returns ordered through time.
    method : {"simple", "log"}, default="simple"
        Compounding convention.
    initial_value : float, default=1.0
        Positive initial wealth.

    Returns
    -------
    ndarray, Series, or DataFrame
        Cumulative wealth with the original shape and labels.
    """
    method = _validate_return_method(method)
    if not np.isfinite(initial_value) or initial_value <= 0.0:
        raise ValueError("initial_value must be a positive finite number.")

    if isinstance(returns, (pd.Series, pd.DataFrame)):
        values = returns.astype(float)
        if method == "simple":
            return initial_value * (1.0 + values).cumprod()
        return initial_value * np.exp(values.cumsum())

    array = _to_float_array(returns)
    if method == "simple":
        return initial_value * np.cumprod(1.0 + array, axis=0)
    return initial_value * np.exp(np.cumsum(array, axis=0))

Features

realized_volatility

realized_volatility

realized_volatility(
    returns: ArrayLike,
    *,
    window: int = 20,
    demean: bool = False,
    annualize: bool = False,
    periods_per_year: int = 252
)

Estimate trailing realized volatility from equally spaced returns.

Parameters

returns : array-like Return series or panel ordered through time. window : int, default=20 Number of observations in each trailing estimate. demean : bool, default=False Use the demeaned sample standard deviation when true; otherwise use the square root of summed squared returns. annualize : bool, default=False Scale the window estimate to an annualized value. periods_per_year : int, default=252 Annual frequency used when annualize=True.

Returns

ndarray, Series, or DataFrame Trailing volatility aligned at each window end.

Source code in src/capacities_ml_fin/finance/features.py
def realized_volatility(
    returns: ArrayLike,
    *,
    window: int = 20,
    demean: bool = False,
    annualize: bool = False,
    periods_per_year: int = 252,
):
    """Estimate trailing realized volatility from equally spaced returns.

    Parameters
    ----------
    returns : array-like
        Return series or panel ordered through time.
    window : int, default=20
        Number of observations in each trailing estimate.
    demean : bool, default=False
        Use the demeaned sample standard deviation when true; otherwise use
        the square root of summed squared returns.
    annualize : bool, default=False
        Scale the window estimate to an annualized value.
    periods_per_year : int, default=252
        Annual frequency used when ``annualize=True``.

    Returns
    -------
    ndarray, Series, or DataFrame
        Trailing volatility aligned at each window end.
    """
    window = _validate_positive_integer(window, name="window")
    periods_per_year = _validate_positive_integer(
        periods_per_year,
        name="periods_per_year",
    )

    if isinstance(returns, (pd.Series, pd.DataFrame)):
        values = returns.astype(float)
        if demean:
            result = values.rolling(window, min_periods=window).std(ddof=1) * np.sqrt(window)
        else:
            result = np.sqrt((values**2).rolling(window, min_periods=window).sum())
        if annualize:
            result = result * np.sqrt(periods_per_year / window)
        return result

    array = _to_float_array(returns)
    result = np.full(array.shape, np.nan, dtype=float)
    for end in range(window - 1, array.shape[0]):
        sample = array[end - window + 1 : end + 1]
        if sample.ndim == 1:
            if not np.all(np.isfinite(sample)):
                continue
            value = np.std(sample, ddof=1) * np.sqrt(window) if demean else np.sqrt(np.sum(sample**2))
            result[end] = value
            continue
        valid = np.all(np.isfinite(sample), axis=0)
        if demean:
            result[end, valid] = np.std(sample[:, valid], axis=0, ddof=1) * np.sqrt(window)
        else:
            result[end, valid] = np.sqrt(np.sum(sample[:, valid] ** 2, axis=0))
    if annualize:
        result *= np.sqrt(periods_per_year / window)
    return result

momentum

momentum

momentum(
    returns: ArrayLike,
    *,
    lookback: int = 252,
    skip: int = 21,
    method: str = "simple"
)

Compute trailing return momentum with an optional skip period.

Parameters

returns : array-like Return observations ordered through time. lookback : int, default=252 Total distance from the current observation to the start of the signal. skip : int, default=21 Most recent observations omitted from the signal. method : {"simple", "log"}, default="simple" Compound simple returns or sum log returns.

Returns

ndarray, Series, or DataFrame Momentum signal based only on information at or before t - skip.

Source code in src/capacities_ml_fin/finance/features.py
def momentum(
    returns: ArrayLike,
    *,
    lookback: int = 252,
    skip: int = 21,
    method: str = "simple",
):
    """Compute trailing return momentum with an optional skip period.

    Parameters
    ----------
    returns : array-like
        Return observations ordered through time.
    lookback : int, default=252
        Total distance from the current observation to the start of the signal.
    skip : int, default=21
        Most recent observations omitted from the signal.
    method : {"simple", "log"}, default="simple"
        Compound simple returns or sum log returns.

    Returns
    -------
    ndarray, Series, or DataFrame
        Momentum signal based only on information at or before ``t - skip``.
    """
    lookback = _validate_positive_integer(lookback, name="lookback")
    if not isinstance(skip, (int, np.integer)) or int(skip) < 0:
        raise ValueError("skip must be a non-negative integer.")
    skip = int(skip)
    if skip >= lookback:
        raise ValueError("skip must be smaller than lookback.")
    method = _validate_return_method(method)
    window = lookback - skip

    if isinstance(returns, (pd.Series, pd.DataFrame)):
        shifted = returns.astype(float).shift(skip)
        if method == "log":
            return shifted.rolling(window, min_periods=window).sum()
        return (1.0 + shifted).rolling(window, min_periods=window).apply(
            np.prod,
            raw=True,
        ) - 1.0

    array = _to_float_array(returns)
    shifted = np.full(array.shape, np.nan, dtype=float)
    if skip == 0:
        shifted[...] = array
    else:
        shifted[skip:] = array[:-skip]

    result = np.full(array.shape, np.nan, dtype=float)
    for end in range(window - 1, array.shape[0]):
        sample = shifted[end - window + 1 : end + 1]
        if sample.ndim == 1:
            if not np.all(np.isfinite(sample)):
                continue
            result[end] = np.sum(sample) if method == "log" else np.prod(1.0 + sample) - 1.0
            continue
        valid = np.all(np.isfinite(sample), axis=0)
        if method == "log":
            result[end, valid] = np.sum(sample[:, valid], axis=0)
        else:
            result[end, valid] = np.prod(1.0 + sample[:, valid], axis=0) - 1.0
    return result

drawdown

drawdown

drawdown(returns: ArrayLike, *, method: str = 'simple')

Compute drawdown from the running maximum wealth.

Parameters

returns : array-like Return series or panel. method : {"simple", "log"}, default="simple" Return convention used to build wealth.

Returns

ndarray, Series, or DataFrame Relative decline wealth / running_max - 1.

Source code in src/capacities_ml_fin/finance/features.py
def drawdown(returns: ArrayLike, *, method: str = "simple"):
    """Compute drawdown from the running maximum wealth.

    Parameters
    ----------
    returns : array-like
        Return series or panel.
    method : {"simple", "log"}, default="simple"
        Return convention used to build wealth.

    Returns
    -------
    ndarray, Series, or DataFrame
        Relative decline ``wealth / running_max - 1``.
    """
    wealth = wealth_index(returns, method=method)
    if isinstance(wealth, (pd.Series, pd.DataFrame)):
        return wealth / wealth.cummax() - 1.0
    array = np.asarray(wealth, dtype=float)
    return array / np.maximum.accumulate(array, axis=0) - 1.0

max_drawdown

max_drawdown

max_drawdown(returns: ArrayLike, *, method: str = 'simple')

Return the most negative drawdown of each return series.

Parameters

returns : array-like Return series or panel. method : {"simple", "log"}, default="simple" Return convention used to build wealth.

Returns

float or ndarray or Series Minimum drawdown for each input series.

Source code in src/capacities_ml_fin/finance/features.py
def max_drawdown(returns: ArrayLike, *, method: str = "simple"):
    """Return the most negative drawdown of each return series.

    Parameters
    ----------
    returns : array-like
        Return series or panel.
    method : {"simple", "log"}, default="simple"
        Return convention used to build wealth.

    Returns
    -------
    float or ndarray or Series
        Minimum drawdown for each input series.
    """
    values = drawdown(returns, method=method)
    if isinstance(values, pd.DataFrame):
        return values.min(axis=0)
    if isinstance(values, pd.Series):
        return float(values.min())
    array = np.asarray(values, dtype=float)
    if array.ndim == 1:
        return float(np.nanmin(array))
    return np.nanmin(array, axis=0)

dollar_volume

dollar_volume

dollar_volume(price: ArrayLike, volume: ArrayLike)

Compute traded dollar volume as price times volume.

Parameters

price, volume : array-like Aligned prices and traded share volumes.

Returns

ndarray, Series, or DataFrame Elementwise traded values.

Source code in src/capacities_ml_fin/finance/features.py
def dollar_volume(price: ArrayLike, volume: ArrayLike):
    """Compute traded dollar volume as price times volume.

    Parameters
    ----------
    price, volume : array-like
        Aligned prices and traded share volumes.

    Returns
    -------
    ndarray, Series, or DataFrame
        Elementwise traded values.
    """
    return _binary_pandas_operation(price, volume, lambda x, y: x * y)

turnover

turnover

turnover(volume: ArrayLike, shares_outstanding: ArrayLike)

Compute share turnover relative to shares outstanding.

Parameters

volume : array-like Traded share volume. shares_outstanding : array-like Strictly positive aligned shares outstanding.

Returns

ndarray, Series, or DataFrame Elementwise turnover ratios.

Source code in src/capacities_ml_fin/finance/features.py
def turnover(volume: ArrayLike, shares_outstanding: ArrayLike):
    """Compute share turnover relative to shares outstanding.

    Parameters
    ----------
    volume : array-like
        Traded share volume.
    shares_outstanding : array-like
        Strictly positive aligned shares outstanding.

    Returns
    -------
    ndarray, Series, or DataFrame
        Elementwise turnover ratios.
    """
    def operation(x, y):
        if isinstance(y, (pd.Series, pd.DataFrame)):
            if (y <= 0.0).any().any() if isinstance(y, pd.DataFrame) else (y <= 0.0).any():
                raise ValueError("shares_outstanding must be strictly positive.")
        elif np.any(np.asarray(y, dtype=float) <= 0.0):
            raise ValueError("shares_outstanding must be strictly positive.")
        return x / y

    return _binary_pandas_operation(volume, shares_outstanding, operation)

relative_bid_ask_spread

relative_bid_ask_spread

relative_bid_ask_spread(bid: ArrayLike, ask: ArrayLike)

Compute the quoted bid-ask spread relative to the midpoint.

Parameters

bid, ask : array-like Positive aligned quotes satisfying ask >= bid.

Returns

ndarray, Series, or DataFrame (ask - bid) / ((ask + bid) / 2).

Source code in src/capacities_ml_fin/finance/features.py
def relative_bid_ask_spread(bid: ArrayLike, ask: ArrayLike):
    """Compute the quoted bid-ask spread relative to the midpoint.

    Parameters
    ----------
    bid, ask : array-like
        Positive aligned quotes satisfying ``ask >= bid``.

    Returns
    -------
    ndarray, Series, or DataFrame
        ``(ask - bid) / ((ask + bid) / 2)``.
    """
    def operation(bid_values, ask_values):
        if isinstance(bid_values, (pd.Series, pd.DataFrame)):
            invalid_order = ask_values < bid_values
            invalid_price = (ask_values <= 0.0) | (bid_values <= 0.0)
            order_error = (
                invalid_order.any().any()
                if isinstance(invalid_order, pd.DataFrame)
                else invalid_order.any()
            )
            price_error = (
                invalid_price.any().any()
                if isinstance(invalid_price, pd.DataFrame)
                else invalid_price.any()
            )
            if order_error:
                raise ValueError("ask must be greater than or equal to bid.")
            if price_error:
                raise ValueError("bid and ask must be strictly positive.")
        else:
            bid_array = np.asarray(bid_values, dtype=float)
            ask_array = np.asarray(ask_values, dtype=float)
            if np.any(ask_array < bid_array):
                raise ValueError("ask must be greater than or equal to bid.")
            if np.any(ask_array <= 0.0) or np.any(bid_array <= 0.0):
                raise ValueError("bid and ask must be strictly positive.")
        midpoint = (ask_values + bid_values) / 2.0
        return (ask_values - bid_values) / midpoint

    return _binary_pandas_operation(bid, ask, operation)

amihud_illiquidity

amihud_illiquidity

amihud_illiquidity(
    returns: ArrayLike,
    traded_value: ArrayLike,
    *,
    window: int | None = None
)

Compute the Amihud absolute-return price-impact proxy.

Parameters

returns : array-like Asset returns. traded_value : array-like Strictly positive aligned dollar volumes. window : int, optional Replace point estimates with their trailing arithmetic mean.

Returns

ndarray, Series, or DataFrame abs(return) / traded_value, optionally smoothed.

Source code in src/capacities_ml_fin/finance/features.py
def amihud_illiquidity(
    returns: ArrayLike,
    traded_value: ArrayLike,
    *,
    window: int | None = None,
):
    """Compute the Amihud absolute-return price-impact proxy.

    Parameters
    ----------
    returns : array-like
        Asset returns.
    traded_value : array-like
        Strictly positive aligned dollar volumes.
    window : int, optional
        Replace point estimates with their trailing arithmetic mean.

    Returns
    -------
    ndarray, Series, or DataFrame
        ``abs(return) / traded_value``, optionally smoothed.
    """
    def operation(return_values, value_values):
        if isinstance(value_values, (pd.Series, pd.DataFrame)):
            invalid = value_values <= 0.0
            if invalid.any().any() if isinstance(invalid, pd.DataFrame) else invalid.any():
                raise ValueError("traded_value must be strictly positive.")
        elif np.any(np.asarray(value_values, dtype=float) <= 0.0):
            raise ValueError("traded_value must be strictly positive.")
        return np.abs(return_values) / value_values

    illiquidity = _binary_pandas_operation(returns, traded_value, operation)
    if window is None:
        return illiquidity

    window = _validate_positive_integer(window, name="window")
    if isinstance(illiquidity, (pd.Series, pd.DataFrame)):
        return illiquidity.rolling(window, min_periods=window).mean()

    array = _to_float_array(illiquidity)
    result = np.full(array.shape, np.nan, dtype=float)
    for end in range(window - 1, array.shape[0]):
        sample = array[end - window + 1 : end + 1]
        if sample.ndim == 1:
            if np.all(np.isfinite(sample)):
                result[end] = np.mean(sample)
            continue
        valid = np.all(np.isfinite(sample), axis=0)
        result[end, valid] = np.mean(sample[:, valid], axis=0)
    return result

Portfolio

normalize_weights

normalize_weights

normalize_weights(weights: ArrayLike)

Normalize static or time-varying portfolio weights to sum to one.

Parameters

weights : array-like Static one-dimensional weights or time-by-asset weights.

Returns

ndarray, Series, or DataFrame Weights normalized once for a vector or row-wise for a matrix.

Raises

ValueError If any normalization total is zero or non-finite.

Source code in src/capacities_ml_fin/finance/portfolio.py
def normalize_weights(weights: ArrayLike):
    """Normalize static or time-varying portfolio weights to sum to one.

    Parameters
    ----------
    weights : array-like
        Static one-dimensional weights or time-by-asset weights.

    Returns
    -------
    ndarray, Series, or DataFrame
        Weights normalized once for a vector or row-wise for a matrix.

    Raises
    ------
    ValueError
        If any normalization total is zero or non-finite.
    """
    if isinstance(weights, pd.Series):
        values = weights.astype(float)
        total = values.sum()
        if not np.isfinite(total) or np.isclose(total, 0.0):
            raise ValueError("weights must have a finite non-zero sum.")
        return values / total

    if isinstance(weights, pd.DataFrame):
        values = weights.astype(float)
        totals = values.sum(axis=1)
        if (~np.isfinite(totals)).any() or np.isclose(totals.to_numpy(), 0.0).any():
            raise ValueError("Each row of weights must have a finite non-zero sum.")
        return values.div(totals, axis=0)

    array = _to_float_array(weights)
    if array.ndim == 1:
        total = np.sum(array)
        if not np.isfinite(total) or np.isclose(total, 0.0):
            raise ValueError("weights must have a finite non-zero sum.")
        return array / total

    totals = np.sum(array, axis=1, keepdims=True)
    if np.any(~np.isfinite(totals)) or np.any(np.isclose(totals, 0.0)):
        raise ValueError("Each row of weights must have a finite non-zero sum.")
    return array / totals

equal_weights

equal_weights

equal_weights(assets: int | Sequence[str])

Construct an equally weighted portfolio.

Parameters

assets : int or sequence of str Positive asset count or unique asset names.

Returns

ndarray or Series Weights equal to 1 / n_assets; names are preserved when supplied.

Source code in src/capacities_ml_fin/finance/portfolio.py
def equal_weights(assets: int | Sequence[str]):
    """Construct an equally weighted portfolio.

    Parameters
    ----------
    assets : int or sequence of str
        Positive asset count or unique asset names.

    Returns
    -------
    ndarray or Series
        Weights equal to ``1 / n_assets``; names are preserved when supplied.
    """
    if isinstance(assets, (int, np.integer)):
        n_assets = _validate_positive_integer(int(assets), name="assets")
        return np.full(n_assets, 1.0 / n_assets)

    names = tuple(assets)
    if not names:
        raise ValueError("assets must contain at least one asset.")
    if not all(isinstance(name, str) and name for name in names):
        raise ValueError("Asset names must be non-empty strings.")
    if len(set(names)) != len(names):
        raise ValueError("Asset names must be unique.")
    return pd.Series(1.0 / len(names), index=names, name="weight")

market_cap_weights

market_cap_weights

market_cap_weights(market_caps: ArrayLike)

Construct cross-sectional weights proportional to market capitalizations.

Parameters

market_caps : array-like Non-negative static or time-varying capitalizations.

Returns

ndarray, Series, or DataFrame Capitalizations normalized across assets.

Source code in src/capacities_ml_fin/finance/portfolio.py
def market_cap_weights(market_caps: ArrayLike):
    """Construct cross-sectional weights proportional to market capitalizations.

    Parameters
    ----------
    market_caps : array-like
        Non-negative static or time-varying capitalizations.

    Returns
    -------
    ndarray, Series, or DataFrame
        Capitalizations normalized across assets.
    """
    if isinstance(market_caps, (pd.Series, pd.DataFrame)):
        values = market_caps.astype(float)
        if values.isna().any().any() if isinstance(values, pd.DataFrame) else values.isna().any():
            raise ValueError("market_caps must not contain missing values.")
        if (values < 0.0).any().any() if isinstance(values, pd.DataFrame) else (values < 0.0).any():
            raise ValueError("market_caps must be non-negative.")
        return normalize_weights(values)

    array = _to_float_array(market_caps)
    if np.any(~np.isfinite(array)):
        raise ValueError("market_caps must contain only finite values.")
    if np.any(array < 0.0):
        raise ValueError("market_caps must be non-negative.")
    return normalize_weights(array)

lag_weights

lag_weights

lag_weights(weights: ArrayLike, *, periods: int = 1)

Lag time-varying weights to prevent contemporaneous use.

Parameters

weights : DataFrame or two-dimensional array-like Time-by-asset portfolio weights. periods : int, default=1 Positive lag length.

Returns

DataFrame or ndarray Shifted weights with missing leading rows.

Source code in src/capacities_ml_fin/finance/portfolio.py
def lag_weights(weights: ArrayLike, *, periods: int = 1):
    """Lag time-varying weights to prevent contemporaneous use.

    Parameters
    ----------
    weights : DataFrame or two-dimensional array-like
        Time-by-asset portfolio weights.
    periods : int, default=1
        Positive lag length.

    Returns
    -------
    DataFrame or ndarray
        Shifted weights with missing leading rows.
    """
    periods = _validate_positive_integer(periods, name="periods")

    if isinstance(weights, pd.Series):
        raise ValueError(
            "Lagging a one-dimensional Series is ambiguous; provide time-varying "
            "weights as a DataFrame or two-dimensional array."
        )
    if isinstance(weights, pd.DataFrame):
        return weights.shift(periods)

    array = _to_float_array(weights)
    if array.ndim == 1:
        raise ValueError("Lagging requires time-varying two-dimensional weights.")
    result = np.full(array.shape, np.nan, dtype=float)
    result[periods:] = array[:-periods]
    return result

portfolio_returns

portfolio_returns

portfolio_returns(
    asset_returns: ArrayLike, weights: ArrayLike
)

Aggregate asset returns using supplied portfolio weights.

Parameters

asset_returns : DataFrame or two-dimensional array-like Time-by-asset returns. weights : array-like Static asset weights or time-varying weights matching the return shape.

Returns

ndarray or Series One portfolio return per observation.

Notes

Weights are neither normalized nor lagged implicitly. Apply :func:normalize_weights and :func:lag_weights explicitly when required. DataFrame weights are aligned by asset label.

Source code in src/capacities_ml_fin/finance/portfolio.py
def portfolio_returns(asset_returns: ArrayLike, weights: ArrayLike):
    """Aggregate asset returns using supplied portfolio weights.

    Parameters
    ----------
    asset_returns : DataFrame or two-dimensional array-like
        Time-by-asset returns.
    weights : array-like
        Static asset weights or time-varying weights matching the return shape.

    Returns
    -------
    ndarray or Series
        One portfolio return per observation.

    Notes
    -----
    Weights are neither normalized nor lagged implicitly. Apply
    :func:`normalize_weights` and :func:`lag_weights` explicitly when required.
    DataFrame weights are aligned by asset label.
    """
    if isinstance(asset_returns, pd.DataFrame):
        returns = asset_returns.astype(float)

        if isinstance(weights, pd.Series):
            if set(weights.index) != set(returns.columns):
                raise ValueError("Weight labels must match the return columns.")
            aligned = weights.reindex(returns.columns).astype(float)
            result = returns.mul(aligned, axis=1).sum(axis=1, min_count=len(returns.columns))
            result.name = "portfolio_return"
            return result

        if isinstance(weights, pd.DataFrame):
            if set(weights.columns) != set(returns.columns):
                raise ValueError("Weight columns must match the return columns.")
            aligned = weights.reindex(index=returns.index, columns=returns.columns).astype(float)
            result = (returns * aligned).sum(axis=1, min_count=len(returns.columns))
            result.name = "portfolio_return"
            return result

        weights_array = _to_float_array(weights)
        if weights_array.ndim == 1:
            if weights_array.shape[0] != returns.shape[1]:
                raise ValueError("Static weights must match the number of assets.")
            result = returns.mul(weights_array, axis=1).sum(
                axis=1,
                min_count=len(returns.columns),
            )
            result.name = "portfolio_return"
            return result
        if weights_array.shape != returns.shape:
            raise ValueError("Time-varying weights must have the same shape as returns.")
        result = pd.Series(
            np.sum(returns.to_numpy() * weights_array, axis=1),
            index=returns.index,
            name="portfolio_return",
        )
        return result

    returns_array = _to_float_array(asset_returns, ndim=(2,))
    weights_array = _to_float_array(weights)
    if weights_array.ndim == 1:
        if weights_array.shape[0] != returns_array.shape[1]:
            raise ValueError("Static weights must match the number of assets.")
        return returns_array @ weights_array
    if weights_array.shape != returns_array.shape:
        raise ValueError("Time-varying weights must have the same shape as returns.")
    return np.sum(returns_array * weights_array, axis=1)

portfolio_losses

portfolio_losses

portfolio_losses(
    asset_returns: ArrayLike, weights: ArrayLike
)

Aggregate portfolio returns and convert them to losses.

Parameters

asset_returns : DataFrame or two-dimensional array-like Time-by-asset returns. weights : array-like Static or time-varying portfolio weights.

Returns

ndarray or Series Portfolio losses under the loss = -return convention.

Source code in src/capacities_ml_fin/finance/portfolio.py
def portfolio_losses(asset_returns: ArrayLike, weights: ArrayLike):
    """Aggregate portfolio returns and convert them to losses.

    Parameters
    ----------
    asset_returns : DataFrame or two-dimensional array-like
        Time-by-asset returns.
    weights : array-like
        Static or time-varying portfolio weights.

    Returns
    -------
    ndarray or Series
        Portfolio losses under the ``loss = -return`` convention.
    """
    return to_losses(portfolio_returns(asset_returns, weights))

Point-in-time alignment

apply_publication_lag

apply_publication_lag

apply_publication_lag(
    data: DataFrame,
    *,
    period_end: str = "period_end",
    lag: int | str | Timedelta,
    available_col: str = "available_date"
) -> DataFrame

Create availability dates from reporting dates and a fixed lag.

Parameters

data : DataFrame Source observations containing reporting-period dates. period_end : str, default="period_end" Reporting-date column. lag : int, str, or Timedelta Non-negative calendar lag; integers denote days. available_col : str, default="available_date" Name of the generated availability column.

Returns

DataFrame Copy of data containing parsed dates and availability timestamps.

Notes

Exact publication timestamps are preferable when available. A fixed lag is only a conservative fallback for point-in-time analysis.

Source code in src/capacities_ml_fin/finance/alignment.py
def apply_publication_lag(
    data: pd.DataFrame,
    *,
    period_end: str = "period_end",
    lag: int | str | pd.Timedelta,
    available_col: str = "available_date",
) -> pd.DataFrame:
    """Create availability dates from reporting dates and a fixed lag.

    Parameters
    ----------
    data : DataFrame
        Source observations containing reporting-period dates.
    period_end : str, default="period_end"
        Reporting-date column.
    lag : int, str, or Timedelta
        Non-negative calendar lag; integers denote days.
    available_col : str, default="available_date"
        Name of the generated availability column.

    Returns
    -------
    DataFrame
        Copy of ``data`` containing parsed dates and availability timestamps.

    Notes
    -----
    Exact publication timestamps are preferable when available. A fixed lag is
    only a conservative fallback for point-in-time analysis.
    """
    if period_end not in data.columns:
        raise KeyError(f"Unknown period_end column: {period_end!r}.")

    if isinstance(lag, (int, np.integer)):
        if int(lag) < 0:
            raise ValueError("lag must be non-negative.")
        offset = pd.Timedelta(days=int(lag))
    else:
        offset = pd.to_timedelta(lag)
        if offset < pd.Timedelta(0):
            raise ValueError("lag must be non-negative.")

    result = data.copy()
    result[period_end] = pd.to_datetime(result[period_end], errors="raise")
    result[available_col] = result[period_end] + offset
    return result

validate_no_lookahead

validate_no_lookahead

validate_no_lookahead(
    data: DataFrame,
    *,
    model_time: str = "date",
    available_time: str = "available_date",
    raise_on_error: bool = True
) -> bool

Check that every observation was available by its model date.

Parameters

data : DataFrame Aligned modeling data. model_time : str, default="date" Timestamp at which each row is used. available_time : str, default="available_date" Timestamp at which information became observable. raise_on_error : bool, default=True Raise on the first violation instead of returning false.

Returns

bool True when every finite availability time is no later than model time.

Source code in src/capacities_ml_fin/finance/alignment.py
def validate_no_lookahead(
    data: pd.DataFrame,
    *,
    model_time: str = "date",
    available_time: str = "available_date",
    raise_on_error: bool = True,
) -> bool:
    """Check that every observation was available by its model date.

    Parameters
    ----------
    data : DataFrame
        Aligned modeling data.
    model_time : str, default="date"
        Timestamp at which each row is used.
    available_time : str, default="available_date"
        Timestamp at which information became observable.
    raise_on_error : bool, default=True
        Raise on the first violation instead of returning false.

    Returns
    -------
    bool
        True when every finite availability time is no later than model time.
    """
    for column in (model_time, available_time):
        if column not in data.columns:
            raise KeyError(f"Unknown time column: {column!r}.")

    model_dates = pd.to_datetime(data[model_time], errors="raise")
    available_dates = pd.to_datetime(data[available_time], errors="raise")
    valid_rows = model_dates.notna() & available_dates.notna()
    violations = valid_rows & (available_dates > model_dates)

    if violations.any() and raise_on_error:
        first = data.index[violations][0]
        raise ValueError(
            "Look-ahead detected: information is available after the model date "
            f"at row {first!r}."
        )
    return not bool(violations.any())

point_in_time_join

point_in_time_join

point_in_time_join(
    left: DataFrame,
    right: DataFrame,
    *,
    left_on: str = "date",
    available_on: str = "available_date",
    by: str | Sequence[str] | None = None,
    suffixes: tuple[str, str] = ("", "_right"),
    allow_exact_matches: bool = True
) -> DataFrame

Join each model row to the latest information available at that time.

Parameters

left, right : DataFrame Modeling rows and timestamped information releases. left_on : str, default="date" Model timestamp in left. available_on : str, default="available_date" Information-availability timestamp in right. by : str or sequence of str, optional Grouping keys such as ticker or entity identifier. suffixes : tuple of str, default=("", "_right") Suffixes for overlapping payload columns. allow_exact_matches : bool, default=True Whether information released exactly at model time is eligible.

Returns

DataFrame Backward as-of join in the original left-row order.

Notes

The result is validated with :func:validate_no_lookahead before return.

Source code in src/capacities_ml_fin/finance/alignment.py
def point_in_time_join(
    left: pd.DataFrame,
    right: pd.DataFrame,
    *,
    left_on: str = "date",
    available_on: str = "available_date",
    by: str | Sequence[str] | None = None,
    suffixes: tuple[str, str] = ("", "_right"),
    allow_exact_matches: bool = True,
) -> pd.DataFrame:
    """Join each model row to the latest information available at that time.

    Parameters
    ----------
    left, right : DataFrame
        Modeling rows and timestamped information releases.
    left_on : str, default="date"
        Model timestamp in ``left``.
    available_on : str, default="available_date"
        Information-availability timestamp in ``right``.
    by : str or sequence of str, optional
        Grouping keys such as ticker or entity identifier.
    suffixes : tuple of str, default=("", "_right")
        Suffixes for overlapping payload columns.
    allow_exact_matches : bool, default=True
        Whether information released exactly at model time is eligible.

    Returns
    -------
    DataFrame
        Backward as-of join in the original left-row order.

    Notes
    -----
    The result is validated with :func:`validate_no_lookahead` before return.
    """
    if left_on not in left.columns:
        raise KeyError(f"Unknown left time column: {left_on!r}.")
    if available_on not in right.columns:
        raise KeyError(f"Unknown availability column: {available_on!r}.")

    by_columns: list[str]
    if by is None:
        by_columns = []
    elif isinstance(by, str):
        by_columns = [by]
    else:
        by_columns = list(by)
        if not by_columns:
            raise ValueError("by must contain at least one grouping column.")

    for column in by_columns:
        if column not in left.columns or column not in right.columns:
            raise KeyError(f"Grouping column {column!r} must exist in both frames.")

    left_work = left.copy()
    right_work = right.copy()
    left_work[left_on] = pd.to_datetime(left_work[left_on], errors="raise")
    right_work[available_on] = pd.to_datetime(right_work[available_on], errors="raise")
    left_work["__pit_order__"] = np.arange(len(left_work))

    if not by_columns:
        joined = pd.merge_asof(
            left_work.sort_values(left_on),
            right_work.sort_values(available_on),
            left_on=left_on,
            right_on=available_on,
            direction="backward",
            allow_exact_matches=allow_exact_matches,
            suffixes=suffixes,
        )
    else:
        pieces: list[pd.DataFrame] = []
        grouper = by_columns[0] if len(by_columns) == 1 else by_columns
        right_groups = {
            key: group.copy()
            for key, group in right_work.groupby(grouper, sort=False, dropna=False)
        }

        for key, left_group in left_work.groupby(grouper, sort=False, dropna=False):
            right_group = right_groups.get(key)
            if right_group is None:
                template = right_work.iloc[:0].copy()
                right_group = template

            # Grouping columns are already known from the left frame. Remove them
            # from the right frame to avoid duplicate columns after the as-of join.
            right_payload = right_group.drop(columns=by_columns, errors="ignore")
            piece = pd.merge_asof(
                left_group.sort_values(left_on),
                right_payload.sort_values(available_on),
                left_on=left_on,
                right_on=available_on,
                direction="backward",
                allow_exact_matches=allow_exact_matches,
                suffixes=suffixes,
            )
            pieces.append(piece)

        joined = pd.concat(pieces, axis=0, ignore_index=True)

    joined = joined.sort_values("__pit_order__").drop(columns="__pit_order__")
    joined.index = left.index

    if available_on in joined.columns:
        validate_no_lookahead(
            joined,
            model_time=left_on,
            available_time=available_on,
        )
    return joined