├── .qrignore ├── README.md ├── pairs_pipeline ├── Introduction.ipynb ├── Part1-Data-Collection.ipynb └── pairs.py └── LICENSE.txt /.qrignore: -------------------------------------------------------------------------------- 1 | README.md 2 | LICENSE.txt 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pairs-pipeline 2 | 3 | Pairs trading strategy that includes a research pipeline for identifying and selecting pairs. Tests all possible pairs in a universe for cointegration using the Johansen test, then runs in-sample backtests on all cointegrating pairs, then runs an out-of-sample backtest on the 5 best performing pairs. Calculates daily hedge ratios using the Johansen test and times entries and exits using Bollinger Bands. Trading rules adapted from Ernie Chan's book *Algorithmic Trading*. Runs in Moonshot on the universe of US ETFs. 4 | 5 | ## Clone in QuantRocket 6 | 7 | CLI: 8 | 9 | ```shell 10 | quantrocket codeload clone 'pairs-pipeline' 11 | ``` 12 | 13 | Python: 14 | 15 | ```python 16 | from quantrocket.codeload import clone 17 | clone("pairs-pipeline") 18 | ``` 19 | 20 | ## Browse in GitHub 21 | 22 | Start here: [pairs_pipeline/Introduction.ipynb](pairs_pipeline/Introduction.ipynb) 23 | 24 | *** 25 | 26 | Find more code in QuantRocket's [Codeload Library](https://www.quantrocket.com/code/) 27 | -------------------------------------------------------------------------------- /pairs_pipeline/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 | "# Pairs Trading Strategy with Pairs Selection Pipeline\n", 16 | "\n", 17 | "This tutorial demonstrates a research pipeline for identifying and backtesting ETF or stock pairs using Moonshot. From a starting universe of stocks or ETFs, all pair combinations are tested for cointegration using the Johansen test. In-sample backtests are run on all cointegrating pairs. A portfolio of the 5 best performing pairs is then selected and backtested out-of-sample. \n", 18 | "\n", 19 | "The pairs trading strategy re-calculates daily hedge ratios using the Johansen test and times entries and exits using Bollinger Bands, as outlined in Ernie Chan's book *Algorithmic Trading: Winning Strategies and Their Rationale*, Wiley, 2013, chapter 4. \n", 20 | "\n", 21 | "The use of a pairs selection pipeline is aimed at mitigating the tendency of cointegrating pairs to eventually cease cointegrating. The tutorial runs on the universe of US ETFs but is designed to be easily adaptable to other universes of stocks or ETFs." 22 | ] 23 | }, 24 | { 25 | "cell_type": "markdown", 26 | "metadata": {}, 27 | "source": [ 28 | "* Part 1: [Data Collection](Part1-Data-Collection.ipynb)\n", 29 | "* Part 2: [Moonshot Pairs Trading Strategy](Part2-Moonshot-Pairs-Strategy.ipynb)\n", 30 | "* Part 3: [Pairs Selection Pipeline](Part3-Pairs-Selection-Pipeline.ipynb)" 31 | ] 32 | } 33 | ], 34 | "metadata": { 35 | "kernelspec": { 36 | "display_name": "Python 3.11", 37 | "language": "python", 38 | "name": "python3" 39 | }, 40 | "language_info": { 41 | "codemirror_mode": { 42 | "name": "ipython", 43 | "version": 3 44 | }, 45 | "file_extension": ".py", 46 | "mimetype": "text/x-python", 47 | "name": "python", 48 | "nbconvert_exporter": "python", 49 | "pygments_lexer": "ipython3", 50 | "version": "3.11.0" 51 | } 52 | }, 53 | "nbformat": 4, 54 | "nbformat_minor": 4 55 | } 56 | -------------------------------------------------------------------------------- /pairs_pipeline/Part1-Data-Collection.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 | "[Pairs Trading](Introduction.ipynb) › Part 1: Data Collection\n", 17 | "***" 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "metadata": {}, 23 | "source": [ 24 | "# Data Collection\n", 25 | "\n", 26 | "The data collection process consists of collecting 1-day bars for US stocks and creating a universe of ETFs." 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "metadata": {}, 32 | "source": [ 33 | "## Collect historical data\n", 34 | "\n", 35 | "First, we create a database for collecting 1-day bars." 36 | ] 37 | }, 38 | { 39 | "cell_type": "code", 40 | "execution_count": 1, 41 | "metadata": {}, 42 | "outputs": [ 43 | { 44 | "data": { 45 | "text/plain": [ 46 | "{'status': 'successfully created quantrocket.v2.history.usstock-1d.sqlite'}" 47 | ] 48 | }, 49 | "execution_count": 1, 50 | "metadata": {}, 51 | "output_type": "execute_result" 52 | } 53 | ], 54 | "source": [ 55 | "from quantrocket.history import create_usstock_db\n", 56 | "create_usstock_db(\"usstock-1d\", bar_size=\"1 day\")" 57 | ] 58 | }, 59 | { 60 | "cell_type": "markdown", 61 | "metadata": {}, 62 | "source": [ 63 | "Then collect the data:" 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": 2, 69 | "metadata": {}, 70 | "outputs": [ 71 | { 72 | "data": { 73 | "text/plain": [ 74 | "{'status': 'the historical data will be collected asynchronously'}" 75 | ] 76 | }, 77 | "execution_count": 2, 78 | "metadata": {}, 79 | "output_type": "execute_result" 80 | } 81 | ], 82 | "source": [ 83 | "from quantrocket.history import collect_history\n", 84 | "collect_history(\"usstock-1d\")" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "metadata": {}, 90 | "source": [ 91 | "Monitor flightlog for completion:\n", 92 | "\n", 93 | "```\n", 94 | "quantrocket.history: INFO [usstock-1d] Collecting US history from 2007 to present\n", 95 | "quantrocket.history: INFO [usstock-1d] Collecting updated US securities listings\n", 96 | "quantrocket.history: INFO [usstock-1d] Collecting additional US history from 2020-04 to present\n", 97 | "quantrocket.history: INFO [usstock-1d] Collected 160 monthly files in quantrocket.v2.history.usstock-1d.sqlite\n", 98 | "```" 99 | ] 100 | }, 101 | { 102 | "cell_type": "markdown", 103 | "metadata": {}, 104 | "source": [ 105 | "## Define universe of US ETFs \n", 106 | "\n", 107 | "Next we download a CSV of US ETFs:" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": 3, 113 | "metadata": {}, 114 | "outputs": [], 115 | "source": [ 116 | "from quantrocket.master import download_master_file\n", 117 | "download_master_file(\"us_etfs.csv\", vendors=\"usstock\", sec_types=\"ETF\")" 118 | ] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "metadata": {}, 123 | "source": [ 124 | "Then upload the CSV to create the \"us-etf\" universe:" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": 4, 130 | "metadata": {}, 131 | "outputs": [ 132 | { 133 | "data": { 134 | "text/plain": [ 135 | "{'code': 'us-etf',\n", 136 | " 'provided': 5855,\n", 137 | " 'inserted': 5855,\n", 138 | " 'total_after_insert': 5855}" 139 | ] 140 | }, 141 | "execution_count": 4, 142 | "metadata": {}, 143 | "output_type": "execute_result" 144 | } 145 | ], 146 | "source": [ 147 | "from quantrocket.master import create_universe\n", 148 | "create_universe(\"us-etf\", infilepath_or_buffer=\"us_etfs.csv\")" 149 | ] 150 | }, 151 | { 152 | "cell_type": "markdown", 153 | "metadata": {}, 154 | "source": [ 155 | "***\n", 156 | "\n", 157 | "## *Next Up*\n", 158 | "\n", 159 | "Part 2: [Moonshot Pairs Strategy](Part2-Moonshot-Pairs-Strategy.ipynb)" 160 | ] 161 | } 162 | ], 163 | "metadata": { 164 | "kernelspec": { 165 | "display_name": "Python 3.11", 166 | "language": "python", 167 | "name": "python3" 168 | }, 169 | "language_info": { 170 | "codemirror_mode": { 171 | "name": "ipython", 172 | "version": 3 173 | }, 174 | "file_extension": ".py", 175 | "mimetype": "text/x-python", 176 | "name": "python", 177 | "nbconvert_exporter": "python", 178 | "pygments_lexer": "ipython3", 179 | "version": "3.11.0" 180 | } 181 | }, 182 | "nbformat": 4, 183 | "nbformat_minor": 4 184 | } 185 | -------------------------------------------------------------------------------- /pairs_pipeline/pairs.py: -------------------------------------------------------------------------------- 1 | # Copyright 2019-2024 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 statsmodels.tsa.vector_ar.vecm import coint_johansen 17 | from moonshot import Moonshot 18 | from moonshot.commission import PerShareCommission 19 | 20 | class USStockCommission(PerShareCommission): 21 | BROKER_COMMISSION_PER_SHARE = 0.005 22 | 23 | class PairsStrategy(Moonshot): 24 | """ 25 | Pairs trading strategy that uses the Johansen test to re-calculate 26 | hedge ratios daily and uses Bollinger Bands to time entries and exits. 27 | Buys (sells) the spread when it crosses below (above) its lower (upper) 28 | Bollinger Band and exits when it crosses its moving average. 29 | 30 | To use the strategy, subclass this base class and define the appropriate 31 | DB and SIDS. 32 | """ 33 | 34 | CODE = "pairs" 35 | DB = None 36 | DB_FIELDS = ["Close", "Open"] 37 | SIDS = [] 38 | LOOKBACK_WINDOW = 20 # Calculate hedge ratios and Bollinger Bands using this lookback 39 | BBAND_STD = 1 # Set Bollinger Bands this many standard deviations away from mean 40 | COMMISSION_CLASS = USStockCommission 41 | 42 | def get_hedge_ratio(self, pair_prices: pd.DataFrame): 43 | """ 44 | Helper function that uses the Johansen test to calculate hedge ratio. This is applied 45 | to the pair prices on a rolling basis in prices_to_signals. 46 | """ 47 | pair_prices = pair_prices.dropna() 48 | 49 | # Skip if we don't have at least 75% of the expected observations 50 | if len(pair_prices) < self.LOOKBACK_WINDOW * 0.75: 51 | return pd.Series(0, index=pair_prices.columns) 52 | 53 | # The second and third parameters indicate constant term, with a lag of 1. 54 | # See Chan, Algorithmic Trading, chapter 2. 55 | result = coint_johansen(pair_prices, 0, 1) 56 | 57 | # The first column of eigenvectors contains the best weights 58 | weights = list(result.evec[:, 0]) 59 | 60 | return pd.Series(weights, index=pair_prices.columns) 61 | 62 | def prices_to_signals(self, prices: pd.DataFrame): 63 | """ 64 | Generates a DataFrame of signals indicating whether to long or short the 65 | spread. 66 | """ 67 | closes = prices.loc["Close"] 68 | 69 | # Calculate hedge ratios on a rolling basis. Unfortunately, pandas 70 | # rolling apply() won't work here, so we have to loop through each day 71 | all_hedge_ratios = [] 72 | for idx in range(len(closes)): 73 | start_idx = idx - self.LOOKBACK_WINDOW 74 | some_closes = closes.iloc[start_idx:idx] 75 | hedge_ratio = self.get_hedge_ratio(some_closes) 76 | hedge_ratio = pd.Series(hedge_ratio).to_frame().T 77 | all_hedge_ratios.append(hedge_ratio) 78 | 79 | hedge_ratios = pd.concat(all_hedge_ratios) 80 | hedge_ratios.index = closes.index 81 | 82 | # Compute spread and Bollinger Bands (spreads and everything derived 83 | # from it is a Series, which we later broadcast back to a DataFrame) 84 | spreads = (closes * hedge_ratios).sum(axis=1) 85 | means = spreads.ffill().rolling(self.LOOKBACK_WINDOW).mean() 86 | stds = spreads.ffill().rolling(self.LOOKBACK_WINDOW).std() 87 | upper_bands = means + self.BBAND_STD * stds 88 | lower_bands = means - self.BBAND_STD * stds 89 | 90 | # Long (short) the spread when it crosses below (above) the lower (upper) 91 | # band, then exit when it crosses the mean 92 | long_entries = spreads < lower_bands 93 | long_exits = spreads >= means 94 | short_entries = spreads > upper_bands 95 | short_exits = spreads <= means 96 | 97 | # Combine entries and exits 98 | ones = pd.Series(1, index=spreads.index) 99 | zeros = pd.Series(0, index=spreads.index) 100 | minus_ones = pd.Series(-1, index=spreads.index) 101 | long_signals = ones.where(long_entries).fillna(zeros.where(long_exits)).ffill() 102 | short_signals = minus_ones.where(short_entries).fillna(zeros.where(short_exits)).ffill() 103 | signals = long_signals + short_signals 104 | 105 | # Broadcast Series of signals to DataFrame 106 | signals = closes.apply(lambda x: signals) 107 | 108 | # Save hedge_ratios for signals_to_target_weights 109 | self.hedge_ratios = hedge_ratios 110 | 111 | return signals 112 | 113 | def signals_to_target_weights(self, signals: pd.DataFrame, prices: pd.DataFrame): 114 | """ 115 | Converts the DataFrame of integer signals, indicating whether to long 116 | or short the spread, into the corresponding weight of each instrument 117 | to hold. 118 | """ 119 | # hedge_ratios represents ratios of shares, multiply by price to get ratios 120 | # of weights 121 | hedge_ratio_weights = self.hedge_ratios * prices.loc["Close"] 122 | 123 | # Multiply weight ratios by signals to get target weights, then reduce to 124 | # 1X total allocation 125 | weights = signals * hedge_ratio_weights 126 | total_weights= weights.abs().sum(axis=1) 127 | weights = weights.div(total_weights, axis=0) 128 | return weights 129 | 130 | def target_weights_to_positions(self, weights: pd.DataFrame, prices: pd.DataFrame): 131 | # we'll enter in the period after the signal 132 | positions = weights.shift() 133 | return positions 134 | 135 | def positions_to_gross_returns(self, positions: pd.DataFrame, prices: pd.DataFrame): 136 | # Enter and exit on the open 137 | opens = prices.loc["Open"] 138 | gross_returns = opens.pct_change() * positions.shift() 139 | return gross_returns 140 | 141 | class GDX_GLD_Pair(PairsStrategy): 142 | 143 | CODE = "pairs-gdx-gld" 144 | DB = "usstock-1d" 145 | SIDS = [ 146 | "FIBBG000PLNQN7", # GDX 147 | "FIBBG000CRF6Q8", # GLD 148 | ] 149 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------