Skip to content

pyMosek

A Pythonic interface to the MOSEK optimization solver.

Release

rhiza v1.14.2 License: MIT Python versions CI Code style: ruff uv CodeFactor OpenSSF Scorecard

Installation

pyMosek requires Python 3.11 or newer. Install it from a clone with uv:

git clone https://github.com/Jebel-Quant/pyMosek.git
cd pyMosek
make install

Usage

Quick start

Describe the risk with a model from risk, pick an objective from objective, and list the constraints. Risk limits come from the risk model itself. Inputs are pandas objects labelled by ticker (plain arrays work too), and the result is labelled the same way. No cones are involved.

>>> import pandas as pd
>>> from pymosek import constraint, objective, optimize, risk
>>> assets = ["AAA", "BBB", "CCC", "DDD"]
>>> exposures = pd.DataFrame({"market": [1.2, 0.9, 1.0, 0.7], "value": [0.5, -0.3, 0.1, -0.6]}, index=assets)
>>> factor_covariance = pd.DataFrame([[0.03, 0.0], [0.0, 0.01]], index=["market", "value"], columns=["market", "value"])
>>> specific_variance = pd.Series([0.02, 0.03, 0.01, 0.02], index=assets)
>>> expected_returns = pd.Series([0.08, 0.04, 0.07, 0.03], index=assets)
>>> model = risk.FactorRiskModel(exposures, factor_covariance, specific_variance)
>>> result = optimize(
...     model,
...     objective.MaximizeReturn(expected_returns),
...     [
...         constraint.CashNeutral(),
...         constraint.MaxLeverage(2),
...         model.max_volatility(0.10),
...         model.exposure_bounds({"market": (0, 0)}),
...     ],
... )
>>> result.weights.round(2)
AAA   -0.24
BBB   -0.39
CCC    0.65
DDD   -0.03
Name: weight, dtype: float64
>>> round(result.expected_return, 4), round(result.volatility, 3), round(result.gross_leverage, 2)
(0.0104, 0.1, 1.3)
>>> bool(abs(result.factor_exposures["market"]) < 1e-6)
True
Namespace Contents
risk SampleCovariance(cov), FactorRiskModel(B, F, d). Their limits are model.max_volatility(limit) and, for factor models, model.exposure_bounds({factor: (lo, hi)}).
objective MaximizeReturn(mu), MinimizeRisk(), MeanVariance(mu, risk_aversion)
constraint LongOnly(), FullyInvested(), Budget(total), CashNeutral(), MaxLeverage(limit), PositionBounds(lower, upper), GroupLimits(groups, bounds)

optimize returns a PortfolioResult with weights, expected_return, volatility, gross_leverage, net_exposure and, for factor models, factor_exposures. If no optimal portfolio exists, it raises OptimizationError and says why (for example, infeasible constraints, or a missing risk limit). A missing or expired MOSEK license raises LicenseError, a subclass of OptimizationError, which says where MOSEK looks for mosek.lic.

examples/long_only_markowitz.py and examples/cash_neutral_factor.py rebuild the two cone-level functions below with this API. The tests check that they give the same portfolios.

Notebooks

Two interactive marimo notebooks in docs/notebooks/ cover the same examples with sliders and charts:

  • long_only_markowitz.py: mean-variance with a weight cap, plus the efficient frontier.
  • cash_neutral_factor.py: a long/short book under a factor model, with volatility and leverage limits, an optional market-neutral constraint, and a plot showing which limit binds.

Each has a PEP 723 header, so it brings its own environment. Open one with uvx marimo edit --sandbox docs/notebooks/long_only_markowitz.py, or run it as a script with uv run --script docs/notebooks/long_only_markowitz.py. They need a MOSEK license.

Cone-level examples

pymosek.long_only_markowitz(mean, covariance, risk_aversion=1.0) returns fully invested, long-only mean-variance weights. It maximises mean' w - (risk_aversion / 2) * w' covariance w subject to sum(w) = 1 and w >= 0, solved as a conic program with MOSEK Fusion.

