Skip to content

API reference

from pymosek import constraint, objective, optimize, risk

Optimiser

pymosek.optimizer.optimize(risk_model, objective, constraints=())

Find the optimal portfolio for objective under constraints.

Parameters:

Name Type Description Default
risk_model RiskModel

A model from :mod:pymosek.risk; it defines the assets.

required
objective Objective

An objective from :mod:pymosek.objective.

required
constraints Iterable[Constraint]

Constraints from :mod:pymosek.constraint, or risk limits made by risk_model (max_volatility, exposure_bounds).

()

Returns:

Type Description
PortfolioResult

The optimal portfolio and its statistics.

Raises:

Type Description
TypeError

If an argument is not a risk model, objective or constraint.

ValueError

If labelled inputs do not match the risk model's assets.

OptimizationError

If no optimal portfolio exists (e.g. infeasible constraints).

LicenseError

If MOSEK cannot check out a license (a subclass of OptimizationError).

Source code in pymosek/optimizer.py
def optimize(
    risk_model: RiskModel,
    objective: Objective,
    constraints: Iterable[Constraint] = (),
) -> PortfolioResult:
    """Find the optimal portfolio for ``objective`` under ``constraints``.

    Args:
        risk_model: A model from :mod:`pymosek.risk`; it defines the assets.
        objective: An objective from :mod:`pymosek.objective`.
        constraints: Constraints from :mod:`pymosek.constraint`, or risk limits made by
            ``risk_model`` (``max_volatility``, ``exposure_bounds``).

    Returns:
        The optimal portfolio and its statistics.

    Raises:
        TypeError: If an argument is not a risk model, objective or constraint.
        ValueError: If labelled inputs do not match the risk model's assets.
        OptimizationError: If no optimal portfolio exists (e.g. infeasible constraints).
        LicenseError: If MOSEK cannot check out a license (a subclass of
            ``OptimizationError``).

    """
    if not isinstance(risk_model, RiskModel):
        msg = f"risk_model must be a pymosek.risk model, got {type(risk_model).__name__}"
        raise TypeError(msg)
    if not isinstance(objective, Objective):
        msg = f"objective must come from pymosek.objective, got {type(objective).__name__}"
        raise TypeError(msg)
    constraints = list(constraints)
    for item in constraints:
        if not isinstance(item, Constraint):
            msg = f"constraints must come from pymosek.constraint or the risk model, got {item!r}"
            raise TypeError(msg)

    with mf.Model("pymosek") as model:
        problem = Problem(model, risk_model)
        for item in constraints:
            item._apply(problem)
        objective._apply(problem)
        _solve(model)
        if model.getPrimalSolutionStatus() != mf.SolutionStatus.Optimal:
            status = model.getProblemStatus()
            reason = _STATUS_MESSAGES.get(status, f"the solver stopped without an optimal solution ({status})")
            msg = f"No optimal portfolio: {reason}."
            raise OptimizationError(msg)
        w = np.asarray(problem.weights.level(), dtype=np.float64)

    weights = pd.Series(w, index=risk_model.assets, name="weight")
    expected_return = None
    if objective.expected_returns is not None:
        expected_return = float(align(objective.expected_returns, risk_model.assets, "expected_returns") @ w)
    return PortfolioResult(
        weights=weights,
        expected_return=expected_return,
        volatility=risk_model.volatility(w),
        gross_leverage=float(np.abs(w).sum()),
        net_exposure=float(w.sum()),
        factor_exposures=risk_model.factor_exposures(w) if isinstance(risk_model, FactorRiskModel) else None,
    )

pymosek.optimizer.PortfolioResult dataclass

An optimal portfolio and its key statistics.

Attributes:

Name Type Description
weights Series

Optimal weights, labelled by asset.

expected_return float | None

mu' w if the objective used expected returns, else None.

volatility float

Expected standard deviation under the risk model.

gross_leverage float

sum(|w|).

net_exposure float

sum(w).

factor_exposures Series | None

B' w labelled by factor, for factor risk models; else None.

Source code in pymosek/optimizer.py
@dataclass(frozen=True)
class PortfolioResult:
    """An optimal portfolio and its key statistics.

    Attributes:
        weights: Optimal weights, labelled by asset.
        expected_return: ``mu' w`` if the objective used expected returns, else ``None``.
        volatility: Expected standard deviation under the risk model.
        gross_leverage: ``sum(|w|)``.
        net_exposure: ``sum(w)``.
        factor_exposures: ``B' w`` labelled by factor, for factor risk models; else ``None``.

    """

    weights: pd.Series
    expected_return: float | None
    volatility: float
    gross_leverage: float
    net_exposure: float
    factor_exposures: pd.Series | None

pymosek.errors.OptimizationError

Bases: RuntimeError

The optimiser found no optimal portfolio (e.g. infeasible or unbounded constraints).

Source code in pymosek/errors.py
class OptimizationError(RuntimeError):
    """The optimiser found no optimal portfolio (e.g. infeasible or unbounded constraints)."""

pymosek.errors.LicenseError

Bases: OptimizationError

MOSEK could not check out a license (missing, expired or invalid mosek.lic).

A subclass of :class:OptimizationError, so except OptimizationError still catches it.

