├── .qrignore ├── README.md ├── qmom ├── Introduction.ipynb ├── qmom.py └── Part1-Interactive-Strategy-Development.ipynb └── LICENSE.txt /.qrignore: -------------------------------------------------------------------------------- 1 | README.md 2 | LICENSE.txt 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # qmom 2 | 3 | Long-only momentum strategy modeled on Alpha Architect's QMOM ETF, selecting stocks with the smoothest momentum and rebalancing the portfolio before quarter end to capture a window-dressing seasonality effect. 4 | 5 | ## Clone in QuantRocket 6 | 7 | CLI: 8 | 9 | ```shell 10 | quantrocket codeload clone 'qmom' 11 | ``` 12 | 13 | Python: 14 | 15 | ```python 16 | from quantrocket.codeload import clone 17 | clone("qmom") 18 | ``` 19 | 20 | ## Browse in GitHub 21 | 22 | Start here: [qmom/Introduction.ipynb](qmom/Introduction.ipynb) 23 | 24 | *** 25 | 26 | Find more code in QuantRocket's [Codeload Library](https://www.quantrocket.com/code/) 27 | -------------------------------------------------------------------------------- /qmom/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 | "# QMOM: Quantitative Momentum\n", 16 | "\n", 17 | "This repository implements a long-only momentum strategy modeled on [Alpha Architect's QMOM ETF](https://etfsite.alphaarchitect.com/qmom/). QMOM provides a couple of enhancements to traditional momentum strategies, including selecting stocks with the smoothest momentum and rebalancing the portfolio before quarter end to capture a window-dressing seasonality effect.\n", 18 | "\n", 19 | "The rules of the QMOM strategy as outlined in the Alpha Architect white paper are:\n", 20 | "\n", 21 | "1. Universe selection\n", 22 | " 1. Starting universe: all NYSE stocks\n", 23 | " 2. Exclude financials, ADRs, REITs\n", 24 | " 3. Liquidity screen: select top N percent of stocks by market cap (N=60)\n", 25 | "2. Apply momentum screen: calculate 12-month returns, excluding most recent month, and select N percent of stocks with best return (N=10)\n", 26 | "3. Filter by smoothness of momentum: of the momentum stocks, select the N percent with the smoothest momentum, as measured by the number of positive days in the last 12 months (N=50)\n", 27 | "4. Apply equal weights \n", 28 | "5. Rebalance portfolio before quarter-end to capture window-dressing seasonality effect " 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": {}, 34 | "source": [ 35 | "## Prerequisites\n", 36 | "\n", 37 | "QVAL and QMOM make up the value and momentum portions, respectively, of the Alpha Architect VMOT (Value/Momentum/Trend) strategy. QMOM can be run independently of QVAL or VMOT. However, because the QMOM universe is identical to the QVAL universe, this tutorial relies on the data collection and universe selection of the QVAL tutorial. Please see that tutorial for help collecting the data and creating the universes.\n", 38 | "\n", 39 | "See also:\n", 40 | "\n", 41 | "* QVAL: `quantrocket codeload clone 'qval'`\n", 42 | "* VMOT: `quantrocket codeload clone 'vmot'`" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "metadata": {}, 48 | "source": [ 49 | "## Contents\n", 50 | "\n", 51 | "* Part 1: [Interactive Strategy Development](Part1-Interactive-Strategy-Development.ipynb)\n", 52 | "* Part 2: [Moonshot Backtest](Part2-Moonshot-Backtest.ipynb)\n", 53 | "* Part 3: [Parameter Scans](Part3-Parameter-Scans.ipynb)" 54 | ] 55 | } 56 | ], 57 | "metadata": { 58 | "kernelspec": { 59 | "display_name": "Python 3.9", 60 | "language": "python", 61 | "name": "python3" 62 | }, 63 | "language_info": { 64 | "codemirror_mode": { 65 | "name": "ipython", 66 | "version": 3 67 | }, 68 | "file_extension": ".py", 69 | "mimetype": "text/x-python", 70 | "name": "python", 71 | "nbconvert_exporter": "python", 72 | "pygments_lexer": "ipython3", 73 | "version": "3.9.7" 74 | } 75 | }, 76 | "nbformat": 4, 77 | "nbformat_minor": 4 78 | } 79 | -------------------------------------------------------------------------------- /qmom/qmom.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 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 | from moonshot.commission import PerShareCommission 18 | 19 | class USStockCommission(PerShareCommission): 20 | BROKER_COMMISSION_PER_SHARE = 0.005 21 | 22 | class QuantitativeMomentum(Moonshot): 23 | """ 24 | Momentum strategy modeled on Alpha Architect's QMOM ETF. 25 | 26 | Strategy rules: 27 | 28 | 1. Universe selection 29 | a. Starting universe: all NYSE stocks 30 | b. Exclude financials, ADRs, REITs 31 | c. Liquidity screen: select top N percent of stocks by dollar 32 | volume (N=60) 33 | 2. Apply momentum screen: calculate 12-month returns, excluding 34 | most recent month, and select N percent of stocks with best 35 | return (N=10) 36 | 3. Filter by smoothness of momentum: of the momentum stocks, select 37 | the N percent with the smoothest momentum, as measured by the number 38 | of positive days in the last 12 months (N=50) 39 | 4. Apply equal weights 40 | 5. Rebalance portfolio before quarter-end to capture window-dressing seasonality effect 41 | """ 42 | 43 | CODE = "qmom" 44 | DB = "sharadar-us-stk-1d" 45 | DB_FIELDS = ["Close", "Volume"] 46 | DOLLAR_VOLUME_TOP_N_PCT = 60 47 | DOLLAR_VOLUME_WINDOW = 90 48 | UNIVERSES = "nyse-stk" 49 | EXCLUDE_UNIVERSES = ["nyse-financials", "nyse-adrs", "nyse-reits"] 50 | MOMENTUM_WINDOW = 252 51 | MOMENTUM_EXCLUDE_MOST_RECENT_WINDOW = 22 52 | TOP_N_PCT = 10 53 | SMOOTHEST_TOP_N_PCT = 50 54 | REBALANCE_INTERVAL = "Q-NOV" # = end of quarter, fiscal year ends in Nov (= Nov 30, Feb 28, May 31, Aug 31); https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#anchored-offsets 55 | COMMISSION_CLASS = USStockCommission 56 | 57 | def prices_to_signals(self, prices: pd.DataFrame): 58 | 59 | # Step 1.c: get a mask of stocks with adequate dollar volume 60 | closes = prices.loc["Close"] 61 | volumes = prices.loc["Volume"] 62 | avg_dollar_volumes = (closes * volumes).rolling(self.DOLLAR_VOLUME_WINDOW).mean() 63 | dollar_volume_ranks = avg_dollar_volumes.rank(axis=1, ascending=False, pct=True) 64 | have_adequate_dollar_volumes = dollar_volume_ranks <= (self.DOLLAR_VOLUME_TOP_N_PCT/100) 65 | 66 | # Step 2: apply momentum screen 67 | year_ago_closes = closes.shift(self.MOMENTUM_WINDOW) 68 | month_ago_closes = closes.shift(self.MOMENTUM_EXCLUDE_MOST_RECENT_WINDOW) 69 | returns = (month_ago_closes - year_ago_closes) / year_ago_closes.where(year_ago_closes != 0) # avoid DivisionByZero errors 70 | # Rank only among stocks with adequate dollar volume 71 | returns_ranks = returns.where(have_adequate_dollar_volumes).rank(axis=1, ascending=False, pct=True) 72 | have_momentum = returns_ranks <= (self.TOP_N_PCT / 100) 73 | 74 | # Step 3: Filter by smoothness of momentum 75 | are_positive_days = closes.pct_change() > 0 76 | positive_days_last_twelve_months = are_positive_days.astype(int).rolling(self.MOMENTUM_WINDOW).sum() 77 | positive_days_last_twelve_months_ranks = positive_days_last_twelve_months.where(have_momentum).rank(axis=1, ascending=False, pct=True) 78 | have_smooth_momentum = positive_days_last_twelve_months_ranks <= (self.SMOOTHEST_TOP_N_PCT/100) 79 | 80 | signals = have_smooth_momentum.astype(int) 81 | return signals 82 | 83 | def signals_to_target_weights(self, signals: pd.DataFrame, prices: pd.DataFrame): 84 | # Step 4: equal weights 85 | daily_signal_counts = signals.abs().sum(axis=1) 86 | weights = signals.div(daily_signal_counts, axis=0).fillna(0) 87 | 88 | # Step 5: Rebalance portfolio before quarter-end to capture window-dressing seasonality effect 89 | # Resample daily to REBALANCE_INTERVAL, taking the last day's signal 90 | # For pandas offset aliases, see https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases 91 | weights = weights.resample(self.REBALANCE_INTERVAL).last() 92 | # Reindex back to daily and fill forward 93 | weights = weights.reindex(prices.loc["Close"].index, method="ffill") 94 | 95 | return weights 96 | 97 | def target_weights_to_positions(self, weights: pd.DataFrame, prices: pd.DataFrame): 98 | # Enter the position the day after the signal 99 | return weights.shift() 100 | 101 | def positions_to_gross_returns(self, positions: pd.DataFrame, prices: pd.DataFrame): 102 | closes = prices.loc["Close"] 103 | position_ends = positions.shift() 104 | 105 | # The return is the security's percent change over the period, 106 | # multiplied by the position. 107 | gross_returns = closes.pct_change() * position_ends 108 | 109 | return gross_returns 110 | 111 | def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame): 112 | orders["Exchange"] = "SMART" 113 | orders["OrderType"] = "MOC" 114 | orders["Tif"] = "DAY" 115 | return orders 116 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /qmom/Part1-Interactive-Strategy-Development.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 | "***\n", 16 | "[QMOM: Quantitative Momentum](Introduction.ipynb) › Part 1: Interactive Strategy Development\n", 17 | "***" 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "metadata": {}, 23 | "source": [ 24 | "# Interactive Strategy Development\n", 25 | "\n", 26 | "We'll develop our strategy logic interactively in a notebook, peeking at the DataFrames as we go, then transfer the code to a `.py` file for backtesting with Moonshot.\n", 27 | "\n", 28 | "As a reminder, the rules of the QMOM strategy as outlined in the Alpha Architect white paper are:\n", 29 | "\n", 30 | "1. Universe selection\n", 31 | " 1. Starting universe: all NYSE stocks\n", 32 | " 2. Exclude financials, ADRs, REITs\n", 33 | " 3. Liquidity screen: select top N percent of stocks by market cap (N=60)\n", 34 | "2. Apply momentum screen: calculate 12-month returns, excluding most recent month, and select N percent of stocks with best return (N=10)\n", 35 | "3. Filter by smoothness of momentum: of the momentum stocks, select the N percent with the smoothest momentum, as measured by the number of positive days in the last 12 months (N=50)\n", 36 | "4. Apply equal weights \n", 37 | "5. Rebalance portfolio before quarter-end to capture window-dressing seasonality effect " 38 | ] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "metadata": {}, 43 | "source": [ 44 | "## Query historical prices\n", 45 | "\n", 46 | "Start by querying historical prices from your Sharadar history database. We specify our universe of NYSE stocks as well as the universes we wish to exclude. \n", 47 | "\n", 48 | "For now we limit ourselves to a couple years of data to make it easier to work with. Later we'll run a backtest using a larger date range." 49 | ] 50 | }, 51 | { 52 | "cell_type": "code", 53 | "execution_count": 1, 54 | "metadata": {}, 55 | "outputs": [], 56 | "source": [ 57 | "from quantrocket import get_prices\n", 58 | "\n", 59 | "DB = \"sharadar-us-stk-1d\"\n", 60 | "UNIVERSES = \"nyse-stk\"\n", 61 | "EXCLUDE_UNIVERSES = [\"nyse-financials\", \"nyse-reits\", \"nyse-adrs\"]\n", 62 | "\n", 63 | "prices = get_prices(DB, \n", 64 | " start_date=\"2014-01-01\",\n", 65 | " end_date=\"2016-01-01\", \n", 66 | " universes=UNIVERSES,\n", 67 | " exclude_universes=EXCLUDE_UNIVERSES, \n", 68 | " fields=[\"Close\", \"Volume\"])" 69 | ] 70 | }, 71 | { 72 | "cell_type": "markdown", 73 | "metadata": {}, 74 | "source": [ 75 | "## Step 1.C: Filter by dollar volume\n", 76 | "\n", 77 | "The QMOM white paper calls for limiting the universe to the top 60% of stocks by market cap. We will use dollar volume as a proxy for market cap.\n", 78 | "\n", 79 | "The code below will compute daily ranks by dollar volume and give us a boolean mask indicating which stocks have adequate dollar volume." 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": 2, 85 | "metadata": {}, 86 | "outputs": [ 87 | { 88 | "data": { 89 | "text/html": [ 90 | "
\n", 91 | "\n", 104 | "\n", 105 | " \n", 106 | " \n", 107 | " \n", 108 | " \n", 109 | " \n", 110 | " \n", 111 | " \n", 112 | " \n", 113 | " \n", 114 | " \n", 115 | " \n", 116 | " \n", 117 | " \n", 118 | " \n", 119 | " \n", 120 | " \n", 121 | " \n", 122 | " \n", 123 | " \n", 124 | " \n", 125 | " \n", 126 | " \n", 127 | " \n", 128 | " \n", 129 | " \n", 130 | " \n", 131 | " \n", 132 | " \n", 133 | " \n", 134 | " \n", 135 | " \n", 136 | " \n", 137 | " \n", 138 | " \n", 139 | " \n", 140 | " \n", 141 | " \n", 142 | " \n", 143 | " \n", 144 | " \n", 145 | " \n", 146 | " \n", 147 | " \n", 148 | " \n", 149 | " \n", 150 | " \n", 151 | " \n", 152 | " \n", 153 | " \n", 154 | " \n", 155 | " \n", 156 | " \n", 157 | " \n", 158 | " \n", 159 | " \n", 160 | " \n", 161 | " \n", 162 | " \n", 163 | " \n", 164 | " \n", 165 | " \n", 166 | " \n", 167 | " \n", 168 | " \n", 169 | " \n", 170 | " \n", 171 | " \n", 172 | " \n", 173 | " \n", 174 | " \n", 175 | " \n", 176 | " \n", 177 | " \n", 178 | " \n", 179 | " \n", 180 | " \n", 181 | " \n", 182 | " \n", 183 | " \n", 184 | " \n", 185 | " \n", 186 | " \n", 187 | " \n", 188 | " \n", 189 | " \n", 190 | " \n", 191 | " \n", 192 | " \n", 193 | " \n", 194 | " \n", 195 | " \n", 196 | " \n", 197 | " \n", 198 | " \n", 199 | " \n", 200 | " \n", 201 | " \n", 202 | " \n", 203 | " \n", 204 | " \n", 205 | " \n", 206 | " \n", 207 | " \n", 208 | " \n", 209 | " \n", 210 | " \n", 211 | " \n", 212 | " \n", 213 | " \n", 214 | " \n", 215 | " \n", 216 | " \n", 217 | " \n", 218 | " \n", 219 | " \n", 220 | " \n", 221 | " \n", 222 | " \n", 223 | " \n", 224 | " \n", 225 | " \n", 226 | " \n", 227 | " \n", 228 | " \n", 229 | " \n", 230 | " \n", 231 | " \n", 232 | " \n", 233 | " \n", 234 | " \n", 235 | " \n", 236 | " \n", 237 | " \n", 238 | " \n", 239 | " \n", 240 | " \n", 241 | " \n", 242 | " \n", 243 | " \n", 244 | " \n", 245 | " \n", 246 | " \n", 247 | " \n", 248 | " \n", 249 | " \n", 250 | " \n", 251 | " \n", 252 | " \n", 253 | " \n", 254 | " \n", 255 | " \n", 256 | " \n", 257 | " \n", 258 | " \n", 259 | " \n", 260 | " \n", 261 | " \n", 262 | " \n", 263 | " \n", 264 | " \n", 265 | " \n", 266 | " \n", 267 | " \n", 268 | " \n", 269 | " \n", 270 | " \n", 271 | " \n", 272 | " \n", 273 | " \n", 274 | " \n", 275 | " \n", 276 | " \n", 277 | "
SidFIBBG0000018G2FIBBG000001J87FIBBG000001JC2FIBBG000001JD1FIBBG000001NT5FIBBG000001NV2FIBBG000001SF9FIBBG000002791FIBBG0000027B8FIBBG000002WJ5...QA000000001978QA000000001981QA000000001995QA000000014708QA000000014977QA000000017129QA000000018169QA000000020127QA000000021599QA000000021660
Date
2015-12-24FalseFalseFalseFalseFalseFalseFalseFalseFalseFalse...FalseFalseFalseFalseFalseFalseFalseFalseFalseTrue
2015-12-28FalseFalseFalseFalseFalseFalseFalseFalseFalseFalse...FalseFalseFalseFalseFalseFalseFalseFalseFalseTrue
2015-12-29FalseFalseFalseFalseFalseFalseFalseFalseFalseFalse...FalseFalseFalseFalseFalseFalseFalseFalseFalseTrue
2015-12-30FalseFalseFalseFalseFalseFalseFalseFalseFalseFalse...FalseFalseFalseFalseFalseFalseFalseFalseFalseTrue
2015-12-31FalseFalseFalseFalseFalseFalseFalseFalseFalseFalse...FalseFalseFalseFalseFalseFalseFalseFalseFalseTrue
\n", 278 | "

