https://github.com/cvxgrp/cvxportfolio

Portfolio optimization and back-testing.

https://github.com/cvxgrp/cvxportfolio

Science Score: 36.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
    3 of 19 committers (15.8%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (16.4%) to scientific vocabulary

Keywords

convex-optimization finance optimization optimization-algorithms optimization-methods optimizer portfolio-optimization python time-series

Keywords from Contributors

cvxpy mathematical-optimization modeling-language numerical-optimization optimization-modeling
Last synced: 5 months ago · JSON representation

Repository

Portfolio optimization and back-testing.

Basic Info
Statistics
  • Stars: 1,106
  • Watchers: 62
  • Forks: 274
  • Open Issues: 27
  • Releases: 1
Topics
convex-optimization finance optimization optimization-algorithms optimization-methods optimizer portfolio-optimization python time-series
Created about 9 years ago · Last pushed 6 months ago
Metadata Files
Readme Contributing License Authors

README.rst

.. Copyright (C) 2023-2024 Enzo Busseti
.. Copyright (C) 2016 Enzo Busseti, Stephen Boyd, Steven Diamond, BlackRock Inc.

.. This file is part of Cvxportfolio.

.. Cvxportfolio is free software: you can redistribute it and/or modify it under
.. the terms of the GNU General Public License as published by the Free Software
.. Foundation, either version 3 of the License, or (at your option) any later
.. version.

.. Cvxportfolio is distributed in the hope that it will be useful, but WITHOUT
.. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
.. FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
.. details.

.. You should have received a copy of the GNU General Public License along with
.. Cvxportfolio. If not, see .

`Cvxportfolio `__
===============================================

|CVXportfolio on PyPI| |linting: pylint| |Coverage Status|
|Documentation Status| |GPLv3| |Anaconda-Server Badge|


`Cvxportfolio `__ is an object-oriented
library for portfolio optimization and back-testing. It implements models
described in the `accompanying paper
`_.

The documentation of the library is at
`www.cvxportfolio.com `_.

.. Installation

*News:*

   Since end of 2023 we're running daily `example strategies
   `_
   using the `development (master) branch
   `_.; each day we commit
   target weights and initial holdings to the repository. All the code that
   runs them, including the `cron script
   `_,
   is in the repository.

Installation
------------

Cvxportolio is written in `Python `_ and can be
installed in any `Python environment
`_ by simple:

.. code:: bash

   pip install -U cvxportfolio

You can see how this works on our `Installation and Hello
World `_ Youtube video.
Anaconda installs 
`are also supported `_.

Cvxportfolio's main dependencies are `CVXPY `__ for
interfacing with numerical solvers and `Pandas `_
for interfacing with databases. We don't require any specific version of our
dependencies and test against all recent ones (up to a few years ago).

Advanced: install development version
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can also install the development version (pre-release) from the current
state of the `master branch of the repository
`_. It is tested daily
by the example strategies.

.. code:: bash

   pip install --upgrade --force-reinstall git+https://github.com/cvxgrp/cvxportfolio@master

.. Test

Test
----

After installing you can run our unit test suite in you local environment by

.. code:: bash

   python -m cvxportfolio.tests

We test against recent Python versions (3.8, 3.9, 3.10, 3.11, 3.12) and recent versions
of the main dependencies (from Pandas 1.4, CVXPY 1.1, ..., up to the current
versions) on all major operating systems. You can see the `automated testing code 
`_.

If you use Cvxportfolio in an environment without internet access you can run
the test suite ignoring the ``cvx.errors.DownloadError`` thrown by the few unit
tests that use the internet:

.. code:: bash

   python -m cvxportfolio.tests --ignore-download-errors


.. Simple Example

Simple example
--------------

In the following example market data is downloaded by a public source
(Yahoo finance) and the forecasts are computed iteratively, at each
point in the backtest, from past data.

.. code:: python

   import cvxportfolio as cvx

   gamma = 3       # risk aversion parameter (Chapter 4.2)
   kappa = 0.05    # covariance forecast error risk parameter (Chapter 4.3)
   objective = cvx.ReturnsForecast() - gamma * (
       cvx.FullCovariance() + kappa * cvx.RiskForecastError()
   ) - cvx.StocksTransactionCost()
   constraints = [cvx.LeverageLimit(3)]

   policy = cvx.MultiPeriodOptimization(objective, constraints, planning_horizon=2)

   simulator = cvx.StockMarketSimulator(['AAPL', 'AMZN', 'TSLA', 'GM', 'CVX', 'NKE'])

   result = simulator.backtest(policy, start_time='2020-01-01')

   # print back-test result statistics
   print(result)

   # plot back-test results
   result.plot()

At each point in the back-test, the policy object only operates on
**past data**, and thus the result you get is a realistic simulation of
what the strategy would have performed in the market. Returns are
forecasted as the historical mean returns and covariances as historical
covariances (both ignoring ``np.nan``\ ’s). The simulator by default
includes holding and transaction costs, using the models described in
the paper, and default parameters that are typical for the US stock
market.

Other examples
--------------

`Many examples 
`_
are shown in the documentation website, along with
their output and comments.

`Even more example scripts
`_ 
are available in the code repository. 

We show in the example on `user-provided
forecasters `_
how the user can define custom classes to forecast the expected returns
and covariances. These provide callbacks that are executed at each point
in time during the back-test. The system enforces causality and safety
against numerical errors. We recommend to always include the default
forecasters that we provide in any analysis you may do, since they are
very robust and well-tested.

We show in the examples on `DOW30
components `_
and `wide assets-classes
ETFs `_
how a simple sweep over hyper-parameters, taking advantage of our
sophisticated parallel backtest machinery, quickly provides results on
the best strategy to apply to any given selection of assets.

Similar projects
----------------

There are many software projects for portfolio optimization and back-testing.
Some notable ones in the Python ecosystem are `Zipline `_,
which implements a call-back model for back-testing very similar to the one
we provide, `Riskfolio-Lib `_
which implements (many!) portfolio optimization models and also follows a modular
approach like ours, `VectorBT `_, a back-testing library
well-suited for high frequency applications, `PyPortfolioOpt `_,
a simple yet powerful library for portfolio optimization that uses well-known models,
`YFinance `_, which is not a portfolio
optimization library (it only provides a data interface to Yahoo Finance), but
used to be one of our dependencies, and also `CVXPY `__ by
itself, which is used by some of the above and has an extensive 
`set of examples `_
devoted to portfolio optimization (indeed, Cvxportfolio was born out of those).

.. Contributions

Contributions
-------------

We welcome contributions and you don't need to sign a CLA.

Bug fixes, improvements in the documentations and examples,
new constraints, new cost objects, ..., are good contributions and can be done
even if you're not familiar with the low-level details on the library.

Development
-----------

To set up a development environment locally you should clone the
repository (or, `fork on
Github `_
and then clone your fork)

.. code:: bash

   git clone https://github.com/cvxgrp/cvxportfolio.git
   cd cvxportfolio

.. We develop in the ``main`` branch. So you should `check out
.. `_ that one. The default branch shown on
.. the homepage of the repository is the ``master`` branch. It hosts the last
.. release.

Then, you should have a look at our
`Makefile `_
and possibly change the ``PYTHON`` variable to match your system's
python interpreter. Once you have done that,

.. code:: bash

   make env
   make test

This will replicate our `development
environment `_ and run our
test suite.

You activate the shell environment with one of scripts in ``env/bin``
(or ``env\Scripts`` on Windows), for example if you use bash on POSIX

.. code:: bash

   source env/bin/activate

and from the environment you can run any of the scripts in the examples
(the cvxportfolio package is installed in `editable
mode `_).
Or, if you don't want to activate the environment, you can just run
scripts directly using ``env/bin/python`` (or ``env\Scripts\python`` on
Windows) like we do in the Makefile.

Additionally, to match our CI/CD pipeline, you may set the following
`git hooks `_

.. code:: bash

   echo "make lint" > .git/hooks/pre-commit
   chmod +x .git/hooks/pre-commit
   echo "make test" > .git/hooks/pre-push
   chmod +x .git/hooks/pre-push


Code style and quality
----------------------

Cvxportfolio follows the `PEP8 `_
specification for code style. This is enforced by the `Pylint
`_ automated linter, with options 
in the `Pyproject 
`_
configuration file.
Pylint is also used to enforce code quality standards, along with some of its
optional plugins.
Docstrings are written in the `Sphinx style 
`_, are also checked by 
Pylint, and are used to generate the documentation.

.. Versions

Versions and releases
---------------------

Cvxportfolio follows the `semantic versioning `_
specification. No breaking change in its public API will be introduced
until the next major version (``2.0.0``), which won't happen for some time. 
New features in the public API are introduced with minor versions 
(``1.1.0``, ``1.2.0``, ...), and only bug fixes at each revision.

The history of our releases (source distributions and wheels) is visible on our 
`PyPI page `_.

Releases are also tagged in our git repository and include a short summary
of changes in 
`their commit messages `_.


.. Citing

Citing
------------

If you use Cvxportfolio in work that leads to publication, you can cite the following:

.. code-block:: bibtex

    @misc{busseti2017cvx,
        author    = "Busseti, Enzo and Diamond, Steven and Boyd, Stephen",
        title     = "Cvxportfolio",
        month    = "January",
        year     = "2017",
        note     = "Portfolio Optimization and Back--{T}esting",
        howpublished = {\url{https://github.com/cvxgrp/cvxportfolio}},
    }

    @article{boyd2017multi,
      author  = "Boyd, Stephen and Busseti, Enzo and Diamond, Steven and Kahn, Ron and Nystrup, Peter and Speth, Jan",
      journal = "Foundations and Trends in Optimization",
      title   = "Multi--{P}eriod Trading via Convex Optimization",
      month   = "August",
      year    = "2017",
      number  = "1",
      pages   = "1--76",
      volume  = "3",
      url     = {\url{https://stanford.edu/~boyd/papers/pdf/cvx_portfolio.pdf}},
    }


The latter is also the first chapter of this PhD thesis:

.. code-block:: bibtex

    @phdthesis{busseti2018portfolio,
        author    = "Busseti, Enzo",
        title     = "Portfolio Management and Optimal Execution via Convex Optimization",
        school    = "Stanford University",
        address   = "Stanford, California, USA",
        month    = "May",
        year     = "2018",
        url     = {\url{https://stacks.stanford.edu/file/druid:wm743bj5020/thesis-augmented.pdf}},
    }


Legal
-----

Cvxportfolio is `free software `_.
It is released under the terms of the `General Public License, version 3
`_.

.. |CVXportfolio on PyPI| image:: https://img.shields.io/pypi/v/cvxportfolio.svg
   :target: https://pypi.org/project/cvxportfolio/
.. |linting: pylint| image:: https://img.shields.io/badge/linting-pylint-yellowgreen
   :target: https://github.com/pylint-dev/pylint
.. |Coverage Status| image:: https://coveralls.io/repos/github/cvxgrp/cvxportfolio/badge.svg?branch=master
   :target: https://coveralls.io/github/cvxgrp/cvxportfolio?branch=master
.. |Documentation Status| image:: https://readthedocs.org/projects/cvxportfolio/badge/?version=stable
   :target: https://cvxportfolio.readthedocs.io/en/stable/?badge=stable
.. |GPLv3| image:: https://img.shields.io/badge/License-GPLv3-blue.svg
   :target: https://www.gnu.org/licenses/gpl-3.0
.. |Anaconda-Server Badge| image:: https://anaconda.org/conda-forge/cvxportfolio/badges/version.svg
   :target: https://anaconda.org/conda-forge/cvxportfolio

Owner

  • Name: Stanford University Convex Optimization Group
  • Login: cvxgrp
  • Kind: organization
  • Location: Stanford, CA

GitHub Events

Total
  • Create event: 11
  • Release event: 1
  • Issues event: 12
  • Watch event: 111
  • Issue comment event: 21
  • Push event: 331
  • Pull request event: 17
  • Fork event: 18
Last Year
  • Create event: 11
  • Release event: 1
  • Issues event: 12
  • Watch event: 111
  • Issue comment event: 21
  • Push event: 331
  • Pull request event: 17
  • Fork event: 18

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 2,701
  • Total Committers: 19
  • Avg Commits per committer: 142.158
  • Development Distribution Score (DDS): 0.147
Past Year
  • Commits: 1,003
  • Committers: 1
  • Avg Commits per committer: 1,003.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
Enzo Busseti e****i@m****m 2,305
enzo.busseti e****i@a****e 171
Thomas Schmelzer t****r@g****m 74
Enzo Busseti e****i 44
Steven Diamond s****2@s****u 21
andrewcz a****r@g****m 20
weiyialanchen w****n@g****m 17
Enzo Busseti e****i@s****u 16
Kevin Zhu k****n@s****m 11
Thomas Schmelzer t****r@a****e 7
JPN j****g@g****m 5
Steven Diamond d****d@c****u 3
Leonardo Joau j****o@i****m 1
Leonardo Joau l****u@g****r 1
Tim Paine t****4@g****m 1
blineder b****n@b****m 1
Enzo Busseti e****o@a****l 1
jessiejessiewang j****7@g****m 1
vroomzel v****l@g****m 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 6 months ago

All Time
  • Total issues: 120
  • Total pull requests: 78
  • Average time to close issues: 12 months
  • Average time to close pull requests: 4 months
  • Total issue authors: 56
  • Total pull request authors: 16
  • Average comments per issue: 2.83
  • Average comments per pull request: 1.35
  • Merged pull requests: 59
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 8
  • Pull requests: 22
  • Average time to close issues: 27 days
  • Average time to close pull requests: 14 days
  • Issue authors: 7
  • Pull request authors: 2
  • Average comments per issue: 5.25
  • Average comments per pull request: 0.23
  • Merged pull requests: 14
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • enzbus (22)
  • kch382001 (12)
  • quant9 (10)
  • thayes75 (9)
  • pcgm-team (7)
  • tschm (4)
  • andrewcz (2)
  • taoluo (2)
  • mtomic-quant (2)
  • tyler-abbot (2)
  • optwave (2)
  • gladiator1410 (2)
  • gobbedy (2)
  • genlirady (1)
  • emanuele (1)
Pull Request Authors
  • enzbus (57)
  • wec7 (9)
  • tschm (7)
  • quant9 (5)
  • andrewcz (4)
  • leonardojoau (2)
  • vroomzel (1)
  • roprisor (1)
  • jxwng (1)
  • blineder (1)
  • walkacross (1)
  • jonathanng (1)
  • quant5 (1)
  • taoluo (1)
  • tyler-abbot (1)
Top Labels
Issue Labels
enhancement (10) question (5) bug (4) error checks (3) docs (2) examples (2) Data input (2) help wanted (1)
Pull Request Labels

Packages

  • Total packages: 3
  • Total downloads:
    • pypi 2,676 last-month
  • Total dependent packages: 0
    (may contain duplicates)
  • Total dependent repositories: 2
    (may contain duplicates)
  • Total versions: 53
  • Total maintainers: 1
proxy.golang.org: github.com/cvxgrp/cvxportfolio
  • Versions: 1
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Dependent packages count: 5.5%
Average: 5.7%
Dependent repos count: 5.8%
Last synced: 6 months ago
pypi.org: cvxportfolio

Portfolio optimization and back-testing.

  • Versions: 51
  • Dependent Packages: 0
  • Dependent Repositories: 2
  • Downloads: 2,676 Last month
Rankings
Stargazers count: 2.4%
Forks count: 3.7%
Average: 7.7%
Dependent packages count: 10.1%
Downloads: 10.8%
Dependent repos count: 11.6%
Maintainers (1)
Last synced: 6 months ago
conda-forge.org: cvxportfolio
  • Versions: 1
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Forks count: 12.3%
Stargazers count: 16.0%
Average: 28.4%
Dependent repos count: 34.0%
Dependent packages count: 51.2%
Last synced: 6 months ago

Dependencies

.github/workflows/test.yml actions
  • actions/checkout v3 composite
  • actions/setup-python v4 composite
  • coverallsapp/github-action v1 composite
pyproject.toml pypi
  • cvxpy *
  • matplotlib *
  • multiprocess *
  • numpy *
  • pandas *
  • requests *
  • scipy *