Source code in pymosek/errors.py
class LicenseError(OptimizationError):
    """MOSEK could not check out a license (missing, expired or invalid ``mosek.lic``).

    A subclass of :class:`OptimizationError`, so ``except OptimizationError`` still
    catches it.
    """

Risk models

pymosek.risk

Risk models, used as risk.SampleCovariance(cov) or risk.FactorRiskModel(B, F, d).

A risk model knows how risky a portfolio is. It also owns the risk-related limits, which it hands out as constraints for :func:pymosek.optimize:

  • model.max_volatility(0.10): expected standard deviation at most 10%;
  • factor_model.exposure_bounds({"market": (0, 0)}): factor exposure limits.

Inputs may be pandas objects labelled by ticker (and by factor name) or plain arrays, in which case assets (and factors) are labelled 0 .. n-1.

import numpy as np from pymosek import risk model = risk.SampleCovariance(np.diag([0.04, 0.09])) round(model.volatility([0.5, 0.5]), 4) 0.1803

FactorRiskModel

Bases: RiskModel

Risk from a factor model Sigma = B F B' + diag(d).

Parameters:

Name Type Description Default
exposures DataFrame | ArrayLike

Factor exposures B: a pd.DataFrame (tickers x factor names) or an n x k array.

required
factor_covariance DataFrame | ArrayLike

Factor covariance F (k x k), symmetric PSD; a pd.DataFrame labelled by factor is matched to exposures' columns.

required
specific_variance Series | ArrayLike

Idiosyncratic variances d (one per asset, >= 0); a pd.Series is matched by ticker.

required

The covariance is never formed when optimising: factor exposures y = B' w get their own variables, so B stays sparse and only the small k x k factor block enters the risk term.

Source code in pymosek/risk.py
class FactorRiskModel(RiskModel):
    """Risk from a factor model ``Sigma = B F B' + diag(d)``.

    Args:
        exposures: Factor exposures ``B``: a ``pd.DataFrame`` (tickers x factor names)
            or an ``n x k`` array.
        factor_covariance: Factor covariance ``F`` (``k x k``), symmetric PSD; a
            ``pd.DataFrame`` labelled by factor is matched to ``exposures``' columns.
        specific_variance: Idiosyncratic variances ``d`` (one per asset, >= 0); a
            ``pd.Series`` is matched by ticker.

    The covariance is never formed when optimising: factor exposures ``y = B' w`` get
    their own variables, so ``B`` stays sparse and only the small ``k x k`` factor
    block enters the risk term.

    """

    def __init__(
        self,
        exposures: pd.DataFrame | ArrayLike,
        factor_covariance: pd.DataFrame | ArrayLike,
        specific_variance: pd.Series | ArrayLike,
    ) -> None:
        """Validate and align the three inputs."""
        b = np.asarray(exposures, dtype=np.float64)
        check_exposures(b)
        n, k = b.shape
        super().__init__(_labels(exposures, n))
        self._factors = exposures.columns if isinstance(exposures, pd.DataFrame) else pd.RangeIndex(k)
        if not self._factors.is_unique:
            msg = "factor labels must be unique"
            raise ValueError(msg)

        if isinstance(factor_covariance, pd.DataFrame):
            try:
                factor_covariance = factor_covariance.loc[self._factors, self._factors]
            except KeyError as error:
                msg = f"factor_covariance labels do not match the exposures' factors: {error}"
                raise ValueError(msg) from None
        f = np.asarray(factor_covariance, dtype=np.float64)
        check_factor_covariance(f, k)

        d = align(specific_variance, self.assets, "specific_variance")
        check_specific_variance(d, n)

        self._b, self._f, self._d = b, f, d
        self._chol_t = psd_factor(f, "factor_covariance").T  # L', with F = L L'

    @property
    def factors(self) -> pd.Index:
        """The factor labels."""
        return self._factors

    def covariance(self) -> pd.DataFrame:
        """The implied dense covariance ``B F B' + diag(d)``."""
        sigma = self._b @ self._f @ self._b.T + np.diag(self._d)
        return pd.DataFrame(sigma, index=self.assets, columns=self.assets)

    def variance(self, weights: ArrayLike | pd.Series) -> float:
        """Portfolio variance ``y' F y + w' diag(d) w`` with ``y = B' w``."""
        w = self._weights(weights)
        y = self._b.T @ w
        return float(y @ self._f @ y + self._d @ w**2)

    def factor_exposures(self, weights: ArrayLike | pd.Series) -> pd.Series:
        """Net factor exposures ``B' w`` of a portfolio, labelled by factor."""
        return pd.Series(self._b.T @ self._weights(weights), index=self._factors, name="exposure")

    def exposure_bounds(self, bounds: Mapping[object, Bound]) -> Constraint:
        """Constraint: limits on factor exposures, e.g. ``{"market": (0, 0), "value": (None, 0.1)}``.

        Each value is ``(lower, upper)``; either side may be ``None`` (open).
        """
        return _ExposureBounds(self, dict(bounds))

    def _factor_exposure(self, problem: Problem) -> mf.Variable:
        """The shared ``y = B' w`` variables of ``problem``."""

        def build() -> mf.Variable:
            """Create ``y`` and the linear constraint ``y = B' w``."""
            y = problem.model.variable("factor_exposure", len(self._factors), mf.Domain.unbounded())
            problem.model.constraint(
                mf.Expr.sub(y, mf.Expr.mul(mf.Matrix.dense(self._b.T), problem.weights)),
                mf.Domain.equalsTo(0.0),
            )
            return y

        return problem.cached("factor_exposure", build)

    def _risk_vector(self, problem: Problem) -> mf.Expression:
        """``(L' y, sqrt(d) * w)`` with ``y = B' w`` and ``F = L L'``."""
        return mf.Expr.vstack(
            mf.Expr.mul(mf.Matrix.dense(self._chol_t), self._factor_exposure(problem)),
            mf.Expr.mulElm(np.sqrt(self._d), problem.weights),
        )