5 rows × 1600 columns

\n", 279 | "
" 280 | ], 281 | "text/plain": [ 282 | "Sid FIBBG0000018G2 FIBBG000001J87 FIBBG000001JC2 FIBBG000001JD1 \\\n", 283 | "Date \n", 284 | "2015-12-24 False False False False \n", 285 | "2015-12-28 False False False False \n", 286 | "2015-12-29 False False False False \n", 287 | "2015-12-30 False False False False \n", 288 | "2015-12-31 False False False False \n", 289 | "\n", 290 | "Sid FIBBG000001NT5 FIBBG000001NV2 FIBBG000001SF9 FIBBG000002791 \\\n", 291 | "Date \n", 292 | "2015-12-24 False False False False \n", 293 | "2015-12-28 False False False False \n", 294 | "2015-12-29 False False False False \n", 295 | "2015-12-30 False False False False \n", 296 | "2015-12-31 False False False False \n", 297 | "\n", 298 | "Sid FIBBG0000027B8 FIBBG000002WJ5 ... QA000000001978 \\\n", 299 | "Date ... \n", 300 | "2015-12-24 False False ... False \n", 301 | "2015-12-28 False False ... False \n", 302 | "2015-12-29 False False ... False \n", 303 | "2015-12-30 False False ... False \n", 304 | "2015-12-31 False False ... False \n", 305 | "\n", 306 | "Sid QA000000001981 QA000000001995 QA000000014708 QA000000014977 \\\n", 307 | "Date \n", 308 | "2015-12-24 False False False False \n", 309 | "2015-12-28 False False False False \n", 310 | "2015-12-29 False False False False \n", 311 | "2015-12-30 False False False False \n", 312 | "2015-12-31 False False False False \n", 313 | "\n", 314 | "Sid QA000000017129 QA000000018169 QA000000020127 QA000000021599 \\\n", 315 | "Date \n", 316 | "2015-12-24 False False False False \n", 317 | "2015-12-28 False False False False \n", 318 | "2015-12-29 False False False False \n", 319 | "2015-12-30 False False False False \n", 320 | "2015-12-31 False False False False \n", 321 | "\n", 322 | "Sid QA000000021660 \n", 323 | "Date \n", 324 | "2015-12-24 True \n", 325 | "2015-12-28 True \n", 326 | "2015-12-29 True \n", 327 | "2015-12-30 True \n", 328 | "2015-12-31 True \n", 329 | "\n", 330 | "[5 rows x 1600 columns]" 331 | ] 332 | }, 333 | "execution_count": 2, 334 | "metadata": {}, 335 | "output_type": "execute_result" 336 | } 337 | ], 338 | "source": [ 339 | "closes = prices.loc[\"Close\"]\n", 340 | "volumes = prices.loc[\"Volume\"]\n", 341 | "\n", 342 | "# calculate 90 day average dollar volume\n", 343 | "avg_dollar_volumes = (closes * volumes).rolling(90).mean()\n", 344 | "\n", 345 | "# rank biggest to smallest; pct=True gives percentile ranks between 0-1\n", 346 | "dollar_volume_ranks = avg_dollar_volumes.rank(axis=1, ascending=False, pct=True)\n", 347 | " \n", 348 | "have_adequate_dollar_volumes = dollar_volume_ranks <= (0.60)\n", 349 | "have_adequate_dollar_volumes.tail()" 350 | ] 351 | }, 352 | { 353 | "cell_type": "markdown", 354 | "metadata": {}, 355 | "source": [ 356 | "We'll use this filter in the next step." 357 | ] 358 | }, 359 | { 360 | "cell_type": "markdown", 361 | "metadata": {}, 362 | "source": [ 363 | "## Step 2: Apply momentum screen\n", 364 | "\n", 365 | "Next, we identify the 10% of stocks with the strongest 12-month momentum, excluding the most recent month. First calculate the returns:" 366 | ] 367 | }, 368 | { 369 | "cell_type": "code", 370 | "execution_count": 3, 371 | "metadata": {}, 372 | "outputs": [], 373 | "source": [ 374 | "TRADING_DAYS_PER_YEAR = 252\n", 375 | "TRADING_DAYS_PER_MONTH = 22\n", 376 | "year_ago_closes = closes.shift(TRADING_DAYS_PER_YEAR)\n", 377 | "month_ago_closes = closes.shift(TRADING_DAYS_PER_MONTH)\n", 378 | "returns = (month_ago_closes - year_ago_closes) / year_ago_closes.where(year_ago_closes != 0) # avoid DivisionByZero errors" 379 | ] 380 | }, 381 | { 382 | "cell_type": "markdown", 383 | "metadata": {}, 384 | "source": [ 385 | "We identify momentum stocks by ranking on returns, but we only apply the rankings to stocks with adequate dollar volume:" 386 | ] 387 | }, 388 | { 389 | "cell_type": "code", 390 | "execution_count": 4, 391 | "metadata": {}, 392 | "outputs": [], 393 | "source": [ 394 | "returns_ranks = returns.where(have_adequate_dollar_volumes).rank(axis=1, ascending=False, pct=True)\n", 395 | "have_momentum = returns_ranks <= 0.10" 396 | ] 397 | }, 398 | { 399 | "cell_type": "markdown", 400 | "metadata": {}, 401 | "source": [ 402 | "## Step 3: Filter by smoothness of momentum\n", 403 | "\n", 404 | "The next step is to rank the momentum stocks by the smoothness of their momentum and select the top 50%. To calculate \"smoothness,\" we count the number of days with a positive return over the last 12 months. The basic idea as explained in the white paper is that a stock which was mediocre for most of the year but made giant gains over a short period is not as appealing as a stock which rose more steadily over the course of the year. \n", 405 | "\n", 406 | "First, get a rolling count of positive days in the last year:" 407 | ] 408 | }, 409 | { 410 | "cell_type": "code", 411 | "execution_count": 5, 412 | "metadata": {}, 413 | "outputs": [], 414 | "source": [ 415 | "are_positive_days = closes.pct_change() > 0\n", 416 | "positive_days_last_twelve_months = are_positive_days.astype(int).rolling(TRADING_DAYS_PER_YEAR).sum()" 417 | ] 418 | }, 419 | { 420 | "cell_type": "markdown", 421 | "metadata": {}, 422 | "source": [ 423 | "Then, rank and filter to select the stocks with smoothest momentum:" 424 | ] 425 | }, 426 | { 427 | "cell_type": "code", 428 | "execution_count": 6, 429 | "metadata": {}, 430 | "outputs": [], 431 | "source": [ 432 | "positive_days_last_twelve_months_ranks = positive_days_last_twelve_months.where(have_momentum).rank(axis=1, ascending=False, pct=True)\n", 433 | "have_smooth_momentum = positive_days_last_twelve_months_ranks <= 0.50" 434 | ] 435 | }, 436 | { 437 | "cell_type": "markdown", 438 | "metadata": {}, 439 | "source": [ 440 | "These stocks are our long signals: " 441 | ] 442 | }, 443 | { 444 | "cell_type": "code", 445 | "execution_count": 7, 446 | "metadata": {}, 447 | "outputs": [], 448 | "source": [ 449 | "long_signals = have_smooth_momentum.astype(int)" 450 | ] 451 | }, 452 | { 453 | "cell_type": "markdown", 454 | "metadata": {}, 455 | "source": [ 456 | "## Step 4: Apply equal weights\n", 457 | "\n", 458 | "The QMOM strategy trades an equal-weighted portfolio. By convention, for an unlevered strategy the daily weights should add up to 1 (=100% invested), so we divide each day's signals by the number of signals to get the individual position weights: " 459 | ] 460 | }, 461 | { 462 | "cell_type": "code", 463 | "execution_count": 8, 464 | "metadata": {}, 465 | "outputs": [ 466 | { 467 | "data": { 468 | "text/plain": [ 469 | "Date\n", 470 | "2015-12-24 39\n", 471 | "2015-12-28 42\n", 472 | "2015-12-29 40\n", 473 | "2015-12-30 43\n", 474 | "2015-12-31 44\n", 475 | "dtype: int64" 476 | ] 477 | }, 478 | "execution_count": 8, 479 | "metadata": {}, 480 | "output_type": "execute_result" 481 | } 482 | ], 483 | "source": [ 484 | "daily_signal_counts = long_signals.abs().sum(axis=1)\n", 485 | "daily_signal_counts.tail()" 486 | ] 487 | }, 488 | { 489 | "cell_type": "code", 490 | "execution_count": 9, 491 | "metadata": {}, 492 | "outputs": [ 493 | { 494 | "data": { 495 | "text/plain": [ 496 | "Date Sid \n", 497 | "2015-12-31 FIBBG0027Y18M0 0.022727\n", 498 | " FIBBG002832GV8 0.022727\n", 499 | " FIBBG002WMH2F2 0.022727\n", 500 | " FIBBG00449JPX5 0.022727\n", 501 | " FIBBG00KXRCDP0 0.022727\n", 502 | "dtype: float64" 503 | ] 504 | }, 505 | "execution_count": 9, 506 | "metadata": {}, 507 | "output_type": "execute_result" 508 | } 509 | ], 510 | "source": [ 511 | "weights = long_signals.div(daily_signal_counts, axis=0).fillna(0)\n", 512 | "weights.where(weights!=0).stack().tail()" 513 | ] 514 | }, 515 | { 516 | "cell_type": "markdown", 517 | "metadata": {}, 518 | "source": [ 519 | "## Step 5: Rebalance before quarter-end\n", 520 | "\n", 521 | "The Alpha Architect white paper outlines a technique to potentially enhance momentum returns by rebalancing the portfolio a month or so before quarter-end. The intention is to benefit from window dressing behavior by portfolio managers who bid up the strongest performing stocks in the last month of the quarter in order to include them in their quarterly statements. \n", 522 | "\n", 523 | "To accomplish this with pandas, we can resample the DataFrame of daily weights to quarterly using the `Q-NOV` frequency. `Q-NOV` is a quarterly frequency with a fiscal year ending November 30. We can use pandas' `date_range` function to see some sample dates:" 524 | ] 525 | }, 526 | { 527 | "cell_type": "code", 528 | "execution_count": 10, 529 | "metadata": {}, 530 | "outputs": [ 531 | { 532 | "data": { 533 | "text/plain": [ 534 | "DatetimeIndex(['2018-02-28', '2018-05-31', '2018-08-31', '2018-11-30'], dtype='datetime64[ns]', freq='Q-NOV')" 535 | ] 536 | }, 537 | "execution_count": 10, 538 | "metadata": {}, 539 | "output_type": "execute_result" 540 | } 541 | ], 542 | "source": [ 543 | "import pandas as pd\n", 544 | "pd.date_range(start=\"2018-01-01\", freq=\"Q-NOV\", periods=4)" 545 | ] 546 | }, 547 | { 548 | "cell_type": "markdown", 549 | "metadata": {}, 550 | "source": [ 551 | "Rebalancing on these dates will allow us to benefit from quarter-end window dressing. After resampling to `Q-NOV`, we take the last signal of the modified quarter, then reindex back to daily and fill forward:" 552 | ] 553 | }, 554 | { 555 | "cell_type": "code", 556 | "execution_count": 11, 557 | "metadata": {}, 558 | "outputs": [], 559 | "source": [ 560 | "# Resample daily to Q-NOV, taking the last day's signal\n", 561 | "# For pandas offset aliases, see https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases\n", 562 | "weights = weights.resample(\"Q-NOV\").last()\n", 563 | "\n", 564 | "# Reindex back to daily and fill forward\n", 565 | "weights = weights.reindex(closes.index, method=\"ffill\")" 566 | ] 567 | }, 568 | { 569 | "cell_type": "markdown", 570 | "metadata": {}, 571 | "source": [ 572 | "## Step 6: Positions and returns\n", 573 | "\n", 574 | "The DataFrame of weights represents what we want to own, as calculated at the end of the day. Assuming we enter positions the next day, we simply shift the weights forward to simulate our positions:" 575 | ] 576 | }, 577 | { 578 | "cell_type": "code", 579 | "execution_count": 12, 580 | "metadata": {}, 581 | "outputs": [], 582 | "source": [ 583 | "positions = weights.shift()" 584 | ] 585 | }, 586 | { 587 | "cell_type": "markdown", 588 | "metadata": {}, 589 | "source": [ 590 | "To calculate the return (before costs), we multiply the security's percent change over the period by the size of the position.\n", 591 | "\n", 592 | "Since `positions` represents when we enter the position, we must shift `positions` forward to get the \"end\" of the position, since that is when we collect the percent change, not when we first enter the position." 593 | ] 594 | }, 595 | { 596 | "cell_type": "code", 597 | "execution_count": 13, 598 | "metadata": {}, 599 | "outputs": [], 600 | "source": [ 601 | "position_ends = positions.shift()\n", 602 | "gross_returns = closes.pct_change() * position_ends" 603 | ] 604 | }, 605 | { 606 | "cell_type": "markdown", 607 | "metadata": {}, 608 | "source": [ 609 | "***\n", 610 | "\n", 611 | "## *Next Up*\n", 612 | "\n", 613 | "Part 2: [Moonshot Backtest](Part2-Moonshot-Backtest.ipynb)" 614 | ] 615 | } 616 | ], 617 | "metadata": { 618 | "kernelspec": { 619 | "display_name": "Python 3.9", 620 | "language": "python", 621 | "name": "python3" 622 | }, 623 | "language_info": { 624 | "codemirror_mode": { 625 | "name": "ipython", 626 | "version": 3 627 | }, 628 | "file_extension": ".py", 629 | "mimetype": "text/x-python", 630 | "name": "python", 631 | "nbconvert_exporter": "python", 632 | "pygments_lexer": "ipython3", 633 | "version": "3.9.7" 634 | } 635 | }, 636 | "nbformat": 4, 637 | "nbformat_minor": 4 638 | } 639 | --------------------------------------------------------------------------------