pymosek.cash_neutral_factor_portfolio(mean, exposures, factor_covariance, specific_variance, max_volatility=0.10, max_leverage=5.0) maximises expected return mean' w for a cash-neutral portfolio (sum(w) = 0) with gross leverage sum(|w|) <= max_leverage. The risk is a hard constraint: the expected standard deviation sqrt(w' Σ w) stays at or below max_volatility. Σ comes from a factor model, Σ = B F B' + diag(d). It is never formed. With F = L L', the risk constraint is a single quadratic cone, and formulation picks one of two equivalent ways to write it:

  • "exposure" (default): factor exposures are a variable, y = B' w, and the cone is over L' y and sqrt(d) * w.
  • "direct": the cone is over L' B' w and sqrt(d) * w.

examples/compare_factor_formulations.py compares the two. With dense exposures they are equivalent. With sparse exposures (industry dummies) "exposure" keeps the problem far smaller: at n=5000, k=80 it has about 51k nonzeros against 435k, and solves in 0.10 s against 0.16 s.

MOSEK needs a license. Point MOSEKLM_LICENSE_FILE at your mosek.lic, or place the file at ~/mosek/mosek.lic. Without one, the solver tests are skipped locally. On CI they fail.

Development

Run make help to see all available targets:

 task              section         needs                  does
 book              Book            test benchmark stress  build the companion
                                   hypothesis-test        book
 book-nav          Book                                   check that every
                                                          mkdocs nav entry
                                                          resolves in the built
                                                          book
 marimo            Book            install                start the Marimo
                                                          editor
 marimo-validate   Book            install                check that every
                                                          Marimo notebook runs
 serve             Book            book                   build the book and
                                                          serve it on port 8000
 clean             Dev                                    remove build
                                                          artifacts and stale
                                                          local branches
 doctor            Dev                                    check local
                                                          prerequisites
 setup             Dev                                    run the repository's
                                                          own environment setup
                                                          hook
 failed-workflows  GitHub Helpers                         list recent failing
                                                          workflow runs
 latest-release    GitHub Helpers                         show information
                                                          about the latest
                                                          GitHub release
 view-issues       GitHub Helpers                         list open issues
 view-prs          GitHub Helpers                         list open pull
                                                          requests
 whoami            GitHub Helpers                         check github auth
                                                          status
 workflow-status   GitHub Helpers                         show recent runs for
                                                          the release workflow
 all               Python          fmt deps test          run every gate, as CI
                                   docs-coverage          does
                                   security license
                                   typecheck rhiza-test
 coverage          Python          install                measure coverage and
                                                          write
                                                          _tests/coverage.xml
 deps              Python          install                run deptry over the
                                                          contributed folders
 dist-check        Python          setup                  build the sdist and
                                                          wheel, and check
                                                          their version and
                                                          licence metadata
 docs-coverage     Python          install                check docstring
                                                          coverage with
                                                          interrogate
 install           Python          setup                  create the venv and
                                                          sync dependencies
 license           Python          install                scan for copyleft
                                                          licences
 security          Python          install                run the bandit
                                                          security scan
 test              Python          install                run all tests
 test-lowest       Python          install                run the tests against
                                                          the oldest
                                                          dependencies the
                                                          manifest allows
 typecheck         Python          install                run ty and/or mypy
                                                          (typechecker = ty |
                                                          mypy | both)
 docs-examples     Quality         install                check the fenced
                                                          examples in the docs
                                                          tree
 fmt               Quality                                run the pre-commit
                                                          hooks over all files
 complexity        Quality                                fail on a block above
                                                          the
                                                          cyclomatic-complexity
                                                          ceiling
 test-pyproject    Quality         install                run the
                                                          pyproject.toml
                                                          structure checks,
                                                          verbosely
 rhiza-test        Quality         install                run the rhiza
                                                          repository checks
 semgrep           Quality                                run the semgrep
                                                          static analysis rules
 todos             Quality                                list every TODO,
                                                          FIXME and HACK
                                                          comment
 update            Template                               sync the rhiza
                                                          template into this
                                                          repository
 benchmark         Testing extras  install                run the performance
                                                          benchmarks
 hypothesis-test   Testing extras  install                run the
                                                          property-based tests
 stress            Testing extras  install                run the stress and
                                                          load tests

License

MIT