factors property

The factor labels.

__init__(exposures, factor_covariance, specific_variance)

Validate and align the three inputs.

Source code in pymosek/risk.py
def __init__(
    self,
    exposures: pd.DataFrame | ArrayLike,
    factor_covariance: pd.DataFrame | ArrayLike,
    specific_variance: pd.Series | ArrayLike,
) -> None:
    """Validate and align the three inputs."""
    b = np.asarray(exposures, dtype=np.float64)
    check_exposures(b)
    n, k = b.shape
    super().__init__(_labels(exposures, n))
    self._factors = exposures.columns if isinstance(exposures, pd.DataFrame) else pd.RangeIndex(k)
    if not self._factors.is_unique:
        msg = "factor labels must be unique"
        raise ValueError(msg)

    if isinstance(factor_covariance, pd.DataFrame):
        try:
            factor_covariance = factor_covariance.loc[self._factors, self._factors]
        except KeyError as error:
            msg = f"factor_covariance labels do not match the exposures' factors: {error}"
            raise ValueError(msg) from None
    f = np.asarray(factor_covariance, dtype=np.float64)
    check_factor_covariance(f, k)

    d = align(specific_variance, self.assets, "specific_variance")
    check_specific_variance(d, n)

    self._b, self._f, self._d = b, f, d
    self._chol_t = psd_factor(f, "factor_covariance").T  # L', with F = L L'

covariance()

The implied dense covariance B F B' + diag(d).

Source code in pymosek/risk.py
def covariance(self) -> pd.DataFrame:
    """The implied dense covariance ``B F B' + diag(d)``."""
    sigma = self._b @ self._f @ self._b.T + np.diag(self._d)
    return pd.DataFrame(sigma, index=self.assets, columns=self.assets)

exposure_bounds(bounds)

Constraint: limits on factor exposures, e.g. {"market": (0, 0), "value": (None, 0.1)}.

Each value is (lower, upper); either side may be None (open).

Source code in pymosek/risk.py
def exposure_bounds(self, bounds: Mapping[object, Bound]) -> Constraint:
    """Constraint: limits on factor exposures, e.g. ``{"market": (0, 0), "value": (None, 0.1)}``.

    Each value is ``(lower, upper)``; either side may be ``None`` (open).
    """
    return _ExposureBounds(self, dict(bounds))

factor_exposures(weights)

Net factor exposures B' w of a portfolio, labelled by factor.

Source code in pymosek/risk.py
def factor_exposures(self, weights: ArrayLike | pd.Series) -> pd.Series:
    """Net factor exposures ``B' w`` of a portfolio, labelled by factor."""
    return pd.Series(self._b.T @ self._weights(weights), index=self._factors, name="exposure")

variance(weights)

Portfolio variance y' F y + w' diag(d) w with y = B' w.

Source code in pymosek/risk.py
def variance(self, weights: ArrayLike | pd.Series) -> float:
    """Portfolio variance ``y' F y + w' diag(d) w`` with ``y = B' w``."""
    w = self._weights(weights)
    y = self._b.T @ w
    return float(y @ self._f @ y + self._d @ w**2)

RiskModel

Bases: ABC

Base class for risk models.

A subclass provides :meth:covariance and the private _risk_vector hook: an affine expression in the weights whose Euclidean norm is the portfolio volatility.

Source code in pymosek/risk.py
class RiskModel(ABC):
    """Base class for risk models.

    A subclass provides :meth:`covariance` and the private ``_risk_vector`` hook: an
    affine expression in the weights whose Euclidean norm is the portfolio volatility.
    """

    def __init__(self, assets: pd.Index) -> None:
        """Remember the asset labels; they must be unique."""
        if not assets.is_unique:
            msg = "asset labels must be unique"
            raise ValueError(msg)
        self._assets = assets

    @property
    def assets(self) -> pd.Index:
        """The asset labels, in the model's order."""
        return self._assets

    @property
    def n_assets(self) -> int:
        """Number of assets."""
        return len(self._assets)

    def _weights(self, weights: ArrayLike | pd.Series) -> NDArray[np.float64]:
        """Align portfolio weights onto the model's assets."""
        return align(weights, self._assets, "weights")

    @abstractmethod
    def covariance(self) -> pd.DataFrame:
        """The full asset covariance matrix (dense; for reporting and checks)."""

    def variance(self, weights: ArrayLike | pd.Series) -> float:
        """Portfolio variance ``w' Sigma w``."""
        w = self._weights(weights)
        return float(w @ self.covariance().to_numpy() @ w)

    def volatility(self, weights: ArrayLike | pd.Series) -> float:
        """Portfolio volatility (expected standard deviation) ``sqrt(w' Sigma w)``."""
        return float(np.sqrt(max(self.variance(weights), 0.0)))

    def max_volatility(self, limit: float) -> Constraint:
        """Constraint: the portfolio's volatility under this model is at most ``limit``."""
        return _MaxVolatility(self, limit)

    @abstractmethod
    def _risk_vector(self, problem: Problem) -> mf.Expression:
        """Affine expression in ``problem.weights`` whose norm is the volatility."""

