Skip to main content

Portfolio optimization.

Project description

Cvxportfolio

CVXportfolio on PyPI Downloads Coverage Status

WORK IN PROGRESS. Cvxportfolio is currently under development. We will freeze the user interface by end of 2023Q2 and release the first stable version by end of 2023Q3.

cvxportfolio is a python library for portfolio optimization and simulation based on the book Multi-Period Trading via Convex Optimization (also available in print).

The documentation of the package is at cvxportfolio.readthedocs.io.

Installation

pip install -U cvxportfolio

Testing locally

We ship our unit test suite with the pip package. After installing you can test in you local environment by

python -m unittest discover cvxportfolio

Example

To get a sneak preview of cvxportfolio you may try the following code. This is available in examples/hello_world.py and runs with cvxportfolio >= 0.3.0. All objects in cvxportfolio can either be provided data (in a variety of forms, but preferably pandas series or dataframes) or infer/download it. For 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. That is, at each point in the backtest, 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. The simulator by default includes holding and transaction costs, using the models described in the book, and default parameters that are typical for the US stock market. The logic used matches what is described in Chapter 7 of the book. For example, returns are forecasted as the historical mean returns and covariances as historical covariances (both ignoring np.nan's). The logic used is detailed in the forecast module. Many optimizations are applied to make sure the system works well with real data.

import cvxportfolio as cvx
import matplotlib.pyplot as plt

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.TransactionCost()
constraints = [cvx.LeverageLimit(3)]

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

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

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

print(result)

# plot value of the portfolio in time
result.v.plot(figsize=(12, 5), label='Multi Period Optimization')
plt.ylabel('USD')
plt.title('Total value of the portfolio in time')
plt.show()

# plot weights of the (non-cash) assets for the SPO policy
result.w.iloc[:, :-1].plot()
plt.title('Weights of the portfolio in time')
plt.show()

Development

Cvxportfolio is under development and things might change (quite fast), however you are (most) welcome to read the code, play with it, and contribute. To set up a development environment locally you should

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

This will replicate our development environment. From there you can test with

make test

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

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.

Examples from the book

In branch 0.0.X you can find the original material used to generate plots and results in the book. Those are being restored, and (slowly) translated in the new framework. As you may see from those ipython notebooks a lot of the logic that was implemented there, outside of cvxportfolio proper, is being included and made automatic in newer versions of cvxportfolio.

Academic

If you use cvxportfolio in your academic work please cite our book:

@book{BBDKKNS:17,
    author       = {S. Boyd and E. Busseti and S. Diamond and R. Kahn and K. Koh and P. Nystrup and J. Speth},
    title        = {Multi-Period Trading via Convex Optimization},
    series       = {Foundations and Trends in Optimization},
    year         = {2017},
    month        = {August},
    publisher    = {Now Publishers},
    url          = {http://stanford.edu/~boyd/papers/cvx_portfolio.html},
}

License

Cvxportfolio is licensed under the Apache 2.0 permissive open source license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cvxportfolio-0.3.4.tar.gz (253.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cvxportfolio-0.3.4-py3-none-any.whl (268.4 kB view details)

Uploaded Python 3

File details

Details for the file cvxportfolio-0.3.4.tar.gz.

File metadata

  • Download URL: cvxportfolio-0.3.4.tar.gz
  • Upload date:
  • Size: 253.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.3

File hashes

Hashes for cvxportfolio-0.3.4.tar.gz
Algorithm Hash digest
SHA256 81b4f44d2febb537fbd3daf2ef22a3f8b81963139e533763a019d651fe3e63c1
MD5 4fed8e05c0abb9cd6ca85de12a4cede7
BLAKE2b-256 cc0cd58fdbe7a919d8081d55a02209f0c4e2e5e3b8f86b3b96cba9c021b7da89

See more details on using hashes here.

File details

Details for the file cvxportfolio-0.3.4-py3-none-any.whl.

File metadata

  • Download URL: cvxportfolio-0.3.4-py3-none-any.whl
  • Upload date:
  • Size: 268.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.11.3

File hashes

Hashes for cvxportfolio-0.3.4-py3-none-any.whl
Algorithm Hash digest
SHA256 8fc1c2898ac4d073c295a15d6e1a09f49327b4b69808467c38304df2263d5e81
MD5 83b0f8be649c2709656eac15751165ab
BLAKE2b-256 c87fa0c39632a3ca147ce998ebd76d3473f835348db6ff21e8d30fd6d8f02118

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page