API reference¶
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: |
required |
objective
|
Objective
|
An objective from :mod: |
required |
constraints
|
Iterable[Constraint]
|
Constraints from :mod: |
()
|
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
|
Source code in pymosek/optimizer.py
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
|
|
volatility |
float
|
Expected standard deviation under the risk model. |
gross_leverage |
float
|
|
net_exposure |
float
|
|
factor_exposures |
Series | None
|
|
Source code in pymosek/optimizer.py
pymosek.errors.OptimizationError
¶
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.
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 |
required |
factor_covariance
|
DataFrame | ArrayLike
|
Factor covariance |
required |
specific_variance
|
Series | ArrayLike
|
Idiosyncratic variances |
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
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 | |
factors
property
¶
The factor labels.
__init__(exposures, factor_covariance, specific_variance)
¶
Validate and align the three inputs.
Source code in pymosek/risk.py
covariance()
¶
The implied dense covariance B F B' + diag(d).
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
factor_exposures(weights)
¶
Net factor exposures B' w of a portfolio, labelled by factor.
variance(weights)
¶
Portfolio variance y' F y + w' diag(d) w with y = B' w.
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
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.
covariance()
abstractmethod
¶
max_volatility(limit)
¶
variance(weights)
¶
volatility(weights)
¶
Portfolio volatility (expected standard deviation) sqrt(w' Sigma w).
SampleCovariance
¶
Bases: RiskModel
Risk from a full covariance matrix (pd.DataFrame indexed by ticker, or array).
Source code in pymosek/risk.py
__init__(covariance)
¶
Validate the matrix (square, symmetric, PSD) and factor it.
Source code in pymosek/risk.py
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
MeanVariance
dataclass
¶
Bases: Objective
Maximise mu' w - (risk_aversion / 2) * variance.
Source code in pymosek/objective.py
MinimizeRisk
dataclass
¶
Bases: Objective
Minimise portfolio volatility (equivalently, variance).
Source code in pymosek/objective.py
Objective
¶
Bases: ABC
What the optimiser aims for; build one with the names in this module.
Source code in pymosek/objective.py
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
CashNeutral
dataclass
¶
Constraint
¶
Bases: ABC
A portfolio constraint; build one with the names in this module (or a risk model).
Source code in pymosek/constraint.py
FullyInvested
dataclass
¶
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
__post_init__()
¶
Validate every bound and that each bounded group exists.
Source code in pymosek/constraint.py
LongOnly
dataclass
¶
Bases: Constraint
No short positions: every weight is non-negative.
Source code in pymosek/constraint.py
MaxLeverage
dataclass
¶
Bases: Constraint
Gross leverage sum(|w|) is at most limit.
Source code in pymosek/constraint.py
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
__post_init__()
¶
Require at least one side and, for scalars, lower <= upper.
Source code in pymosek/constraint.py
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 |
required |
covariance
|
ArrayLike
|
Symmetric positive semi-definite |
required |
risk_aversion
|
float
|
Risk-aversion coefficient |
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 |
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
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 |
required |
exposures
|
ArrayLike
|
Factor exposures |
required |
factor_covariance
|
ArrayLike
|
Symmetric positive semi-definite factor covariance |
required |
specific_variance
|
ArrayLike
|
Non-negative idiosyncratic variances |
required |
max_volatility
|
float
|
Cap on the portfolio's expected standard deviation
|
0.1
|
max_leverage
|
float
|
Cap on gross leverage |
5.0
|
formulation
|
Formulation
|
|
'exposure'
|
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
The optimal weights. They sum to zero, their volatility is at most |
NDArray[float64]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the inputs have inconsistent shapes, |
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]