assets property

The asset labels, in the model's order.

n_assets property

Number of assets.

__init__(assets)

Remember the asset labels; they must be unique.

Source code in pymosek/risk.py
def __init__(self, assets: pd.Index) -> None:
    """Remember the asset labels; they must be unique."""
    if not assets.is_unique:
        msg = "asset labels must be unique"
        raise ValueError(msg)
    self._assets = assets

covariance() abstractmethod

The full asset covariance matrix (dense; for reporting and checks).

Source code in pymosek/risk.py
@abstractmethod
def covariance(self) -> pd.DataFrame:
    """The full asset covariance matrix (dense; for reporting and checks)."""

max_volatility(limit)

Constraint: the portfolio's volatility under this model is at most limit.

Source code in pymosek/risk.py
def max_volatility(self, limit: float) -> Constraint:
    """Constraint: the portfolio's volatility under this model is at most ``limit``."""
    return _MaxVolatility(self, limit)

variance(weights)

Portfolio variance w' Sigma w.

Source code in pymosek/risk.py
def variance(self, weights: ArrayLike | pd.Series) -> float:
    """Portfolio variance ``w' Sigma w``."""
    w = self._weights(weights)
    return float(w @ self.covariance().to_numpy() @ w)

volatility(weights)

Portfolio volatility (expected standard deviation) sqrt(w' Sigma w).

Source code in pymosek/risk.py
def volatility(self, weights: ArrayLike | pd.Series) -> float:
    """Portfolio volatility (expected standard deviation) ``sqrt(w' Sigma w)``."""
    return float(np.sqrt(max(self.variance(weights), 0.0)))

SampleCovariance

Bases: RiskModel

Risk from a full covariance matrix (pd.DataFrame indexed by ticker, or array).

Source code in pymosek/risk.py
class SampleCovariance(RiskModel):
    """Risk from a full covariance matrix (``pd.DataFrame`` indexed by ticker, or array)."""

    def __init__(self, covariance: pd.DataFrame | ArrayLike) -> None:
        """Validate the matrix (square, symmetric, PSD) and factor it."""
        if isinstance(covariance, pd.DataFrame):
            if not covariance.index.equals(covariance.columns):
                msg = "covariance must have the same labels on rows and columns"
                raise ValueError(msg)
            assets = covariance.index
        sigma = np.asarray(covariance, dtype=np.float64)
        if sigma.ndim != 2 or sigma.shape[0] != sigma.shape[1] or sigma.shape[0] == 0:
            msg = f"covariance must be a non-empty square matrix, got shape {sigma.shape}"
            raise ValueError(msg)
        if not isinstance(covariance, pd.DataFrame):
            assets = pd.RangeIndex(sigma.shape[0])
        super().__init__(assets)
        self._sigma = sigma
        self._g = psd_factor(sigma)

    def covariance(self) -> pd.DataFrame:
        """The covariance matrix, labelled by asset."""
        return pd.DataFrame(self._sigma, index=self.assets, columns=self.assets)

    def _risk_vector(self, problem: Problem) -> mf.Expression:
        """``G' w`` with ``Sigma = G G'``."""
        return mf.Expr.mul(mf.Matrix.dense(self._g.T), problem.weights)

__init__(covariance)

Validate the matrix (square, symmetric, PSD) and factor it.

Source code in pymosek/risk.py
def __init__(self, covariance: pd.DataFrame | ArrayLike) -> None:
    """Validate the matrix (square, symmetric, PSD) and factor it."""
    if isinstance(covariance, pd.DataFrame):
        if not covariance.index.equals(covariance.columns):
            msg = "covariance must have the same labels on rows and columns"
            raise ValueError(msg)
        assets = covariance.index
    sigma = np.asarray(covariance, dtype=np.float64)
    if sigma.ndim != 2 or sigma.shape[0] != sigma.shape[1] or sigma.shape[0] == 0:
        msg = f"covariance must be a non-empty square matrix, got shape {sigma.shape}"
        raise ValueError(msg)
    if not isinstance(covariance, pd.DataFrame):
        assets = pd.RangeIndex(sigma.shape[0])
    super().__init__(assets)
    self._sigma = sigma
    self._g = psd_factor(sigma)

covariance()

The covariance matrix, labelled by asset.

Source code in pymosek/risk.py
def covariance(self) -> pd.DataFrame:
    """The covariance matrix, labelled by asset."""
    return pd.DataFrame(self._sigma, index=self.assets, columns=self.assets)

Objectives

pymosek.objective

Portfolio objectives, used as objective.MaximizeReturn(mu) etc.

from pymosek import objective objective.MinimizeRisk() MinimizeRisk()

MaximizeReturn dataclass

Bases: Objective

Maximise expected return mu' w.

Pair it with a risk or leverage limit (e.g. model.max_volatility(0.10)), otherwise the optimum is unbounded.

Source code in pymosek/objective.py
@dataclass(frozen=True, eq=False)
class MaximizeReturn(Objective):
    """Maximise expected return ``mu' w``.

    Pair it with a risk or leverage limit (e.g. ``model.max_volatility(0.10)``),
    otherwise the optimum is unbounded.
    """

    expected_returns: ArrayLike | pd.Series

    def _apply(self, problem: Problem) -> None:
        """Maximise ``mu' w``."""
        mu = problem.align(self.expected_returns, "expected_returns")
        problem.model.objective(mf.ObjectiveSense.Maximize, mf.Expr.dot(mu, problem.weights))

MeanVariance dataclass

Bases: Objective

Maximise mu' w - (risk_aversion / 2) * variance.

Source code in pymosek/objective.py
@dataclass(frozen=True, eq=False)
class MeanVariance(Objective):
    """Maximise ``mu' w - (risk_aversion / 2) * variance``."""

    expected_returns: ArrayLike | pd.Series
    risk_aversion: float = 1.0

    def __post_init__(self) -> None:
        """Require positive risk aversion."""
        if not self.risk_aversion > 0:
            msg = "MeanVariance: risk_aversion must be positive"
            raise ValueError(msg)

    def _apply(self, problem: Problem) -> None:
        """Maximise ``mu' w - (gamma / 2) v`` with ``v >= variance``."""
        mu = problem.align(self.expected_returns, "expected_returns")
        problem.model.objective(
            mf.ObjectiveSense.Maximize,
            mf.Expr.sub(mf.Expr.dot(mu, problem.weights), mf.Expr.mul(0.5 * self.risk_aversion, problem.variance())),
        )

__post_init__()

Require positive risk aversion.

Source code in pymosek/objective.py
def __post_init__(self) -> None:
    """Require positive risk aversion."""
    if not self.risk_aversion > 0:
        msg = "MeanVariance: risk_aversion must be positive"
        raise ValueError(msg)

MinimizeRisk dataclass

Bases: Objective

Minimise portfolio volatility (equivalently, variance).

Source code in pymosek/objective.py
@dataclass(frozen=True)
class MinimizeRisk(Objective):
    """Minimise portfolio volatility (equivalently, variance)."""

    def _apply(self, problem: Problem) -> None:
        """Minimise the volatility bound ``t``."""
        problem.model.objective(mf.ObjectiveSense.Minimize, problem.volatility())

Objective

Bases: ABC

What the optimiser aims for; build one with the names in this module.

Source code in pymosek/objective.py
class Objective(ABC):
    """What the optimiser aims for; build one with the names in this module."""

    #: Expected returns, if the objective uses them (reported back in the result).
    expected_returns: ArrayLike | pd.Series | None = None

    @abstractmethod
    def _apply(self, problem: Problem) -> None:
        """Set this objective on ``problem``."""

Constraints

pymosek.constraint

Generic portfolio constraints, used as constraint.CashNeutral() etc.

Each name is called like a function and returns a :class:Constraint to put in the list passed to :func:pymosek.optimize. Arguments are checked immediately, so a bad limit fails where it is written, not at solve time.

Risk limits are not here: they belong to the risk model (model.max_volatility(0.10), factor_model.exposure_bounds({...})).

from pymosek import constraint constraint.MaxLeverage(5) MaxLeverage(limit=5)

Budget dataclass

Bases: Constraint

Weights sum to total (1 for fully invested, 0 for cash-neutral).

Source code in pymosek/constraint.py
@dataclass(frozen=True)
class Budget(Constraint):
    """Weights sum to ``total`` (1 for fully invested, 0 for cash-neutral)."""

    total: float

    def __post_init__(self) -> None:
        """Reject a NaN total."""
        if math.isnan(self.total):
            msg = "Budget: total must not be NaN"
            raise ValueError(msg)

    def _apply(self, problem: Problem) -> None:
        """Add ``sum(w) = total``."""
        problem.model.constraint(mf.Expr.sum(problem.weights), mf.Domain.equalsTo(self.total))

__post_init__()

Reject a NaN total.

Source code in pymosek/constraint.py
def __post_init__(self) -> None:
    """Reject a NaN total."""
    if math.isnan(self.total):
        msg = "Budget: total must not be NaN"
        raise ValueError(msg)

CashNeutral dataclass

Bases: Budget

Weights sum to zero: longs are financed by shorts.

Source code in pymosek/constraint.py
@dataclass(frozen=True)
class CashNeutral(Budget):
    """Weights sum to zero: longs are financed by shorts."""

    total: float = field(default=0.0, init=False, repr=False)

Constraint

Bases: ABC

A portfolio constraint; build one with the names in this module (or a risk model).

Source code in pymosek/constraint.py
class Constraint(ABC):
    """A portfolio constraint; build one with the names in this module (or a risk model)."""

    @abstractmethod
    def _apply(self, problem: Problem) -> None:
        """Add this constraint to ``problem``."""

FullyInvested dataclass

Bases: Budget

Weights sum to one.

Source code in pymosek/constraint.py
@dataclass(frozen=True)
class FullyInvested(Budget):
    """Weights sum to one."""

    total: float = field(default=1.0, init=False, repr=False)

GroupLimits dataclass

Bases: Constraint

Limits on the summed weight of asset groups (sectors, countries, ...).

groups maps each asset to its group (a pd.Series indexed by ticker, or an array in asset order); assets may be left out. bounds maps a group to (lower, upper), either side None for open, e.g. GroupLimits(sectors, {"Tech": (None, 0.30), "Energy": (0, 0)}).

Source code in pymosek/constraint.py
@dataclass(frozen=True, eq=False)
class GroupLimits(Constraint):
    """Limits on the summed weight of asset groups (sectors, countries, ...).

    ``groups`` maps each asset to its group (a ``pd.Series`` indexed by ticker, or an
    array in asset order); assets may be left out. ``bounds`` maps a group to
    ``(lower, upper)``, either side ``None`` for open, e.g.
    ``GroupLimits(sectors, {"Tech": (None, 0.30), "Energy": (0, 0)})``.
    """

    groups: pd.Series | ArrayLike
    bounds: Mapping[object, Bound] = field(default_factory=dict)

    def __post_init__(self) -> None:
        """Validate every bound and that each bounded group exists."""
        if not self.bounds:
            msg = "GroupLimits: bounds must name at least one group"
            raise ValueError(msg)
        labels = pd.Series(self.groups) if not isinstance(self.groups, pd.Series) else self.groups
        known = set(labels.dropna().unique())
        for group, bound in self.bounds.items():
            if group not in known:
                msg = f"GroupLimits: group {group!r} has no assets"
                raise ValueError(msg)
            check_bound(f"GroupLimits[{group!r}]", bound)

    def _membership(self, problem: Problem) -> pd.Series:
        """Return each asset's group, ordered like the problem's assets (NaN if none)."""
        if isinstance(self.groups, pd.Series):
            extra = self.groups.index.difference(problem.assets)
            if len(extra):
                msg = f"GroupLimits: groups name unknown assets {list(extra)}"
                raise ValueError(msg)
            return self.groups.reindex(problem.assets)
        labels = np.asarray(self.groups, dtype=object)
        if labels.shape != (len(problem.assets),):
            msg = f"GroupLimits: groups must have one entry per asset ({len(problem.assets)})"
            raise ValueError(msg)
        return pd.Series(labels, index=problem.assets)

    def _apply(self, problem: Problem) -> None:
        """Add ``lower <= sum(w[group]) <= upper`` for every bounded group."""
        membership = self._membership(problem).to_numpy()
        for group, bound in self.bounds.items():
            members = np.flatnonzero(membership == group)
            bounded(problem, mf.Expr.sum(problem.weights.pick(members.tolist())), bound)

__post_init__()

Validate every bound and that each bounded group exists.

Source code in pymosek/constraint.py
def __post_init__(self) -> None:
    """Validate every bound and that each bounded group exists."""
    if not self.bounds:
        msg = "GroupLimits: bounds must name at least one group"
        raise ValueError(msg)
    labels = pd.Series(self.groups) if not isinstance(self.groups, pd.Series) else self.groups
    known = set(labels.dropna().unique())
    for group, bound in self.bounds.items():
        if group not in known:
            msg = f"GroupLimits: group {group!r} has no assets"
            raise ValueError(msg)
        check_bound(f"GroupLimits[{group!r}]", bound)

LongOnly dataclass

Bases: Constraint

No short positions: every weight is non-negative.

Source code in pymosek/constraint.py
@dataclass(frozen=True)
class LongOnly(Constraint):
    """No short positions: every weight is non-negative."""

    def _apply(self, problem: Problem) -> None:
        """Add ``w >= 0``."""
        problem.model.constraint(problem.weights, mf.Domain.greaterThan(0.0))

MaxLeverage dataclass

Bases: Constraint

Gross leverage sum(|w|) is at most limit.

Source code in pymosek/constraint.py
@dataclass(frozen=True)
class MaxLeverage(Constraint):
    """Gross leverage ``sum(|w|)`` is at most ``limit``."""

    limit: float

    def __post_init__(self) -> None:
        """Require a positive limit."""
        if not self.limit > 0:
            msg = "MaxLeverage: limit must be positive"
            raise ValueError(msg)

    def _apply(self, problem: Problem) -> None:
        """Add ``sum(z) <= limit`` with ``z >= |w|``."""
        problem.model.constraint(mf.Expr.sum(problem.gross()), mf.Domain.lessThan(self.limit))

__post_init__()

Require a positive limit.

Source code in pymosek/constraint.py
def __post_init__(self) -> None:
    """Require a positive limit."""
    if not self.limit > 0:
        msg = "MaxLeverage: limit must be positive"
        raise ValueError(msg)

PositionBounds dataclass

Bases: Constraint

Per-asset weight limits, e.g. PositionBounds(upper=0.05) or (-0.02, 0.02).

Each bound is a scalar for all assets, or a per-asset pd.Series (matched by ticker) or array; None leaves that side open.

Source code in pymosek/constraint.py
@dataclass(frozen=True, eq=False)
class PositionBounds(Constraint):
    """Per-asset weight limits, e.g. ``PositionBounds(upper=0.05)`` or ``(-0.02, 0.02)``.

    Each bound is a scalar for all assets, or a per-asset ``pd.Series`` (matched by
    ticker) or array; ``None`` leaves that side open.
    """

    lower: float | ArrayLike | pd.Series | None = None
    upper: float | ArrayLike | pd.Series | None = None

    def __post_init__(self) -> None:
        """Require at least one side and, for scalars, ``lower <= upper``."""
        if self.lower is None and self.upper is None:
            msg = "PositionBounds: give lower, upper, or both"
            raise ValueError(msg)
        if _is_real(self.lower) and _is_real(self.upper):
            check_bound("PositionBounds", (float(self.lower), float(self.upper)))

    def _side(self, problem: Problem, value: float | ArrayLike | pd.Series | None, name: str) -> np.ndarray:
        """Expand a scalar to all assets or align a per-asset bound; ``None`` is unbounded."""
        if value is None:
            return np.full(len(problem.assets), np.inf if name == "upper" else -np.inf)
        if _is_real(value):
            return np.full(len(problem.assets), float(value))
        return problem.align(value, f"PositionBounds.{name}")

    def _apply(self, problem: Problem) -> None:
        """Add ``lower <= w <= upper`` elementwise, skipping an open side."""
        lower = self._side(problem, self.lower, "lower")
        upper = self._side(problem, self.upper, "upper")
        if np.any(lower > upper):
            msg = "PositionBounds: a lower bound exceeds its upper bound"
            raise ValueError(msg)
        for given, domain in ((self.lower, mf.Domain.greaterThan(lower)), (self.upper, mf.Domain.lessThan(upper))):
            if given is not None:
                problem.model.constraint(problem.weights, domain)

__post_init__()

Require at least one side and, for scalars, lower <= upper.

Source code in pymosek/constraint.py
def __post_init__(self) -> None:
    """Require at least one side and, for scalars, ``lower <= upper``."""
    if self.lower is None and self.upper is None:
        msg = "PositionBounds: give lower, upper, or both"
        raise ValueError(msg)
    if _is_real(self.lower) and _is_real(self.upper):
        check_bound("PositionBounds", (float(self.lower), float(self.upper)))

Cone-level functions

pymosek.portfolio.long_only_markowitz(mean, covariance, risk_aversion=1.0)

Compute fully invested long-only mean-variance weights.

Parameters:

Name Type Description Default
mean ArrayLike

Expected returns, one per asset (length n).

required
covariance ArrayLike

Symmetric positive semi-definite n x n covariance matrix.

required
risk_aversion float

Risk-aversion coefficient gamma > 0; larger values tilt the portfolio towards lower variance.

1.0

Returns:

Type Description
NDArray[float64]

The optimal weights: non-negative and summing to one.

Raises:

Type Description
ValueError

If the inputs have inconsistent shapes, the covariance matrix is not symmetric positive semi-definite, or risk_aversion is not positive.

SolutionError

If MOSEK does not return an optimal solution.

Examples:

With equal expected returns only risk matters, so the weights are the minimum-variance ones, proportional to 1 / variance:

>>> import numpy as np
>>> from pymosek import long_only_markowitz
>>> w = long_only_markowitz([0.05, 0.05], np.diag([0.04, 0.01]))
>>> w.round(2).tolist()
[0.2, 0.8]
Source code in pymosek/portfolio.py
def long_only_markowitz(
    mean: ArrayLike,
    covariance: ArrayLike,
    risk_aversion: float = 1.0,
) -> NDArray[np.float64]:
    """Compute fully invested long-only mean-variance weights.

    Args:
        mean: Expected returns, one per asset (length ``n``).
        covariance: Symmetric positive semi-definite ``n x n`` covariance matrix.
        risk_aversion: Risk-aversion coefficient ``gamma > 0``; larger values tilt the
            portfolio towards lower variance.

    Returns:
        The optimal weights: non-negative and summing to one.

    Raises:
        ValueError: If the inputs have inconsistent shapes, the covariance matrix is
            not symmetric positive semi-definite, or ``risk_aversion`` is not positive.
        mosek.fusion.SolutionError: If MOSEK does not return an optimal solution.

    Examples:
        With equal expected returns only risk matters, so the weights are the
        minimum-variance ones, proportional to ``1 / variance``:

        >>> import numpy as np
        >>> from pymosek import long_only_markowitz
        >>> w = long_only_markowitz([0.05, 0.05], np.diag([0.04, 0.01]))
        >>> w.round(2).tolist()
        [0.2, 0.8]

    """
    mu = np.asarray(mean, dtype=np.float64)
    sigma = np.asarray(covariance, dtype=np.float64)

    if mu.ndim != 1 or mu.size == 0:
        msg = "mean must be a non-empty 1-D array"
        raise ValueError(msg)
    n = mu.size
    if sigma.shape != (n, n):
        msg = f"covariance must have shape ({n}, {n}), got {sigma.shape}"
        raise ValueError(msg)
    if not risk_aversion > 0:
        msg = "risk_aversion must be positive"
        raise ValueError(msg)

    g = psd_factor(sigma)

    with mf.Model("long_only_markowitz") as model:
        weights = model.variable("w", n, mf.Domain.greaterThan(0.0))
        variance = model.variable("variance", 1, mf.Domain.greaterThan(0.0))

        model.constraint("budget", mf.Expr.sum(weights), mf.Domain.equalsTo(1.0))
        # (variance, 1/2, G' w) in Qr  <=>  variance >= ||G' w||^2 = w' Sigma w
        model.constraint(
            "risk",
            mf.Expr.vstack(variance, 0.5, mf.Expr.mul(mf.Matrix.dense(g.T), weights)),
            mf.Domain.inRotatedQCone(),
        )
        model.objective(
            "utility",
            mf.ObjectiveSense.Maximize,
            mf.Expr.sub(mf.Expr.dot(mu, weights), mf.Expr.mul(0.5 * risk_aversion, variance)),
        )

        model.acceptedSolutionStatus(mf.AccSolutionStatus.Optimal)
        model.solve()
        return np.asarray(weights.level(), dtype=np.float64)

pymosek.factor.cash_neutral_factor_portfolio(mean, exposures, factor_covariance, specific_variance, max_volatility=0.1, max_leverage=5.0, formulation='exposure')

Maximise expected return, cash-neutral, under a volatility and a leverage cap.

Parameters:

Name Type Description Default
mean ArrayLike

Expected returns, one per asset (length n).

required
exposures ArrayLike

Factor exposures B, shape (n, k).

required
factor_covariance ArrayLike

Symmetric positive semi-definite factor covariance F, shape (k, k).

required
specific_variance ArrayLike

Non-negative idiosyncratic variances d (length n).

required
max_volatility float

Cap on the portfolio's expected standard deviation sqrt(w' Sigma w), in the units of mean; must be positive.

