├── .qrignore ├── README.md ├── zipline-futures-pairs └── futures_pairs_trading.py └── LICENSE.txt /.qrignore: -------------------------------------------------------------------------------- 1 | README.md 2 | LICENSE.txt 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # zipline-futures-pairs 2 | 3 | A futures pairs trading Zipline strategy. Adapted from the Quantopian futures pairs trading tutorial. 4 | 5 | ## Clone in QuantRocket 6 | 7 | CLI: 8 | 9 | ```shell 10 | quantrocket codeload clone 'zipline-futures-pairs' 11 | ``` 12 | 13 | Python: 14 | 15 | ```python 16 | from quantrocket.codeload import clone 17 | clone("zipline-futures-pairs") 18 | ``` 19 | -------------------------------------------------------------------------------- /zipline-futures-pairs/futures_pairs_trading.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import scipy as sp 3 | from zipline.api import ( 4 | continuous_future, 5 | schedule_function, 6 | date_rules, 7 | time_rules, 8 | record, 9 | order_target_percent, 10 | set_benchmark, 11 | set_commission, 12 | commission, 13 | set_slippage, 14 | slippage 15 | ) 16 | 17 | def initialize(context): 18 | 19 | # Get continuous futures for Light Sweet Crude Oil... 20 | context.crude_oil = continuous_future('CL', roll='calendar') 21 | # ... and RBOB Gasoline 22 | context.gasoline = continuous_future('RB', roll='calendar') 23 | 24 | # If Zipline has trouble pulling the default benchmark, try setting the 25 | # benchmark to something already in your bundle 26 | set_benchmark(context.crude_oil) 27 | 28 | # Ignore commissions and slippage for now 29 | set_commission(us_futures=commission.PerTrade(cost=0)) 30 | set_slippage(us_futures=slippage.FixedSlippage(spread=0.0)) 31 | 32 | # Long and short moving average window lengths 33 | context.long_ma = 65 34 | context.short_ma = 5 35 | 36 | # True if we currently hold a long position on the spread 37 | context.currently_long_the_spread = False 38 | # True if we currently hold a short position on the spread 39 | context.currently_short_the_spread = False 40 | 41 | # Rebalance pairs every day, 30 minutes after market open 42 | schedule_function(func=rebalance_pairs, 43 | date_rule=date_rules.every_day(), 44 | time_rule=time_rules.market_open(minutes=30)) 45 | 46 | # Record Crude Oil and Gasoline Futures prices everyday 47 | schedule_function(record_price, 48 | date_rules.every_day(), 49 | time_rules.market_open()) 50 | 51 | def rebalance_pairs(context, data): 52 | 53 | # Calculate how far away the current spread is from its equilibrium 54 | zscore = calc_spread_zscore(context, data) 55 | 56 | # Get target weights to rebalance portfolio 57 | target_weights = get_target_weights(context, data, zscore) 58 | 59 | if target_weights: 60 | # If we have target weights, rebalance portfolio 61 | cl_contract, rb_contract = data.current( 62 | [context.crude_oil, context.gasoline], 63 | 'contract' 64 | ) 65 | order_target_percent(cl_contract, target_weights[cl_contract]) 66 | order_target_percent(rb_contract, target_weights[rb_contract]) 67 | 68 | def calc_spread_zscore(context, data): 69 | 70 | # Get pricing data for our pair of continuous futures 71 | prices = data.history([context.crude_oil, 72 | context.gasoline], 73 | 'price', 74 | context.long_ma, 75 | '1d') 76 | 77 | cl_price = prices[context.crude_oil] 78 | rb_price = prices[context.gasoline] 79 | 80 | # Calculate returns for each continuous future 81 | cl_returns = cl_price.pct_change()[1:] 82 | rb_returns = rb_price.pct_change()[1:] 83 | 84 | # Calculate the spread 85 | regression = sp.stats.linregress( 86 | rb_returns[-context.long_ma:], 87 | cl_returns[-context.long_ma:], 88 | ) 89 | spreads = cl_returns - (regression.slope * rb_returns) 90 | 91 | # Calculate zscore of current spread 92 | zscore = (np.mean(spreads[-context.short_ma]) - np.mean(spreads)) / np.std(spreads, ddof=1) 93 | 94 | return zscore 95 | 96 | def get_target_weights(context, data, zscore): 97 | 98 | # Get current contracts for both continuous futures 99 | cl_contract, rb_contract = data.current( 100 | [context.crude_oil, context.gasoline], 101 | 'contract' 102 | ) 103 | 104 | # Initialize target weights 105 | target_weights = {} 106 | 107 | if context.currently_short_the_spread and zscore < 0.0: 108 | # Update target weights to exit position 109 | target_weights[cl_contract] = 0 110 | target_weights[rb_contract] = 0 111 | 112 | context.currently_long_the_spread = False 113 | context.currently_short_the_spread = False 114 | 115 | elif context.currently_long_the_spread and zscore > 0.0: 116 | # Update target weights to exit position 117 | target_weights[cl_contract] = 0 118 | target_weights[rb_contract] = 0 119 | 120 | context.currently_long_the_spread = False 121 | context.currently_short_the_spread = False 122 | 123 | elif zscore < -1.0 and (not context.currently_long_the_spread): 124 | # Update target weights to long the spread 125 | target_weights[cl_contract] = 0.5 126 | target_weights[rb_contract] = -0.5 127 | 128 | context.currently_long_the_spread = True 129 | context.currently_short_the_spread = False 130 | 131 | elif zscore > 1.0 and (not context.currently_short_the_spread): 132 | # Update target weights to short the spread 133 | target_weights[cl_contract] = -0.5 134 | target_weights[rb_contract] = 0.5 135 | 136 | context.currently_long_the_spread = False 137 | context.currently_short_the_spread = True 138 | 139 | return target_weights 140 | 141 | def record_price(context, data): 142 | 143 | # Get current price of primary crude oil and gasoline contracts. 144 | crude_oil_price = data.current(context.crude_oil, 'price') 145 | gasoline_price = data.current(context.gasoline, 'price') 146 | 147 | # Adjust price of gasoline (42x) so that both futures have same scale. 148 | record(Crude_Oil=crude_oil_price, Gasoline=gasoline_price*42) 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 | --------------------------------------------------------------------------------