{"id":51126922,"url":"https://github.com/PyPortfolio/PyPortfolioOpt","last_synced_at":"2026-07-13T15:00:28.169Z","repository":{"id":37444250,"uuid":"135300551","full_name":"PyPortfolio/PyPortfolioOpt","owner":"PyPortfolio","description":"Financial portfolio optimization in python, including classical efficient frontier, Black-Litterman, Hierarchical Risk Parity","archived":false,"fork":false,"pushed_at":"2026-07-07T21:18:14.000Z","size":15197,"stargazers_count":5838,"open_issues_count":105,"forks_count":1144,"subscribers_count":140,"default_branch":"main","last_synced_at":"2026-07-11T08:07:13.268Z","etag":null,"topics":["algorithmic-trading","covariance","efficient-frontier","finance","financial-analysis","investing","investment","investment-analysis","portfolio-management","portfolio-optimization","python","quantitative-finance"],"latest_commit_sha":null,"homepage":"https://pyportfolioopt.readthedocs.io/","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/PyPortfolio.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":"docs/Roadmap.rst","authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2018-05-29T13:30:30.000Z","updated_at":"2026-07-10T18:41:03.000Z","dependencies_parsed_at":"2023-01-30T22:01:10.228Z","dependency_job_id":"da1ddce7-e25b-4c27-90c1-98bd749a73a1","html_url":"https://github.com/PyPortfolio/PyPortfolioOpt","commit_stats":{"total_commits":629,"total_committers":37,"mean_commits":17.0,"dds":0.2575516693163752,"last_synced_commit":"8a1b381371b0793129a5e2ac87191945cc34b58d"},"previous_names":["pyportfolio/pyportfolioopt","robertmartin8/pyportfolioopt"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/PyPortfolio/PyPortfolioOpt","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PyPortfolio%2FPyPortfolioOpt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PyPortfolio%2FPyPortfolioOpt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PyPortfolio%2FPyPortfolioOpt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PyPortfolio%2FPyPortfolioOpt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/PyPortfolio","download_url":"https://codeload.github.com/PyPortfolio/PyPortfolioOpt/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/PyPortfolio%2FPyPortfolioOpt/sbom","scorecard":{"id":780327,"data":{"date":"2025-08-11","repo":{"name":"github.com/robertmartin8/PyPortfolioOpt","commit":"65cabcee11d91777d63628744c36869ec64a1c85"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":3.1,"checks":[{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Code-Review","score":6,"reason":"Found 7/11 approved changesets -- score normalized to 6","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Maintained","score":0,"reason":"0 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Token-Permissions","score":0,"reason":"detected GitHub workflow tokens with excessive permissions","details":["Warn: no topLevel permission defined: .github/workflows/codecov.yml:1","Warn: no topLevel permission defined: .github/workflows/main.yml:1","Info: no jobLevel write permissions found"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE.txt:0","Info: FSF or OSI recognized license: MIT License: LICENSE.txt:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'master'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"Pinned-Dependencies","score":0,"reason":"dependency not pinned by hash detected -- score normalized to 0","details":["Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codecov.yml:19: update your workflow using https://app.stepsecurity.io/secureworkflow/robertmartin8/PyPortfolioOpt/codecov.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/codecov.yml:21: update your workflow using https://app.stepsecurity.io/secureworkflow/robertmartin8/PyPortfolioOpt/codecov.yml/master?enable=pin","Warn: third-party GitHubAction not pinned by hash: .github/workflows/codecov.yml:34: update your workflow using https://app.stepsecurity.io/secureworkflow/robertmartin8/PyPortfolioOpt/codecov.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:24: update your workflow using https://app.stepsecurity.io/secureworkflow/robertmartin8/PyPortfolioOpt/main.yml/master?enable=pin","Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/main.yml:26: update your workflow using https://app.stepsecurity.io/secureworkflow/robertmartin8/PyPortfolioOpt/main.yml/master?enable=pin","Warn: containerImage not pinned by hash: docker/Dockerfile:1: pin your Docker image by updating python:3.11-slim-buster to python:3.11-slim-buster@sha256:c46b0ae5728c2247b99903098ade3176a58e274d9c7d2efeaaab3e0621a53935","Warn: pipCommand not pinned by hash: docker/Dockerfile:6-12","Warn: pipCommand not pinned by hash: docker/Dockerfile:6-12","Warn: pipCommand not pinned by hash: .github/workflows/codecov.yml:27","Warn: pipCommand not pinned by hash: .github/workflows/codecov.yml:28","Warn: pipCommand not pinned by hash: .github/workflows/codecov.yml:31","Warn: pipCommand not pinned by hash: .github/workflows/main.yml:32","Warn: pipCommand not pinned by hash: .github/workflows/main.yml:33","Warn: pipCommand not pinned by hash: .github/workflows/main.yml:34","Info:   0 out of   4 GitHub-owned GitHubAction dependencies pinned","Info:   0 out of   1 third-party GitHubAction dependencies pinned","Info:   0 out of   1 containerImage dependencies pinned","Info:   0 out of   8 pipCommand dependencies pinned"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 29 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Vulnerabilities","score":0,"reason":"22 existing vulnerabilities detected","details":["Warn: Project is vulnerable to: GHSA-vqfr-h8mv-ghfj","Warn: Project is vulnerable to: GHSA-cpwx-vrp4-4pq7","Warn: Project is vulnerable to: GHSA-gmj6-6f8f-6699","Warn: Project is vulnerable to: GHSA-q2x7-8rv6-6q7h","Warn: Project is vulnerable to: GHSA-33p9-3p43-82vq","Warn: Project is vulnerable to: GHSA-9hjg-9r4m-mvj7","Warn: Project is vulnerable to: PYSEC-2025-49 / GHSA-5rjg-fvgr-3xxf","Warn: Project is vulnerable to: GHSA-7cx3-6m66-7c5m","Warn: Project is vulnerable to: GHSA-48p4-8xcf-vxj5","Warn: Project is vulnerable to: GHSA-pq67-6m6q-mj2v","Warn: Project is vulnerable to: PYSEC-2018-34 / GHSA-2fc2-6r4j-p65h","Warn: Project is vulnerable to: PYSEC-2021-856 / GHSA-5545-2q6w-2gh6","Warn: Project is vulnerable to: PYSEC-2019-108 / GHSA-9fq2-x9r6-wfmf","Warn: Project is vulnerable to: PYSEC-2018-33 / GHSA-cw6w-4rcx-xphc","Warn: Project is vulnerable to: PYSEC-2021-857 / GHSA-f7c7-j99h-c22f","Warn: Project is vulnerable to: GHSA-fpfv-jqm9-f5jm","Warn: Project is vulnerable to: PYSEC-2017-1 / GHSA-frgw-fgh6-9g52","Warn: Project is vulnerable to: PYSEC-2020-73","Warn: Project is vulnerable to: PYSEC-2024-110 / GHSA-jw8x-6495-233v","Warn: Project is vulnerable to: GHSA-jxfp-4rvq-9h9m","Warn: Project is vulnerable to: PYSEC-2023-102","Warn: Project is vulnerable to: PYSEC-2023-114"],"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-23T04:45:08.015Z","repository_id":37444250,"created_at":"2025-08-23T04:45:08.015Z","updated_at":"2025-08-23T04:45:08.015Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35416386,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-07-13T02:00:06.543Z","response_time":119,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["algorithmic-trading","covariance","efficient-frontier","finance","financial-analysis","investing","investment","investment-analysis","portfolio-management","portfolio-optimization","python","quantitative-finance"],"created_at":"2026-06-25T08:32:25.291Z","updated_at":"2026-07-13T15:00:28.149Z","avatar_url":"https://github.com/PyPortfolio.png","language":"Jupyter Notebook","funding_links":[],"categories":["Portfolio Optimization"],"sub_categories":[],"readme":"## Welcome to PyPortfolioOpt\n\n\u003ca href=\"https://pyportfolioopt.readthedocs.io/en/latest/\"\u003e\u003cimg src=\"https://github.com/PyPortfolio/PyPortfolioOpt/blob/main/media/logo_v1.png?raw=true\" width=\"275\" align=\"right\" /\u003e\u003c/a\u003e\n\nPyPortfolioOpt is a library implementing portfolio optimization methods, including\nclassical mean-variance optimization, Black-Litterman allocation, or shrinkage and Hierarchical Risk Parity.\nPyPortfolioOpt is inspired by scikit-learn; it is **extensive** yet easily **extensible**, for casual investors, or professionals looking for an easy prototyping tool. Whether you are a fundamentals-oriented investor who has identified a\nhandful of undervalued picks, or an algorithmic trader who has a basket of\nstrategies, PyPortfolioOpt can help you combine your alpha sources in a risk-efficient way.\n\n\n\u003c!-- buttons --\u003e\n\n|  | **[Documentation](https://pyportfolioopt.readthedocs.io/en/latest/)** · **[Tutorials](https://github.com/pyportfolio/pyportfolioopt/tree/main/cookbook)** · **[Release Notes](https://github.com/PyPortfolio/PyPortfolioOpt/releases)** |\n|---|---|\n| **Open\u0026#160;Source** | [![MIT](https://img.shields.io/github/license/pyportfolio/pyportfolioopt)](https://github.com/pyportfolio/pyportfolioopt/blob/main/LICENSE) [![GC.OS Sponsored](https://img.shields.io/badge/GC.OS-Sponsored%20Project-orange.svg?style=flat\u0026colorA=0eac92\u0026colorB=2077b4)](https://gc-os-ai.github.io/) | |\n| **Community** | [![!discord](https://img.shields.io/static/v1?logo=discord\u0026label=discord\u0026message=chat\u0026color=lightgreen)](https://discord.gg/7uKdHfdcJG) [![!linkedin](https://img.shields.io/static/v1?logo=linkedin\u0026label=LinkedIn\u0026message=news\u0026color=lightblue)](https://www.linkedin.com/company/pyportfolioopt/)  |\n| **CI/CD** | [![github-actions](https://img.shields.io/github/actions/workflow/status/pyportfolio/pyportfolioopt/main.yml?logo=github)](https://github.com/pyportfolio/pyportfolioopt/actions/workflows/main.yml) [![readthedocs](https://img.shields.io/readthedocs/pyportfolioopt?logo=readthedocs)](https://pyportfolioopt.readthedocs.io/en/latest/?badge=latest) |\n| **Code** |  [![!pypi](https://img.shields.io/pypi/v/pyportfolioopt?color=orange)](https://pypi.org/project/pyportfolioopt/) [![!python-versions](https://img.shields.io/pypi/pyversions/pyportfolioopt)](https://www.python.org/) [![!black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)  |\n| **Downloads** | ![PyPI - Downloads](https://img.shields.io/pypi/dw/pyportfolioopt) ![PyPI - Downloads](https://img.shields.io/pypi/dm/pyportfolioopt) [![Downloads](https://static.pepy.tech/badge/pyportfolioopt)](https://pepy.tech/project/pyportfolioopt) |\n| **Citation** | [JOSS article](https://joss.theoj.org/papers/10.21105/joss.03066) |\n\n\n\u003c!-- content --\u003e\n\nHead over to the **[documentation on ReadTheDocs](https://pyportfolioopt.readthedocs.io/en/latest/)** to get an in-depth look at the project, or check out the [cookbook](https://github.com/pyportfolio/pyportfolioopt/tree/main/cookbook) to see some examples showing the full process from downloading data to building a portfolio.\n\n\u003ccenter\u003e\n\u003cimg src=\"https://github.com/PyPortfolio/PyPortfolioOpt/blob/main/media/conceptual_flowchart_v2.png?raw=true\" style=\"width:70%;\"/\u003e\n\u003c/center\u003e\n\n## Table of contents\n\n- [Table of contents](#table-of-contents)\n- [Getting started](#getting-started)\n  - [For development](#for-development)\n- [A quick example](#a-quick-example)\n- [An overview of classical portfolio optimization methods](#an-overview-of-classical-portfolio-optimization-methods)\n- [Features](#features)\n  - [Expected returns](#expected-returns)\n  - [Risk models (covariance)](#risk-models-covariance)\n  - [Objective functions](#objective-functions)\n  - [Adding constraints or different objectives](#adding-constraints-or-different-objectives)\n  - [Black-Litterman allocation](#black-litterman-allocation)\n  - [Other optimizers](#other-optimizers)\n- [Advantages over existing implementations](#advantages-over-existing-implementations)\n- [Project principles and design decisions](#project-principles-and-design-decisions)\n- [Testing](#testing)\n- [Citing PyPortfolioOpt](#citing-pyportfolioopt)\n- [Contributing](#contributing)\n- [Getting in touch](#getting-in-touch)\n\n## 🚀 Installation\n\n### Using pip\n\n```bash\npip install pyportfolioopt\n```\n\n### From source\n\nClone the repository, navigate to the folder, and install using pip:\n\n```bash\ngit clone https://github.com/PyPortfolio/PyPortfolioOpt.git\ncd PyPortfolioOpt\npip install .\n```\n\n## Getting started\n\nHere is an example on real life stock data,\ndemonstrating how easy it is to find the long-only portfolio\nthat maximises the Sharpe ratio (a measure of risk-adjusted returns).\n\n```python\nimport pandas as pd\nfrom pypfopt import EfficientFrontier\nfrom pypfopt import risk_models\nfrom pypfopt import expected_returns\n\n# Read in price data\ndf = pd.read_csv(\"tests/resources/stock_prices.csv\", parse_dates=True, index_col=\"date\")\n\n# Calculate expected returns and sample covariance\nmu = expected_returns.mean_historical_return(df)\nS = risk_models.sample_cov(df)\n\n# Optimize for maximal Sharpe ratio\nef = EfficientFrontier(mu, S)\nraw_weights = ef.max_sharpe()\ncleaned_weights = ef.clean_weights()\nef.save_weights_to_file(\"weights.csv\")  # saves to file\n\nfor name, value in cleaned_weights.items():\n    print(f\"{name}: {value:.4f}\")\n```\n\n```result\nGOOG: 0.0458\nAAPL: 0.0674\nFB: 0.2008\nBABA: 0.0849\nAMZN: 0.0352\nGE: 0.0000\nAMD: 0.0000\nWMT: 0.0000\nBAC: 0.0000\nGM: 0.0000\nT: 0.0000\nUAA: 0.0000\nSHLD: 0.0000\nXOM: 0.0000\nRRC: 0.0000\nBBY: 0.0159\nMA: 0.3287\nPFE: 0.2039\nJPM: 0.0000\nSBUX: 0.0173\n```\n\n```python\nexp_return, volatility, sharpe=ef.portfolio_performance(verbose=True)\n\nround(exp_return, 4), round(volatility, 4), round(sharpe, 4)\n```\n\n```result\nExpected annual return: 29.9%\nAnnual volatility: 21.8%\nSharpe Ratio: 1.38\n```\n\nThis is interesting but not useful in itself.\nHowever, PyPortfolioOpt provides a method which allows you to\nconvert the above continuous weights to an actual allocation\nthat you could buy. Just enter the most recent prices, and the desired portfolio size ($10,000 in this example):\n\n```python\nfrom pypfopt.discrete_allocation import DiscreteAllocation, get_latest_prices\n\nlatest_prices = get_latest_prices(df)\n\nda = DiscreteAllocation(cleaned_weights, latest_prices, total_portfolio_value=10000)\nallocation, leftover = da.greedy_portfolio()\nfor name, value in allocation.items():\n    print(f\"{name}: {value}\")\n\nprint(\"Funds remaining: ${:.2f}\".format(leftover))\n```\n\n```result\nMA: 19\nPFE: 57\nFB: 12\nBABA: 4\nAAPL: 4\nGOOG: 1\nSBUX: 2\nBBY: 2\nFunds remaining: $17.46\n```\n\n_Disclaimer: nothing about this project constitues investment advice,\nand the author bears no responsibiltiy for your subsequent investment decisions.\nPlease refer to the [license](https://github.com/PyPortfolio/PyPortfolioOpt/blob/main/LICENSE.txt) for more information._\n\n## An overview of classical portfolio optimization methods\n\nHarry Markowitz's 1952 paper is the undeniable classic,\nwhich turned portfolio optimization from an art into a science.\nThe key insight is that by combining assets with different expected returns and volatilities,\none can decide on a mathematically optimal allocation which minimises\nthe risk for a target return – the set of all such optimal portfolios is referred to as the **efficient frontier**.\n\n\u003ccenter\u003e\n\u003cimg src=\"https://github.com/PyPortfolio/PyPortfolioOpt/blob/main/media/efficient_frontier_white.png?raw=true\" style=\"width:60%;\"/\u003e\n\u003c/center\u003e\n\nAlthough much development has been made in the subject, more than half a century later,\nMarkowitz's core ideas are still fundamentally important and see daily use in many portfolio management firms.\nThe main drawback of mean-variance optimization is that the theoretical\ntreatment requires knowledge of the expected returns and the future risk-characteristics (covariance) of the assets. Obviously, if we knew the expected returns of a stock life would be much easier, but the whole game is that stock returns are notoriously hard to forecast. As a substitute, we can derive estimates of the expected return and covariance based on historical data – though we do lose the theoretical guarantees provided by Markowitz, the closer our estimates are to the real values, the better our portfolio will be.\n\nThus this project provides four major sets of functionality (though of course they are intimately related)\n\n- Estimates of expected returns\n- Estimates of risk (i.e covariance of asset returns)\n- Objective functions to be optimized\n- Optimizers.\n\nA key design goal of PyPortfolioOpt is **modularity** – the user should be able to swap in their\ncomponents while still making use of the framework that PyPortfolioOpt provides.\n\n## Features\n\nIn this section, we detail some of PyPortfolioOpt's available functionality. More examples are offered in the Jupyter notebooks [here](https://github.com/pyportfolio/pyportfolioopt/tree/main/cookbook). Another good resource is the [tests](https://github.com/pyportfolio/pyportfolioopt/tree/main/tests).\n\nA far more comprehensive version of this can be found on [ReadTheDocs](https://pyportfolioopt.readthedocs.io/en/latest/), as well as possible extensions for more advanced users.\n\n### Expected returns\n\n- Mean historical returns:\n  - the simplest and most common approach, which states that the expected return of each asset is equal to the mean of its historical returns.\n  - easily interpretable and very intuitive\n- Exponentially weighted mean historical returns:\n  - similar to mean historical returns, except it gives exponentially more weight to recent prices\n  - it is likely the case that an asset's most recent returns hold more weight than returns from 10 years ago when it comes to estimating future returns.\n- Capital Asset Pricing Model (CAPM):\n  - a simple model to predict returns based on the beta to the market\n  - this is used all over finance!\n\n### Risk models (covariance)\n\nThe covariance matrix encodes not just the volatility of an asset, but also how it correlated to other assets. This is important because in order to reap the benefits of diversification (and thus increase return per unit risk), the assets in the portfolio should be as uncorrelated as possible.\n\n- Sample covariance matrix:\n  - an unbiased estimate of the covariance matrix\n  - relatively easy to compute\n  - the de facto standard for many years\n  - however, it has a high estimation error, which is particularly dangerous in mean-variance optimization because the optimizer is likely to give excess weight to these erroneous estimates.\n- Semicovariance: a measure of risk that focuses on downside variation.\n- Exponential covariance: an improvement over sample covariance that gives more weight to recent data\n- Covariance shrinkage: techniques that involve combining the sample covariance matrix with a structured estimator, to reduce the effect of erroneous weights. PyPortfolioOpt provides wrappers around the efficient vectorised implementations provided by `sklearn.covariance`.\n  - manual shrinkage\n  - Ledoit Wolf shrinkage, which chooses an optimal shrinkage parameter. We offer three shrinkage targets: `constant_variance`, `single_factor`, and `constant_correlation`.\n  - Oracle Approximating Shrinkage\n- Minimum Covariance Determinant:\n  - a robust estimate of the covariance\n  - implemented in `sklearn.covariance`\n\n\u003cp align=\"center\"\u003e\n    \u003cimg width=60% src=\"https://github.com/PyPortfolio/PyPortfolioOpt/blob/main/media/corrplot_white.png?raw=true\"\u003e\n\u003c/p\u003e\n\n(This plot was generated using `plotting.plot_covariance`)\n\n### Objective functions\n\n- Maximum Sharpe ratio: this results in a _tangency portfolio_ because on a graph of returns vs risk, this portfolio corresponds to the tangent of the efficient frontier that has a y-intercept equal to the risk-free rate. This is the default option because it finds the optimal return per unit risk.\n- Minimum volatility. This may be useful if you're trying to get an idea of how low the volatility _could_ be, but in practice it makes a lot more sense to me to use the portfolio that maximises the Sharpe ratio.\n- Efficient return, a.k.a. the Markowitz portfolio, which minimises risk for a given target return – this was the main focus of Markowitz 1952\n- Efficient risk: the Sharpe-maximising portfolio for a given target risk.\n- Maximum quadratic utility. You can provide your own risk-aversion level and compute the appropriate portfolio.\n\n### Adding constraints or different objectives\n\n- Long/short: by default all of the mean-variance optimization methods in PyPortfolioOpt are long-only, but they can be initialised to allow for short positions by changing the weight bounds:\n\n```python\nef = EfficientFrontier(mu, S, weight_bounds=(-1, 1))\n```\n\n- Market neutrality: for the `efficient_risk` and `efficient_return` methods, PyPortfolioOpt provides an option to form a market-neutral portfolio (i.e weights sum to zero). This is not possible for the max Sharpe portfolio and the min volatility portfolio because in those cases because they are not invariant with respect to leverage. Market neutrality requires negative weights:\n\n```python\nef = EfficientFrontier(mu, S, weight_bounds=(-1, 1))\nfor name, value in ef.efficient_return(target_return=0.2, market_neutral=True).items():\n    print(f\"{name}: {value:.4f}\")\n```\n\n```result\nGOOG: 0.0747\nAAPL: 0.0532\nFB: 0.0664\nBABA: 0.0116\nAMZN: 0.0518\nGE: -0.0595\nAMD: -0.0679\nWMT: -0.0817\nBAC: -0.1413\nGM: -0.1402\nT: -0.1371\nUAA: 0.0003\nSHLD: -0.0706\nXOM: -0.0775\nRRC: -0.0510\nBBY: 0.0349\nMA: 0.3758\nPFE: 0.1112\nJPM: 0.0141\nSBUX: 0.0330\n```\n\n- Minimum/maximum position size: it may be the case that you want no security to form more than 10% of your portfolio. This is easy to encode:\n\n```python\nef = EfficientFrontier(mu, S, weight_bounds=(0, 0.1))\n```\n\nOne issue with mean-variance optimization is that it leads to many zero-weights. While these are\n\"optimal\" in-sample, there is a large body of research showing that this characteristic leads\nmean-variance portfolios to underperform out-of-sample. To that end, I have introduced an\nobjective function that can reduce the number of negligible weights for any of the objective functions. Essentially, it adds a penalty (parameterised by `gamma`) on small weights, with a term that looks just like L2 regularisation in machine learning. It may be necessary to try several `gamma` values to achieve the desired number of non-negligible weights. For the test portfolio of 20 securities, `gamma ~ 1` is sufficient\n\n```python\nfrom pypfopt import objective_functions\nef = EfficientFrontier(mu, S)\nef.add_objective(objective_functions.L2_reg, gamma=1)\nfor name, value in ef.max_sharpe().items():\n    print(f\"{name}: {value:.4f}\")\n```\n\n```result\nGOOG: 0.0820\nAAPL: 0.0919\nFB: 0.1074\nBABA: 0.0680\nAMZN: 0.1011\nGE: 0.0309\nAMD: 0.0000\nWMT: 0.0353\nBAC: 0.0002\nGM: 0.0000\nT: 0.0274\nUAA: 0.0183\nSHLD: 0.0000\nXOM: 0.0466\nRRC: 0.0024\nBBY: 0.0645\nMA: 0.1426\nPFE: 0.0841\nJPM: 0.0279\nSBUX: 0.0695\n```\n\n### Black-Litterman allocation\n\nPyportfolioopt supports Black-Litterman asset allocation, which allows you to combine\na prior estimate of returns (e.g the market-implied returns) with your own views to form a\nposterior estimate. This results in much better estimates of expected returns than just using\nthe mean historical return. Check out the [docs](https://pyportfolioopt.readthedocs.io/en/latest/BlackLitterman.html) for a discussion of the theory, as well as advice\non formatting inputs.\n\n```python\nfrom pypfopt import risk_models, BlackLittermanModel\n\nS = risk_models.sample_cov(df)\nviewdict = {\"AAPL\": 0.20, \"BBY\": -0.30, \"BAC\": 0, \"SBUX\": -0.2, \"T\": 0.131321}\nbl = BlackLittermanModel(S, pi=\"equal\", absolute_views=viewdict, omega=\"default\")\nrets = bl.bl_returns()\n\nef = EfficientFrontier(rets, S)\nfor name, value in ef.max_sharpe().items():\n    print(f\"{name}: {value:.4f}\")\n```\n\n```result\nGOOG: 0.0000\nAAPL: 0.1749\nFB: 0.0503\nBABA: 0.0951\nAMZN: 0.0000\nGE: 0.0000\nAMD: 0.0000\nWMT: 0.0000\nBAC: 0.0000\nGM: 0.0000\nT: 0.5235\nUAA: 0.0000\nSHLD: 0.0000\nXOM: 0.1298\nRRC: 0.0000\nBBY: 0.0000\nMA: 0.0000\nPFE: 0.0264\nJPM: 0.0000\nSBUX: 0.0000\n```\n\n### Other optimizers\n\nThe features above mostly pertain to solving mean-variance optimization problems via quadratic programming (though this is taken care of by `cvxpy`). However, we offer different optimizers as well:\n\n- Mean-semivariance optimization\n- Mean-CVaR optimization\n- Hierarchical Risk Parity, using clustering algorithms to choose uncorrelated assets\n- Markowitz's critical line algorithm (CLA)\n\nPlease refer to the [documentation](https://pyportfolioopt.readthedocs.io/en/latest/OtherOptimizers.html) for more.\n\n## Advantages over existing implementations\n\n- Includes both classical methods (Markowitz 1952 and Black-Litterman), suggested best practices\n  (e.g covariance shrinkage), along with many recent developments and novel\n  features, like L2 regularisation, shrunk covariance, hierarchical risk parity.\n- Native support for pandas dataframes: easily input your daily prices data.\n- Extensive practical tests, which use real-life data.\n- Easy to combine with your proprietary strategies and models.\n- Robust to missing data, and price-series of different lengths (e.g FB data\n  only goes back to 2012 whereas AAPL data goes back to 1980).\n\n## Project principles and design decisions\n\n- It should be easy to swap out individual components of the optimization process\n  with the user's proprietary improvements.\n- Usability is everything: it is better to be self-explanatory than consistent.\n- There is no point in portfolio optimization unless it can be practically\n  applied to real asset prices.\n- Everything that has been implemented should be tested.\n- Inline documentation is good: dedicated (separate) documentation is better.\n  The two are not mutually exclusive.\n- Formatting should never get in the way of coding: because of this,\n  I have deferred **all** formatting decisions to [Black](https://github.com/psf/black).\n\n## Testing\n\nTests are written in pytest (much more intuitive than `unittest` and the variants in my opinion), and I have tried to ensure close to 100% coverage. Run the tests by navigating to the package directory and simply running `pytest` on the command line.\n\nPyPortfolioOpt provides a test dataset of daily returns for 20 tickers:\n\n```python\n['GOOG', 'AAPL', 'FB', 'BABA', 'AMZN', 'GE', 'AMD', 'WMT', 'BAC', 'GM', 'T', 'UAA', 'SHLD', 'XOM', 'RRC', 'BBY', 'MA', 'PFE', 'JPM', 'SBUX']\n```\n\nThese tickers have been informally selected to meet several criteria:\n\n- reasonably liquid\n- different performances and volatilities\n- different amounts of data to test robustness\n\nCurrently, the tests have not explored all of the edge cases and combinations\nof objective functions and parameters. However, each method and parameter has\nbeen tested to work as intended.\n\n## Citing PyPortfolioOpt\n\nIf you use PyPortfolioOpt for published work, please cite the [JOSS paper](https://joss.theoj.org/papers/10.21105/joss.03066).\n\nCitation string:\n\n```text\nMartin, R. A., (2021). PyPortfolioOpt: portfolio optimization in Python. Journal of Open Source Software, 6(61), 3066, https://doi.org/10.21105/joss.03066\n```\n\nBibTex::\n\n```bibtex\n@article{Martin2021,\n  doi = {10.21105/joss.03066},\n  url = {https://doi.org/10.21105/joss.03066},\n  year = {2021},\n  publisher = {The Open Journal},\n  volume = {6},\n  number = {61},\n  pages = {3066},\n  author = {Robert Andrew Martin},\n  title = {PyPortfolioOpt: portfolio optimization in Python},\n  journal = {Journal of Open Source Software}\n}\n```\n\n## Contributing\n\nContributions are _most welcome_. Have a look at the [Contribution Guide](https://github.com/PyPortfolio/PyPortfolioOpt/blob/main/CONTRIBUTING.md) for more.\n\nWe'd like to thank all of the people who have contributed to PyPortfolioOpt since its release in 2018.\nSpecial shout-outs to:\n\n- Tuan Tran\n- Philipp Schiele\n- Carl Peasnell\n- Felipe Schneider\n- Dingyuan Wang\n- Pat Newell\n- Aditya Bhutra\n- Thomas Schmelzer\n- Rich Caputo\n- Franz Kiraly\n- Nicolas Knudde\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FPyPortfolio%2FPyPortfolioOpt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FPyPortfolio%2FPyPortfolioOpt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FPyPortfolio%2FPyPortfolioOpt/lists"}