├── .qrignore ├── benchmark ├── __init__.py ├── Introduction.ipynb └── benchmark.py ├── README.md └── LICENSE.txt /.qrignore: -------------------------------------------------------------------------------- 1 | README.md 2 | LICENSE.txt 3 | -------------------------------------------------------------------------------- /benchmark/__init__.py: -------------------------------------------------------------------------------- 1 | from codeload.benchmark.benchmark import EqualWeightedIndex, DollarVolumeWeightedIndex 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # benchmark 2 | 3 | Equal-weighted and dollar-volume-weighted benchmark strategies for Moonshot. 4 | 5 | ## Clone in QuantRocket 6 | 7 | CLI: 8 | 9 | ```shell 10 | quantrocket codeload clone 'benchmark' 11 | ``` 12 | 13 | Python: 14 | 15 | ```python 16 | from quantrocket.codeload import clone 17 | clone("benchmark") 18 | ``` 19 | 20 | ## Browse in GitHub 21 | 22 | Start here: [benchmark/Introduction.ipynb](benchmark/Introduction.ipynb) 23 | 24 | *** 25 | 26 | Find more code in QuantRocket's [Codeload Library](https://www.quantrocket.com/code/) 27 | -------------------------------------------------------------------------------- /benchmark/Introduction.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "\"QuantRocket
\n", 8 | "Disclaimer" 9 | ] 10 | }, 11 | { 12 | "cell_type": "markdown", 13 | "metadata": {}, 14 | "source": [ 15 | "# Moonshot Benchmarks\n", 16 | "\n", 17 | "This repository provides equal-weighted and dollar-volume-weighted benchmark strategies for Moonshot.\n", 18 | "\n", 19 | "You can construct the benchmark strategy with the same universe of securities used in the trading strategy you want to compare to create a more meaningful benchmark than standard indexes like the S&P 500. " 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "## Usage\n", 27 | "\n", 28 | "The strategies provided in [benchmark.py](benchmark.py) are base classes and must be subclassed. Provide a `CODE` and `DB` (and optionally `UNIVERSES` and `EXCLUDE_UNIVERSES`):\n", 29 | "\n", 30 | "```python \n", 31 | "from codeload.benchmark import EqualWeightedIndex\n", 32 | "\n", 33 | "class CanadaEqualWeightedIndex(EqualWeightedIndex):\n", 34 | "\n", 35 | " CODE = \"canada-benchmark\"\n", 36 | " DB = \"canada-stk-1d\"\n", 37 | "```\n", 38 | "\n", 39 | "You can filter the universe by minimum average dollar volume: \n", 40 | " \n", 41 | "```python \n", 42 | "class CanadaEqualWeightedIndex(EqualWeightedIndex):\n", 43 | "\n", 44 | " CODE = \"canada-benchmark\"\n", 45 | " DB = \"canada-stk-1d\"\n", 46 | " MIN_DOLLAR_VOLUME = 1e6\n", 47 | "```\n", 48 | "\n", 49 | "Or by dollar volume rank:\n", 50 | "\n", 51 | "```python\n", 52 | "class CanadaEqualWeightedIndex(EqualWeightedIndex):\n", 53 | "\n", 54 | " CODE = \"canada-benchmark\"\n", 55 | " DB = \"canada-stk-1d\"\n", 56 | " DOLLAR_VOLUME_TOP_N_PCT = 50\n", 57 | "```\n", 58 | "\n", 59 | "A dollar-volume weighted variant is also provided:\n", 60 | "\n", 61 | "```python\n", 62 | "from codeload.benchmark import DollarVolumeWeightedIndex\n", 63 | "\n", 64 | "class JapanDollarVolumeWeightedIndex(DollarVolumeWeightedIndex):\n", 65 | "\n", 66 | " CODE = \"japan-benchmark\"\n", 67 | " DB = \"japan-stk-1d\"\n", 68 | "```\n", 69 | "\n", 70 | "Adapt the strategies as needed to mirror the trading rules, minus alpha factors, of the strategy you want to compare." 71 | ] 72 | } 73 | ], 74 | "metadata": { 75 | "kernelspec": { 76 | "display_name": "Python 3", 77 | "language": "python", 78 | "name": "python3" 79 | }, 80 | "language_info": { 81 | "codemirror_mode": { 82 | "name": "ipython", 83 | "version": 3 84 | }, 85 | "file_extension": ".py", 86 | "mimetype": "text/x-python", 87 | "name": "python", 88 | "nbconvert_exporter": "python", 89 | "pygments_lexer": "ipython3", 90 | "version": "3.6.6" 91 | } 92 | }, 93 | "nbformat": 4, 94 | "nbformat_minor": 2 95 | } 96 | -------------------------------------------------------------------------------- /benchmark/benchmark.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019 QuantRocket LLC - All Rights Reserved 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import pandas as pd 16 | from moonshot import Moonshot 17 | 18 | class EqualWeightedIndex(Moonshot): 19 | """ 20 | Strategy that buys all stocks in the universe, optionally filtering by dollar volume, 21 | and weights equally. 22 | 23 | Examples 24 | -------- 25 | Create equal-weighted index of Canadian stocks with average dollar volume >= 1M CAD: 26 | 27 | >>> from codeload.benchmark import EqualWeightedIndex 28 | >>> 29 | >>> class CanadaEqualWeightedIndex(EqualWeightedIndex): 30 | >>> 31 | >>> CODE = "canada-benchmark" 32 | >>> DB = "canada-stk-1d" 33 | >>> MIN_DOLLAR_VOLUME = 1e6 34 | """ 35 | CODE = None 36 | DB = None 37 | DB_FIELDS = ["Close", "Volume"] 38 | UNIVERSES = None 39 | EXCLUDE_UNIVERSES = None 40 | 41 | # Optionally filter universe by min dollar volume, or dollar volume rank 42 | # (dollar volume rank takes precedence if both defined) 43 | MIN_DOLLAR_VOLUME = 0 44 | DOLLAR_VOLUME_TOP_N_PCT = None 45 | DOLLAR_VOLUME_WINDOW = 30 46 | 47 | def prices_to_signals(self, prices: pd.DataFrame): 48 | 49 | dollar_volumes = prices.loc["Volume"] * prices.loc["Close"] 50 | avg_dollar_volumes = dollar_volumes.rolling(window=self.DOLLAR_VOLUME_WINDOW).mean() 51 | if self.DOLLAR_VOLUME_TOP_N_PCT: 52 | dollar_volume_ranks = avg_dollar_volumes.rank(axis=1, ascending=False, pct=True) 53 | have_adequate_dollar_volumes = dollar_volume_ranks <= (self.DOLLAR_VOLUME_TOP_N_PCT/100) 54 | else: 55 | have_adequate_dollar_volumes = avg_dollar_volumes >= self.MIN_DOLLAR_VOLUME 56 | 57 | signals = have_adequate_dollar_volumes.astype(int) 58 | return signals 59 | 60 | def signals_to_target_weights(self, signals: pd.DataFrame, prices: pd.DataFrame): 61 | weights = self.allocate_equal_weights(signals) 62 | return weights 63 | 64 | def target_weights_to_positions(self, weights: pd.DataFrame, prices: pd.DataFrame): 65 | positions = weights.shift() 66 | return positions 67 | 68 | def positions_to_gross_returns(self, positions: pd.DataFrame, prices: pd.DataFrame): 69 | closes = prices.loc["Close"] 70 | pct_changes = closes.pct_change() 71 | # Ignore gains or losses that are likely spurious data (e.g. 2->100 or 100->2) 72 | pct_changes = pct_changes.where((pct_changes > -0.98) & (pct_changes < 50), 0) 73 | gross_returns = pct_changes * positions.shift() 74 | return gross_returns 75 | 76 | class DollarVolumeWeightedIndex(EqualWeightedIndex): 77 | """ 78 | Strategy that buys all stocks in the universe, optionally filtering by dollar volume, 79 | and weights by dollar volume. 80 | 81 | Examples 82 | -------- 83 | Create dollar-volume-weighted index of Japanese stocks, including only stocks in the top 84 | 50% of dollar volume: 85 | 86 | >>> from codeload.benchmark import DollarVolumeWeightedIndex 87 | >>> 88 | >>> class JapanDollarVolumeWeightedIndex(DollarVolumeWeightedIndex): 89 | >>> 90 | >>> CODE = "japan-benchmark" 91 | >>> DB = "japan-stk-1d" 92 | >>> DOLLAR_VOLUME_TOP_N_PCT = 50 93 | """ 94 | CODE = None 95 | DB = None 96 | DB_FIELDS = ["Close", "Volume"] 97 | UNIVERSES = None 98 | EXCLUDE_UNIVERSES = None 99 | 100 | # Optionally filter universe by min dollar volume, or dollar volume rank 101 | # (dollar volume rank takes precedence if both defined) 102 | MIN_DOLLAR_VOLUME = 0 103 | DOLLAR_VOLUME_TOP_N_PCT = None 104 | DOLLAR_VOLUME_WINDOW = 30 105 | 106 | def signals_to_target_weights(self, signals: pd.DataFrame, prices: pd.DataFrame): 107 | 108 | dollar_volumes = prices.loc["Volume"] * prices.loc["Close"] 109 | avg_dollar_volumes = dollar_volumes.rolling(window=self.DOLLAR_VOLUME_WINDOW).mean() 110 | avg_dollar_volumes = avg_dollar_volumes.where(signals > 0) 111 | 112 | total_daily_dollar_volumes = avg_dollar_volumes.sum(axis=1) 113 | weights = avg_dollar_volumes.div(total_daily_dollar_volumes, axis=0) 114 | return weights 115 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 10 | 11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 12 | 13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 14 | 15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 16 | 17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 18 | 19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. 20 | 21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). 22 | 23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. 24 | 25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." 26 | 27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 28 | 29 | 2. Grant of Copyright License. 30 | 31 | Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 32 | 33 | 3. Grant of Patent License. 34 | 35 | Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 36 | 37 | 4. Redistribution. 38 | 39 | You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: 40 | 41 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 42 | You must cause any modified files to carry prominent notices stating that You changed the files; and 43 | You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and 44 | If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. 45 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 46 | 47 | 5. Submission of Contributions. 48 | 49 | Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 50 | 51 | 6. Trademarks. 52 | 53 | This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 54 | 55 | 7. Disclaimer of Warranty. 56 | 57 | Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 58 | 59 | 8. Limitation of Liability. 60 | 61 | In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 62 | 63 | 9. Accepting Warranty or Additional Liability. 64 | 65 | While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. 66 | 67 | END OF TERMS AND CONDITIONS 68 | --------------------------------------------------------------------------------