{"id":51126924,"url":"https://github.com/johnsoong216/pymarkowitz","last_synced_at":"2026-07-13T15:00:28.700Z","repository":{"id":62581586,"uuid":"243413043","full_name":"johnsoong216/pymarkowitz","owner":"johnsoong216","description":"Mean Variance (Markowitz) Portfolio Optimization and Beyond","archived":false,"fork":false,"pushed_at":"2024-04-25T14:21:42.000Z","size":21990,"stargazers_count":58,"open_issues_count":4,"forks_count":16,"subscribers_count":4,"default_branch":"master","last_synced_at":"2024-08-10T21:28:38.522Z","etag":null,"topics":["backtesting","finance","markowitz-portfolio","mean-variance-optimization","portfolio-construction","portfolio-management","portfolio-optimization","python","risk-measurement"],"latest_commit_sha":null,"homepage":"","language":"Python","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/johnsoong216.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-02-27T02:31:14.000Z","updated_at":"2024-08-10T11:12:12.000Z","dependencies_parsed_at":"2022-11-03T22:01:17.555Z","dependency_job_id":null,"html_url":"https://github.com/johnsoong216/pymarkowitz","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/johnsoong216/pymarkowitz","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnsoong216%2Fpymarkowitz","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnsoong216%2Fpymarkowitz/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnsoong216%2Fpymarkowitz/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnsoong216%2Fpymarkowitz/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/johnsoong216","download_url":"https://codeload.github.com/johnsoong216/pymarkowitz/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/johnsoong216%2Fpymarkowitz/sbom","scorecard":{"id":529029,"data":{"date":"2025-08-11","repo":{"name":"github.com/johnsoong216/pymarkowitz","commit":"5d389d8ae084b58aac31e2093e6e3f58940fb0e6"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":3,"checks":[{"name":"Dangerous-Workflow","score":-1,"reason":"no workflows found","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":"Maintained","score":0,"reason":"0 commit(s) and 0 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":"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":"Code-Review","score":0,"reason":"Found 0/18 approved changesets -- score normalized to 0","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":"Token-Permissions","score":-1,"reason":"No tokens found","details":null,"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":"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":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}},{"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:0","Info: FSF or OSI recognized license: MIT License: LICENSE: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":-1,"reason":"no dependencies found","details":null,"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 15 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"}}]},"last_synced_at":"2025-08-20T05:16:09.628Z","repository_id":62581586,"created_at":"2025-08-20T05:16:09.628Z","updated_at":"2025-08-20T05:16:09.628Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35426086,"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":["backtesting","finance","markowitz-portfolio","mean-variance-optimization","portfolio-construction","portfolio-management","portfolio-optimization","python","risk-measurement"],"created_at":"2026-06-25T08:32:25.291Z","updated_at":"2026-07-13T15:00:28.694Z","avatar_url":"https://github.com/johnsoong216.png","language":"Python","funding_links":[],"categories":["Portfolio Optimization"],"sub_categories":[],"readme":"\n# Pymarkowitz\n\n\u003cp align=\"left\"\u003e\n    \u003ca href=\"https://www.python.org/\"\u003e\n        \u003cimg src=\"https://ForTheBadge.com/images/badges/made-with-python.svg\"\n            alt=\"python\"\u003e\u003c/a\u003e \u0026nbsp;\n    \u003ca href=\"https://opensource.org/licenses/MIT\"\u003e\n        \u003cimg src=\"https://img.shields.io/badge/License-MIT-brightgreen.svg?style=flat-square\"\n            alt=\"MIT license\"\u003e\u003c/a\u003e \u0026nbsp;\n\u003c/p\u003e\n\n**Pymarkowitz** is an open source library for implementing portfolio optimisation. This library extends beyond the classical mean-variance optimization and takes into account a variety of risk and reward metrics, as well as the skew/kurtosis of assets.\n\n**Pymarkowitz** can aid your decision-making in portfolio allocation in a risk-efficient manner. Pymarkowitz covers major objectives and constraints related with major types of risk and reward metrics, as well as simulation to examine the relationship between all these metrics. The flexibility in its implementation gives you the maximum discretion to customize and suit it to your own needs. \n\n\n*Disclaimer: This library is for educational and entertainment purpose only. Please invest with due diligence at your own risk.\n\nHead over to the directory **demos** to get an in-depth look at the project and its functionalities, or continue below to check out some brief examples.\n\n---\n\n## Table of Contents\n\n\n- [Installation](#installation)\n- [Features](#features)\n- [Reference](#reference)\n- [License](#license)\n\n---\n\n## Installation\n\n### Setup\n\n\u003e install directly using pip\n\n```shell\n$ pip install pymarkowitz\n```\n\n\u003e install from github\n\n```shell\n$ pip install git+https://github.com/johnsoong216/pymarkowitz.git\n```\n\n### Development\n\n\u003e For development purposes you can clone or fork the repo and hack right away!\n\n```shell\n$ git clone https://github.com/johnsoong216/pymarkowitz.git\n```\n---\n\n## Features\n- [Preprocessing](##preprocessing)\n- [Optimization](##optimization)\n- [Simulation](##simulation)\n- [Backtesting](##backtesting)\n\n\n---\n### Preprocessing\n\n\u003e First step is to import all availble modules\n\n```python\nimport numpy as np\nimport pandas as pd\nfrom pymarkowitz import *\n\n```\n\u003e Read data with pandas. The dataset is available in the **datasets** directory. I will select 15 random stocks with 1000 observations\n\n```python\n\nsp500 = pd.read_csv(\"datasets/sp500_1990_2000.csv\", index_col='DATE').drop([\"Unnamed: 0\"], axis=1)\nselected = sp500.iloc[:1000, np.random.choice(np.arange(0, sp500.shape[1]), 15, replace=False)]\n\n```\n\u003e Use a ReturnGenerator to compute historical mean return and daily return. Note that there are a variety of options to compute rolling/continuous/discrete returns. Please refer to the **Return.ipynb** jupyter notebook in **demo** directory\n\n```python\n\nret_generator = ReturnGenerator(selected)\nmu_return = ret_generator.calc_mean_return(method='geometric')\ndaily_return = ret_generator.calc_return(method='daily')\n\n```\n\u003e Use a MomentGenerator to compute covariance/coskewness/cokurtosis matrix and beta. Note that there are a variety of options to compute the comoment matrix and asset beta, such as with semivariance, exponential and customized weighting. Normalizing matrices are also supported. Please refer to the **Moment(Covariance).ipynb** jupyter notebook in **demo** directory\n\n```python\n\nbenchmark = sp500.iloc[:1000].pct_change().dropna(how='any').sum(axis=1)/sp500.shape[1]\ncov_matrix = mom_generator.calc_cov_mat()\nbeta_vec = mom_generator.calc_beta(benchmark)\n\n```\n\n\u003e Construct higher moment matrices by calling\n\n```python\n\n\ncoskew_matrix = mom_generator.calc_coskew_mat()\ncokurt_matrix = mom_generator.calc_cokurt_mat()\ncoseventh_matrix = mom_generator.calc_comoment_mat(7)\n\n```\n\n\u003e Construct an Optimizer\n\n```python\n\nPortOpt = Optimizer(mu_return, cov_matrix, beta_vec)\n\n```\n\n### Optimization\n\n\u003e Please refer to the **Optimization.ipynb** jupyter notebook in **demo** directory for more detailed explanations.\n\n\n\u003e Set your Objective. \n\n```python\n\n### Call PortOpt.objective_options() to look at all available objectives\n\nPortOpt.add_objective(\"min_volatility\")\n\n```\n\n\u003e Set your Constraints. \n\n```python\n\n### Call PortOpt.constraint_options() to look at all available constraints.\n\nPortOpt.add_constraint(\"weight\", weight_bound=(-1,1), leverage=1) # Portfolio Long/Short\nPortOpt.add_constraint(\"concentration\", top_holdings=2, top_concentration=0.5) # Portfolio Concentration\n\n```\n\n\u003e Solve and Check Summary\n\n\n```python\nPortOpt.solve()\nweight_dict, metric_dict = PortOpt.summary(risk_free=0.015, market_return=0.07, top_holdings=2)\n\n\n# Metric Dict Sample Output\n{'Expected Return': 0.085,\n 'Leverage': 1.0001,\n 'Number of Holdings': 5,\n 'Top 2 Holdings Concentrations': 0.5779,\n 'Volatility': 0.1253,\n 'Portfolio Beta': 0.7574,\n 'Sharpe Ratio': 0.5586,\n 'Treynor Ratio': 0.0924,\n \"Jenson's Alpha\": 0.0283}\n \n# Weight Dict Sample Output\n{'GIS': 0.309, 'CINF': 0.0505, 'USB': 0.104, 'HES': 0.2676, 'AEP': 0.269}\n\n```\n\n### Simulation\n\n\u003e Simulate and Select the Return Format (Seaborn, Plotly, DataFrame). DataFrame Option will also have the random weights used in each iteration.\n\n\u003e Please refer to the **Simulation.ipynb** jupyter notebook in **demo** directory for more detailed explanations.\n\n\n```python\n\n### Call Portopt.metric_options to see all available options for x, y axis\n\nPortOpt.simulate(x='expected_return', y='sharpe', y_var={\"risk_free\": 0.02}, iters=10000, weight_bound=(-1, 1), leverage=1, ret_format='sns')\n\n```\n![Sharpe VS Return](https://github.com/johnsoong216/pymarkowitz/blob/master/images/return_vs_sharpe.png)\n\n\n### Backtesting\n\n\u003e Use **pymarkowitz** to construct optimized weights and backtest with real life portfolio.\nIn this example, I am using SPDR sector ETFs to construct an optimized portfolio and compare against buy \u0026 hold SPY.\n\n\n---\n\n```python\nimport bt\n\ndata = bt.get('spy, rwr, xlb, xli, xly, xlp, xle, xlf, xlu, xlv, xlk', start='2005-01-01')\n```\n\n\u003e The configurations can be adjusted flexibly, please check backtesting.ipynb in demo directory for more detail. In this case we are minimizing volatility with a capped weight of 25% on each sector.\n```python\nstrategy = WeighMarkowitz(Config) #Imported from pymarkowitz.backtester.py\n\n# Personal Strategy\ns1 = bt.Strategy('s1', [bt.algos.RunWeekly(),\n                       bt.algos.SelectAll(),\n                       strategy,\n                       bt.algos.Rebalance()])\ntest1 = bt.Backtest(s1, data)\n\n# Buy \u0026 Hold\ns2 = bt.Strategy('s2', [bt.algos.RunWeekly(),\n                       bt.algos.SelectAll(),\n                       bt.algos.WeighEqually(),\n                       bt.algos.Rebalance()])\ntest2 = bt.Backtest(s2, data[['spy']].iloc[Config.lookback:])\nres = bt.run(test1, test2)\nres.plot()\n```\n![Backtest_Result](https://github.com/johnsoong216/pymarkowitz/blob/master/images/backtest_sector_vs_spy.PNG)\n\n\n---\n\n## Reference\n\nCalculations of **Correlation, Diversifcation \u0026 Risk Parity Factors**:\n\u003cbr\u003e\nhttps://investresolve.com/file/pdf/Portfolio-Optimization-Whitepaper.pdf\n\nCalculations for **Sharpe, Sortino, Beta, Treynor, Jenson's Alpha**:\n\u003cbr\u003e\nhttps://www.cfainstitute.org/-/media/documents/support/programs/investment-foundations/19-performance-evaluation.ashx?la=en\u0026hash=F7FF3085AAFADE241B73403142AAE0BB1250B311\n\u003cbr\u003e\nhttps://www.investopedia.com/terms/j/jensensmeasure.asp\n\u003cbr\u003e\nhttps://www.investopedia.com/ask/answers/070615/what-formula-calculating-beta.asp\n\u003cbr\u003e\n\nCalculations for **Higher Moment Matrices**:\n\u003cbr\u003e\nhttps://cran.r-project.org/web/packages/PerformanceAnalytics/vignettes/EstimationComoments.pdf\n\u003cbr\u003e\n\n\n---\n\n## License\n\n[![License](http://img.shields.io/:license-mit-blue.svg?style=flat-square)](http://badges.mit-license.org)\n\n- **[MIT license](http://opensource.org/licenses/mit-license.php)**\n- Copyright 2020 ©\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnsoong216%2Fpymarkowitz","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjohnsoong216%2Fpymarkowitz","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnsoong216%2Fpymarkowitz/lists"}