0.1
max_leverage float

Cap on gross leverage sum(|w|); must be positive.

5.0
formulation Formulation

"exposure" (y = B' w as a linear constraint, the default) or "direct" (L' B' w inside the cone). Both give the same optimum; see the module docstring.

'exposure'

Returns:

Type Description
NDArray[float64]

The optimal weights. They sum to zero, their volatility is at most

NDArray[float64]

max_volatility, and their absolute values sum to at most max_leverage.

Raises:

Type Description
ValueError

If the inputs have inconsistent shapes, factor_covariance is not symmetric positive semi-definite, specific_variance has negative entries, max_volatility/max_leverage are not positive, or formulation is unknown.

SolutionError

If MOSEK does not return an optimal solution.

Examples:

Two assets with no factor risk: go long the one with positive expected return and short the other, until the 10% volatility cap binds at |w| = 0.10 / sqrt(2 * 0.01):

>>> from pymosek import cash_neutral_factor_portfolio
>>> w = cash_neutral_factor_portfolio([0.1, -0.1], [[0.0], [0.0]], [[0.01]], [0.01, 0.01])
>>> w.round(2).tolist()
[0.71, -0.71]
Source code in pymosek/factor.py
def cash_neutral_factor_portfolio(
    mean: ArrayLike,
    exposures: ArrayLike,
    factor_covariance: ArrayLike,
    specific_variance: ArrayLike,
    max_volatility: float = 0.10,
    max_leverage: float = 5.0,
    formulation: Formulation = "exposure",
) -> NDArray[np.float64]:
    """Maximise expected return, cash-neutral, under a volatility and a leverage cap.

    Args:
        mean: Expected returns, one per asset (length ``n``).
        exposures: Factor exposures ``B``, shape ``(n, k)``.
        factor_covariance: Symmetric positive semi-definite factor covariance ``F``,
            shape ``(k, k)``.
        specific_variance: Non-negative idiosyncratic variances ``d`` (length ``n``).
        max_volatility: Cap on the portfolio's expected standard deviation
            ``sqrt(w' Sigma w)``, in the units of ``mean``; must be positive.
        max_leverage: Cap on gross leverage ``sum(|w|)``; must be positive.
        formulation: ``"exposure"`` (``y = B' w`` as a linear constraint, the
            default) or ``"direct"`` (``L' B' w`` inside the cone). Both give the same
            optimum; see the module docstring.

    Returns:
        The optimal weights. They sum to zero, their volatility is at most
        ``max_volatility``, and their absolute values sum to at most ``max_leverage``.

    Raises:
        ValueError: If the inputs have inconsistent shapes, ``factor_covariance`` is
            not symmetric positive semi-definite, ``specific_variance`` has negative
            entries, ``max_volatility``/``max_leverage`` are not positive, or
            ``formulation`` is unknown.
        mosek.fusion.SolutionError: If MOSEK does not return an optimal solution.

    Examples:
        Two assets with no factor risk: go long the one with positive expected return
        and short the other, until the 10% volatility cap binds at
        ``|w| = 0.10 / sqrt(2 * 0.01)``:

        >>> from pymosek import cash_neutral_factor_portfolio
        >>> w = cash_neutral_factor_portfolio([0.1, -0.1], [[0.0], [0.0]], [[0.01]], [0.01, 0.01])
        >>> w.round(2).tolist()
        [0.71, -0.71]

    """
    model, weights = build_model(
        mean, exposures, factor_covariance, specific_variance, max_volatility, max_leverage, formulation
    )
    with model:
        model.solve()
        return np.asarray(weights.level(), dtype=np.float64)