├── borrow_fees_alpha ├── __init__.py ├── Introduction.ipynb ├── avoid-high-borrow.py ├── short-high-borrow.py ├── Part6-Zipline-Strategy-Code.ipynb ├── Part1-Data-Collection.ipynb ├── Part4-Moonshot-Strategy-Code.ipynb └── Part2-EDA.ipynb ├── .qrignore ├── README.md └── LICENSE.txt /borrow_fees_alpha/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.qrignore: -------------------------------------------------------------------------------- 1 | README.md 2 | LICENSE.txt 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # borrow-fees-alpha 2 | 3 | Introduction to QuantRocket's borrow fees dataset. Uses Alphalens to analyze borrow fees as an alpha source and uses Moonshot and Zipline to demonstrate ways to incorporate borrow fees into long or short strategies. 4 | 5 | ## Clone in QuantRocket 6 | 7 | CLI: 8 | 9 | ```shell 10 | quantrocket codeload clone 'borrow-fees-alpha' 11 | ``` 12 | 13 | Python: 14 | 15 | ```python 16 | from quantrocket.codeload import clone 17 | clone("borrow-fees-alpha") 18 | ``` 19 | 20 | ## Browse in GitHub 21 | 22 | Start here: [borrow_fees_alpha/Introduction.ipynb](borrow_fees_alpha/Introduction.ipynb) 23 | 24 | *** 25 | 26 | Find more code in QuantRocket's [Code Library](https://www.quantrocket.com/code/) 27 | -------------------------------------------------------------------------------- /borrow_fees_alpha/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 | "# Borrow Fees as Alpha Factor\n", 16 | "\n", 17 | "This tutorial provides an overview of QuantRocket's borrow fees dataset. Borrow fees can be used to model the costs of short selling or as a source of alternative alpha.\n", 18 | "\n", 19 | "The borrow fees dataset is included with a paid software license. Data are sourced from Interactive Brokers, but an Interactive Brokers account is not required to access the data.\n", 20 | " \n", 21 | "**Data collection**\n", 22 | "\n", 23 | "* Part 1: [Data Collection](Part1-Data-Collection.ipynb)\n", 24 | "\n", 25 | "**Research: Borrow Fees as Alpha Factor**\n", 26 | "\n", 27 | "*Explore whether borrow fees predict forward returns*\n", 28 | "\n", 29 | "* Part 2: [Exploratory Data Analysis](Part2-EDA.ipynb)\n", 30 | "* Part 3: [Alphalens Analysis](Part3-Alphalens-Borrow-Fees.ipynb)\n", 31 | "\n", 32 | "**Short Strategy (Moonshot)**\n", 33 | "\n", 34 | "*Backtest a Moonshot strategy that short stocks with high borrow fees*\n", 35 | "\n", 36 | "* Part 4: [Moonshot Strategy Code](Part4-Moonshot-Strategy-Code.ipynb)\n", 37 | "* Part 5: [Moonshot Backtest](Part5-Moonshot-Backtest.ipynb)\n", 38 | "\n", 39 | "**Long Strategy (Zipline)**\n", 40 | "\n", 41 | "*Backtest a Zipline strategy that excludes stocks with high borrow fees from a long-only portfolio*\n", 42 | "\n", 43 | "* Part 6: [Zipline Strategy Code](Part6-Zipline-Strategy-Code.ipynb)\n", 44 | "* Part 7: [Zipline Parameter Scan](Part7-Zipline-Parameter-Scan.ipynb)" 45 | ] 46 | } 47 | ], 48 | "metadata": { 49 | "kernelspec": { 50 | "display_name": "Python 3.11", 51 | "language": "python", 52 | "name": "python3" 53 | }, 54 | "language_info": { 55 | "codemirror_mode": { 56 | "name": "ipython", 57 | "version": 3 58 | }, 59 | "file_extension": ".py", 60 | "mimetype": "text/x-python", 61 | "name": "python", 62 | "nbconvert_exporter": "python", 63 | "pygments_lexer": "ipython3", 64 | "version": "3.11.0" 65 | } 66 | }, 67 | "nbformat": 4, 68 | "nbformat_minor": 4 69 | } 70 | -------------------------------------------------------------------------------- /borrow_fees_alpha/avoid-high-borrow.py: -------------------------------------------------------------------------------- 1 | # Copyright 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 zipline.api as algo 16 | from zipline.pipeline import Pipeline, ibkr, master 17 | from zipline.pipeline.factors import AverageDollarVolume 18 | from zipline.finance.execution import MarketOrder 19 | 20 | BUNDLE = "usstock-1d-bundle" 21 | MAX_BORROW_FEE = 0.3 22 | 23 | def initialize(context: algo.Context): 24 | """ 25 | Called once at the start of a backtest, and once per day in 26 | live trading. 27 | """ 28 | # Attach the pipeline to the algo 29 | algo.attach_pipeline(make_pipeline(), 'pipeline') 30 | 31 | # Rebalance monthly 32 | algo.schedule_function( 33 | rebalance, 34 | algo.date_rules.month_start(), 35 | ) 36 | 37 | def make_pipeline(): 38 | """ 39 | Create a pipeline that filters by dollar volume and borrow fee. 40 | """ 41 | # limit initial universe to common stocks 42 | universe = master.SecuritiesMaster.usstock_SecurityType2.latest.eq("Common Stock") 43 | 44 | screen = AverageDollarVolume(window_length=90).percentile_between(50, 75) 45 | 46 | if MAX_BORROW_FEE: 47 | screen &= (ibkr.BorrowFees.FeeRate.latest <= MAX_BORROW_FEE) 48 | 49 | pipeline = Pipeline( 50 | initial_universe=universe, 51 | screen=screen 52 | ) 53 | return pipeline 54 | 55 | def rebalance(context: algo.Context, data: algo.BarData): 56 | """ 57 | Execute orders according to our schedule_function() timing. 58 | """ 59 | desired_stocks = algo.pipeline_output('pipeline').index 60 | 61 | positions = context.portfolio.positions 62 | 63 | # Exit positions we no longer want to hold 64 | for asset, position in positions.items(): 65 | if asset not in desired_stocks and data.can_trade(asset): 66 | algo.order_target_value(asset, 0, style=MarketOrder()) 67 | 68 | # Enter long positions 69 | for asset in desired_stocks: 70 | 71 | # allocate 1/Nth of capital per asset 72 | algo.order_target_percent(asset, 1/len(desired_stocks), style=MarketOrder()) 73 | -------------------------------------------------------------------------------- /borrow_fees_alpha/short-high-borrow.py: -------------------------------------------------------------------------------- 1 | # Copyright 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 moonshot import Moonshot 17 | from moonshot.slippage.borrowfee import IBKRBorrowFees 18 | from quantrocket.fundamental import get_ibkr_borrow_fees_reindexed_like 19 | from quantrocket.master import get_securities_reindexed_like 20 | 21 | class ShortHighBorrow(Moonshot): 22 | """ 23 | Strategy that shorts stocks with the highest borrow fees. 24 | """ 25 | 26 | CODE = "short-high-borrow" 27 | DB = "usstock-1d-bundle" 28 | DB_FIELDS = ["Open", "Close", "Volume"] 29 | BORROW_FEE_TOP_N_PCT = 10 30 | DOLLAR_VOLUME_TOP_N_PCT = 75 31 | SLIPPAGE_CLASSES = IBKRBorrowFees 32 | 33 | def prices_to_signals(self, prices: pd.DataFrame): 34 | closes = prices.loc["Close"] 35 | volumes = prices.loc["Volume"] 36 | 37 | # limit to common stocks... 38 | sec_types = get_securities_reindexed_like(closes, "usstock_SecurityType2").loc["usstock_SecurityType2"] 39 | are_common_stocks = sec_types == "Common Stock" 40 | 41 | # ...in the top 75% by dollar volume 42 | avg_dollar_volumes = (closes * volumes).rolling(30).mean() 43 | dollar_volume_pct_ranks = avg_dollar_volumes.where(are_common_stocks).rank(axis=1, ascending=False, pct=True) 44 | have_adequate_dollar_volumes = dollar_volume_pct_ranks <= (self.DOLLAR_VOLUME_TOP_N_PCT / 100) 45 | 46 | # rank by borrow fee and short the 10% with the highest fees 47 | borrow_fees = get_ibkr_borrow_fees_reindexed_like(closes) 48 | borrow_fee_ranks = borrow_fees.where(have_adequate_dollar_volumes).rank(axis=1, ascending=False, pct=True) 49 | short_signals = borrow_fee_ranks <= (self.BORROW_FEE_TOP_N_PCT / 100) 50 | 51 | return -short_signals.astype(int) 52 | 53 | def signals_to_target_weights(self, signals: pd.DataFrame, prices: pd.DataFrame): 54 | weights = self.allocate_equal_weights(signals) 55 | return weights 56 | 57 | def target_weights_to_positions(self, weights: pd.DataFrame, prices: pd.DataFrame): 58 | # Enter the position the day after the signal 59 | return weights.shift() 60 | 61 | def positions_to_gross_returns(self, positions: pd.DataFrame, prices: pd.DataFrame): 62 | # We'll enter on the open, so our return is today's open to 63 | # tomorrow's open 64 | opens = prices.loc["Open"] 65 | # The return is the security's percent change over the period, 66 | # multiplied by the position. 67 | gross_returns = opens.pct_change() * positions.shift() 68 | return gross_returns 69 | -------------------------------------------------------------------------------- /borrow_fees_alpha/Part6-Zipline-Strategy-Code.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 | "[Borrow Fees Alpha](Introduction.ipynb) › Part 6: Zipline Code\n", 17 | "***" 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "metadata": {}, 23 | "source": [ 24 | "# Zipline Strategy Code" 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "metadata": {}, 30 | "source": [ 31 | "Since high borrow fee stocks tend to decline but the high borrow fees destroy the profitability of shorting them, perhaps a more appealing way to use borrow fee data is to exclude stocks with high borrow fees from long strategies. Next, we use Zipline to test this approach." 32 | ] 33 | }, 34 | { 35 | "cell_type": "markdown", 36 | "metadata": {}, 37 | "source": [ 38 | "## Install strategy file\n", 39 | "\n", 40 | "The strategy is implemented in [avoid-high-borrow.py](avoid-high-borrow.py).\n", 41 | "\n", 42 | "Execute the following cell to move the strategy file to the `/codeload/zipline` directory:" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": 1, 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "# make directory if doesn't exist\n", 52 | "!mkdir -p /codeload/zipline\n", 53 | "\n", 54 | "!mv avoid-high-borrow.py /codeload/zipline/" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "metadata": {}, 60 | "source": [ 61 | "## Strategy Highlights\n", 62 | "\n", 63 | "Using similar code as the Alphalens analysis earlier, the Zipline strategy creates a Pipeline of midcap stocks (defined as stocks in the 50th-75th percentile by dollar volume) that excludes stocks with borrow fees above 0.3%: \n", 64 | "\n", 65 | "```python\n", 66 | "\n", 67 | "MAX_BORROW_FEE = 0.3\n", 68 | "\n", 69 | "def make_pipeline():\n", 70 | " \"\"\"\n", 71 | " Create a pipeline that filters by dollar volume and borrow fee.\n", 72 | " \"\"\"\n", 73 | "\n", 74 | " # limit initial universe to common stocks\n", 75 | " universe = master.SecuritiesMaster.usstock_SecurityType2.latest.eq(\"Common Stock\")\n", 76 | "\n", 77 | " screen = AverageDollarVolume(window_length=90).percentile_between(50, 75)\n", 78 | " \n", 79 | " if MAX_BORROW_FEE:\n", 80 | " screen &= (ibkr.BorrowFees.FeeRate.latest <= MAX_BORROW_FEE)\n", 81 | " \n", 82 | " pipeline = Pipeline(\n", 83 | " initial_universe=universe,\n", 84 | " screen=screen\n", 85 | " )\n", 86 | " ...\n", 87 | "```\n", 88 | "\n", 89 | "The results of the Pipeline screen are purchased in an equal-weighted, long-only portfolio and rebalanced monthly. " 90 | ] 91 | }, 92 | { 93 | "cell_type": "markdown", 94 | "metadata": {}, 95 | "source": [ 96 | "***\n", 97 | "\n", 98 | "## *Next Up*\n", 99 | "\n", 100 | "Part 7: [Zipline Parameter Scan](Part7-Zipline-Parameter-Scan.ipynb)" 101 | ] 102 | } 103 | ], 104 | "metadata": { 105 | "kernelspec": { 106 | "display_name": "Python 3.11", 107 | "language": "python", 108 | "name": "python3" 109 | }, 110 | "language_info": { 111 | "codemirror_mode": { 112 | "name": "ipython", 113 | "version": 3 114 | }, 115 | "file_extension": ".py", 116 | "mimetype": "text/x-python", 117 | "name": "python", 118 | "nbconvert_exporter": "python", 119 | "pygments_lexer": "ipython3", 120 | "version": "3.11.0" 121 | } 122 | }, 123 | "nbformat": 4, 124 | "nbformat_minor": 4 125 | } 126 | -------------------------------------------------------------------------------- /borrow_fees_alpha/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 | "[Borrow Fees Alpha](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 | "\n", 27 | "## Collect US Stock Daily Bundle\n", 28 | "\n", 29 | "This tutorial uses the US Stock daily bundle. First create the bundle:" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": 1, 35 | "metadata": {}, 36 | "outputs": [ 37 | { 38 | "data": { 39 | "text/plain": [ 40 | "{'status': 'success', 'msg': 'successfully created usstock-1d-bundle bundle'}" 41 | ] 42 | }, 43 | "execution_count": 1, 44 | "metadata": {}, 45 | "output_type": "execute_result" 46 | } 47 | ], 48 | "source": [ 49 | "from quantrocket.zipline import create_usstock_bundle\n", 50 | "create_usstock_bundle(\"usstock-1d-bundle\", data_frequency=\"daily\")" 51 | ] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "metadata": {}, 56 | "source": [ 57 | "Then ingest the data:" 58 | ] 59 | }, 60 | { 61 | "cell_type": "code", 62 | "execution_count": 2, 63 | "metadata": {}, 64 | "outputs": [ 65 | { 66 | "data": { 67 | "text/plain": [ 68 | "{'status': 'the data will be ingested asynchronously'}" 69 | ] 70 | }, 71 | "execution_count": 2, 72 | "metadata": {}, 73 | "output_type": "execute_result" 74 | } 75 | ], 76 | "source": [ 77 | "from quantrocket.zipline import ingest_bundle\n", 78 | "ingest_bundle(\"usstock-1d-bundle\")" 79 | ] 80 | }, 81 | { 82 | "cell_type": "markdown", 83 | "metadata": {}, 84 | "source": [ 85 | "Use flightlog to monitor the progress:\n", 86 | "\n", 87 | "```\n", 88 | "quantrocket.zipline: INFO [usstock-1d-bundle] Ingesting daily bars for usstock-1d-bundle bundle\n", 89 | "quantrocket.zipline: INFO [usstock-1d-bundle] Ingesting adjustments for usstock-1d-bundle bundle\n", 90 | "quantrocket.zipline: INFO [usstock-1d-bundle] Ingesting assets for usstock-1d-bundle bundle\n", 91 | "quantrocket.zipline: INFO [usstock-1d-bundle] Completed ingesting data for 24749 securities in usstock-1d-bundle bundle\n", 92 | "```" 93 | ] 94 | }, 95 | { 96 | "cell_type": "markdown", 97 | "metadata": {}, 98 | "source": [ 99 | "## Collect Borrow Fees\n", 100 | "\n", 101 | "Next, collect borrow fees, which are organized by country:" 102 | ] 103 | }, 104 | { 105 | "cell_type": "code", 106 | "execution_count": 3, 107 | "metadata": {}, 108 | "outputs": [ 109 | { 110 | "data": { 111 | "text/plain": [ 112 | "{'status': 'the borrow fees data will be collected asynchronously'}" 113 | ] 114 | }, 115 | "execution_count": 3, 116 | "metadata": {}, 117 | "output_type": "execute_result" 118 | } 119 | ], 120 | "source": [ 121 | "from quantrocket.fundamental import collect_ibkr_borrow_fees\n", 122 | "collect_ibkr_borrow_fees(countries=\"usa\")" 123 | ] 124 | }, 125 | { 126 | "cell_type": "markdown", 127 | "metadata": {}, 128 | "source": [ 129 | "Use flightlog to monitor for completion:\n", 130 | "\n", 131 | "```\n", 132 | "quantrocket.fundamental: INFO Collecting ibkr usa borrow fees data from 2024-05-01 to present\n", 133 | "quantrocket.fundamental: INFO Saved 2104318 total ibkr borrow fees records to quantrocket.v2.fundamental.ibkr.stockloan.fees.sqlite\n", 134 | "```" 135 | ] 136 | }, 137 | { 138 | "cell_type": "markdown", 139 | "metadata": {}, 140 | "source": [ 141 | "***\n", 142 | "\n", 143 | "## *Next Up*\n", 144 | "\n", 145 | "Part 2: [Exploratory Data Analysis](Part2-EDA.ipynb)" 146 | ] 147 | } 148 | ], 149 | "metadata": { 150 | "kernelspec": { 151 | "display_name": "Python 3.11", 152 | "language": "python", 153 | "name": "python3" 154 | }, 155 | "language_info": { 156 | "codemirror_mode": { 157 | "name": "ipython", 158 | "version": 3 159 | }, 160 | "file_extension": ".py", 161 | "mimetype": "text/x-python", 162 | "name": "python", 163 | "nbconvert_exporter": "python", 164 | "pygments_lexer": "ipython3", 165 | "version": "3.11.0" 166 | } 167 | }, 168 | "nbformat": 4, 169 | "nbformat_minor": 4 170 | } 171 | -------------------------------------------------------------------------------- /borrow_fees_alpha/Part4-Moonshot-Strategy-Code.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 | "[Borrow Fees Alpha](Introduction.ipynb) › Part 4: Moonshot Code\n", 17 | "***" 18 | ] 19 | }, 20 | { 21 | "cell_type": "markdown", 22 | "metadata": {}, 23 | "source": [ 24 | "# Moonshot Strategy Code" 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "metadata": {}, 30 | "source": [ 31 | "The previous notebook revealed that stocks with high borrow fees tend to decline. On the one hand, this tendency makes such stocks attractive to short. On the other hand, their high borrow fees make them unattractive to short. In the next two notebooks, we pit these competing forces against each other by using Moonshot to backtest a strategy that shorts the top decile of stocks by borrow fee, while also incurring the borrowing costs of those short positions. " 32 | ] 33 | }, 34 | { 35 | "cell_type": "markdown", 36 | "metadata": {}, 37 | "source": [ 38 | "## Install strategy file\n", 39 | "\n", 40 | "The strategy is implemented in [short-high-borrow.py](short-high-borrow.py).\n", 41 | "\n", 42 | "Execute the following cell to move the strategy file to the `/codeload/moonshot` directory:" 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": 1, 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "# make directory if doesn't exist\n", 52 | "!mkdir -p /codeload/moonshot\n", 53 | "\n", 54 | "!mv short-high-borrow.py /codeload/moonshot/" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "metadata": {}, 60 | "source": [ 61 | "## Strategy Highlights\n", 62 | "\n", 63 | "The `prices_to_signals` method of the Moonshot strategy replicates much of the logic from our Pipeline. \n", 64 | "\n", 65 | "* Near the end of the `prices_to_signals` method, we use `get_ibkr_borrow_fees_reindexed_like(...)` to pull borrow fees into the strategy. We then use `rank(axis=1...)` to rank stocks daily by borrow fee, then select the top decile.\n", 66 | "* Before that, we limit the universe to common stocks in the top 75% by dollar volume. This is done by creating two boolean DataFrames (`are_common_stocks` and `have_adequate_dollar_volumes`). These DataFrames are passed to Pandas' `where()` method before ranking (`are_common_stocks` is applied before ranking by dollar volume, and `have_adequate_dollar_volumes` is applied before ranking by borrow fees). This approach of using `where()`, which is typical in Moonshot, sets the dollar volumes or borrow fees, respectively, to `NaN` for stocks that don't belong in the universe and thereby excludes such stocks from the ranking, as `rank(...)` ignores `NaN`s. \n", 67 | "\n", 68 | "```python\n", 69 | "\n", 70 | "from quantrocket.fundamental import get_ibkr_borrow_fees_reindexed_like\n", 71 | "from quantrocket.master import get_securities_reindexed_like\n", 72 | "...\n", 73 | "\n", 74 | "class ShortHighBorrow(Moonshot):\n", 75 | "\n", 76 | " ...\n", 77 | "\n", 78 | " def prices_to_signals(self, prices: pd.DataFrame):\n", 79 | " closes = prices.loc[\"Close\"]\n", 80 | " volumes = prices.loc[\"Volume\"]\n", 81 | "\n", 82 | " # limit to common stocks...\n", 83 | " sec_types = get_securities_reindexed_like(closes, \"usstock_SecurityType2\").loc[\"usstock_SecurityType2\"]\n", 84 | " are_common_stocks = sec_types == \"Common Stock\"\n", 85 | "\n", 86 | " # ...in the top 75% by dollar volume\n", 87 | " avg_dollar_volumes = (closes * volumes).rolling(30).mean()\n", 88 | " dollar_volume_pct_ranks = avg_dollar_volumes.where(are_common_stocks).rank(axis=1, ascending=False, pct=True)\n", 89 | " have_adequate_dollar_volumes = dollar_volume_pct_ranks <= 0.75\n", 90 | "\n", 91 | " # rank by borrow fee and short the 10% with the highest fees\n", 92 | " borrow_fees = get_ibkr_borrow_fees_reindexed_like(closes)\n", 93 | " borrow_fee_ranks = borrow_fees.where(have_adequate_dollar_volumes).rank(axis=1, ascending=False, pct=True)\n", 94 | " short_signals = borrow_fee_ranks <= 0.10\n", 95 | " \n", 96 | " return -short_signals.astype(int)\n", 97 | "```\n", 98 | "\n", 99 | "Modeling borrowing costs for short positions is simple in Moonshot. Import the `IBKRBorrowFees` slippage class and assign it to the `SLIPPAGE_CLASSES` attribute of the Moonshot strategy:\n", 100 | "\n", 101 | "```python\n", 102 | "from moonshot.slippage.borrowfee import IBKRBorrowFees\n", 103 | "\n", 104 | "class ShortHighBorrow(Moonshot):\n", 105 | "\n", 106 | " ...\n", 107 | " SLIPPAGE_CLASSES = IBKRBorrowFees\n", 108 | "```\n" 109 | ] 110 | }, 111 | { 112 | "cell_type": "markdown", 113 | "metadata": {}, 114 | "source": [ 115 | "***\n", 116 | "\n", 117 | "## *Next Up*\n", 118 | "\n", 119 | "Part 5: [Moonshot Backtest](Part5-Moonshot-Backtest.ipynb)" 120 | ] 121 | } 122 | ], 123 | "metadata": { 124 | "kernelspec": { 125 | "display_name": "Python 3.11", 126 | "language": "python", 127 | "name": "python3" 128 | }, 129 | "language_info": { 130 | "codemirror_mode": { 131 | "name": "ipython", 132 | "version": 3 133 | }, 134 | "file_extension": ".py", 135 | "mimetype": "text/x-python", 136 | "name": "python", 137 | "nbconvert_exporter": "python", 138 | "pygments_lexer": "ipython3", 139 | "version": "3.11.0" 140 | } 141 | }, 142 | "nbformat": 4, 143 | "nbformat_minor": 4 144 | } 145 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /borrow_fees_alpha/Part2-EDA.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "740c90f9-14cb-428a-8630-4e0339e0a74c", 6 | "metadata": {}, 7 | "source": [ 8 | "\"QuantRocket
\n", 9 | "Disclaimer" 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "id": "7476da07-78d4-4928-8131-c50f7a80f9ae", 15 | "metadata": {}, 16 | "source": [ 17 | "***\n", 18 | "[Borrow Fees Alpha](Introduction.ipynb) › Part 2: Exploratory Data Analysis\n", 19 | "***" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "id": "869f3181-bd1f-475d-bb84-24027cf2ac54", 25 | "metadata": {}, 26 | "source": [ 27 | "# Exploratory Data Analysis\n", 28 | "\n", 29 | "With an alternative data source like borrow fees, exploratory data analysis (EDA) is a good first step. In this notebook, we will run a Pipeline to get an overview of the distribution of borrow fees." 30 | ] 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "id": "59efa3a8-e807-4b35-b10f-cc2acb1efcc4", 35 | "metadata": {}, 36 | "source": [ 37 | "The Pipeline has one column, the borrow fee. For this tutorial, we choose to limit our universe to common stocks." 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 1, 43 | "id": "3686fe19-69af-4a45-9ff3-2e131cef11f6", 44 | "metadata": { 45 | "tags": [] 46 | }, 47 | "outputs": [], 48 | "source": [ 49 | "from zipline.pipeline import Pipeline, ibkr, master\n", 50 | "\n", 51 | "universe = master.SecuritiesMaster.usstock_SecurityType2.latest.eq(\"Common Stock\")\n", 52 | "\n", 53 | "pipeline = Pipeline(\n", 54 | " columns={\n", 55 | " \"borrow_fee\": ibkr.BorrowFees.FeeRate.latest,\n", 56 | " },\n", 57 | " initial_universe=universe\n", 58 | ")" 59 | ] 60 | }, 61 | { 62 | "cell_type": "markdown", 63 | "id": "59357694-ca10-44e7-aa20-c23b40066966", 64 | "metadata": {}, 65 | "source": [ 66 | "Next, we run the pipeline for a single date." 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": 2, 72 | "id": "4e6a281e-c387-4843-baef-196131dedbc4", 73 | "metadata": { 74 | "tags": [] 75 | }, 76 | "outputs": [], 77 | "source": [ 78 | "from zipline.research import run_pipeline, use_bundle\n", 79 | "\n", 80 | "use_bundle(\"usstock-1d-bundle\")\n", 81 | "\n", 82 | "results = run_pipeline(pipeline, start_date=\"2024-01-05\", end_date=\"2024-01-05\")" 83 | ] 84 | }, 85 | { 86 | "cell_type": "markdown", 87 | "id": "f95ffd00-a912-4839-8d9b-ef8c97e80ce9", 88 | "metadata": {}, 89 | "source": [ 90 | "Let's peek at the results. Borrow fees are quoted as the annualized interest rate that is charged to the borrower of the shares. For example, 0.25 corresponds to an annualized interest rate of 0.25%; 5.7 corresponds to an annualized interest rate of 5.7%." 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": 3, 96 | "id": "09ab8c07-74a3-4b8d-b648-8ee72c799704", 97 | "metadata": {}, 98 | "outputs": [ 99 | { 100 | "data": { 101 | "text/html": [ 102 | "
\n", 103 | "\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 | "
borrow_fee
dateasset
2024-01-05Equity(FIBBG000C2V3D6 [A])0.2918
Equity(FIBBG00B3T3HD3 [AA])0.2843
Equity(FIBBG00VR487K7 [ORGN])0.5998
Equity(FIBBG005P7Q881 [AAL])0.2526
Equity(FIBBG003PNL136 [AAMC])5.7020
\n", 153 | "
" 154 | ], 155 | "text/plain": [ 156 | " borrow_fee\n", 157 | "date asset \n", 158 | "2024-01-05 Equity(FIBBG000C2V3D6 [A]) 0.2918\n", 159 | " Equity(FIBBG00B3T3HD3 [AA]) 0.2843\n", 160 | " Equity(FIBBG00VR487K7 [ORGN]) 0.5998\n", 161 | " Equity(FIBBG005P7Q881 [AAL]) 0.2526\n", 162 | " Equity(FIBBG003PNL136 [AAMC]) 5.7020" 163 | ] 164 | }, 165 | "execution_count": 3, 166 | "metadata": {}, 167 | "output_type": "execute_result" 168 | } 169 | ], 170 | "source": [ 171 | "results.head()" 172 | ] 173 | }, 174 | { 175 | "cell_type": "markdown", 176 | "id": "f4af2f86-0007-43f0-8e85-e8fc271ad8c3", 177 | "metadata": {}, 178 | "source": [ 179 | "Next we use pandas' `describe()` method to look at the distribution. Most borrow fees are low: the minimum borrow fee is 0.25%, and the median is below 1%. However, at the extreme end of the distribution, borrow fees can be very high: the maximum on this date is 860%. " 180 | ] 181 | }, 182 | { 183 | "cell_type": "code", 184 | "execution_count": 4, 185 | "id": "d0376969-67aa-4818-8016-71922b08d739", 186 | "metadata": { 187 | "tags": [] 188 | }, 189 | "outputs": [ 190 | { 191 | "data": { 192 | "text/html": [ 193 | "
\n", 194 | "\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 | "
borrow_fee
count4939.000000
mean17.077866
std54.938754
min0.250000
25%0.398650
50%0.704100
75%7.842400
max860.538900
\n", 249 | "
" 250 | ], 251 | "text/plain": [ 252 | " borrow_fee\n", 253 | "count 4939.000000\n", 254 | "mean 17.077866\n", 255 | "std 54.938754\n", 256 | "min 0.250000\n", 257 | "25% 0.398650\n", 258 | "50% 0.704100\n", 259 | "75% 7.842400\n", 260 | "max 860.538900" 261 | ] 262 | }, 263 | "execution_count": 4, 264 | "metadata": {}, 265 | "output_type": "execute_result" 266 | } 267 | ], 268 | "source": [ 269 | "results.describe()" 270 | ] 271 | }, 272 | { 273 | "cell_type": "markdown", 274 | "id": "2e307ee9-c99e-436d-b40c-3bf60b843785", 275 | "metadata": {}, 276 | "source": [ 277 | "Let's view a histogram of the distribution. Because borrow fees have an extremely large range, we clip high borrow fees at 10 to make the histogram easier to view. The histogram reveals that most stocks cluster at the low end of the distribution (easy to borrow with low borrow fees), but a sizable number of stocks have borrow fees in excess of 10% annualized." 278 | ] 279 | }, 280 | { 281 | "cell_type": "code", 282 | "execution_count": 5, 283 | "id": "ec5e9129-be6b-4f35-8431-22a2997ca2c4", 284 | "metadata": {}, 285 | "outputs": [ 286 | { 287 | "data": { 288 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAA8EAAAFuCAYAAAChnRoSAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8pXeV/AAAACXBIWXMAA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s6ZOnZqOjo6tbhvuHdRa7wGGsxUrVmTixIlpaWlJkrS0tGTChAlZsWJFxo0bV+fpIBkaGsqdd96ZadOm1XsUyA033JBPfOITOfjgg+s9Cmzx8ssvZ8yYMbn55pvz05/+NPvss09mz56dqVOn1ns0Cq6pqSnXX399vvzlL2fUqFHZuHFjbr/99nqPBUmGfwf5URK8h1155ZUZNWpUzjzzzHqPQsH9+7//e371q1+lp6en3qPAVjZv3pyXX345H/jAB/Ltb387l156ac4///y89tpr9R6Ngtu8eXNuv/32LFy4MN///vdz66235qKLLsrGjRvrPRoMeyJ4N3R0dGTlypUplUpJklKplFWrVr3jcgGoh76+vrz44ou5/vrrXTpF3T3yyCN5/vnnM3369EybNi2//e1vc9ZZZ+Xhhx+u92gU3IEHHpjW1tYtl/Qdc8wxGTt2bJYvX17nySi6J598MqtWrcqUKVOSJFOmTMnIkSOzbNmyOk8Gw7+D/Mt4N4wfPz6dnZ3p7+9PkvT396ezs3NYXALAe9uCBQvy+OOP55ZbbklbW1u9x4F84QtfyMMPP5wHH3wwDz74YA444IB84xvfyEknnVTv0Si4cePG5YQTTsiPf/zjJG+/2ung4GDe97731Xkyiu6AAw7Ib3/72zz//PNJkmXLlmXNmjU55JBD6jwZDP8OaiqXy+V6DzGcLVu2LHPnzs369eszevTo9PX15fDDD6/3WBTYs88+m+7u7hx66KHZe++9kyQHHXRQbrnlljpPBv+/adOm5bbbbsv73//+eo8Cefnll3PZZZfl1VdfTWtray688MJ85CMfqfdYkLvvvjt33HHHlhdtu+CCC3LKKafUeSqK5qqrrsrSpUuzZs2ajB07NmPGjMm99947rDtIBAMAAFAYLocGAACgMEQwAAAAhSGCAQAAKAwRDAAAQGGIYAAAAApDBAMAAFAYIhgAAIDCEMEAAAAUxv8LchIJrZNUSzMAAAAASUVORK5CYII=", 289 | "text/plain": [ 290 | "
" 291 | ] 292 | }, 293 | "metadata": {}, 294 | "output_type": "display_data" 295 | } 296 | ], 297 | "source": [ 298 | "results.loc[results.borrow_fee > 10, \"borrow_fee\"] = 10\n", 299 | "results.plot.hist(bins=40);" 300 | ] 301 | }, 302 | { 303 | "cell_type": "markdown", 304 | "id": "6d66e82f-f0de-47c1-966c-4979d99bcd07", 305 | "metadata": {}, 306 | "source": [ 307 | "***\n", 308 | "\n", 309 | "## *Next Up*\n", 310 | "\n", 311 | "Part 3: [Alphalens Analysis](Part3-Alphalens-Borrow-Fees.ipynb)" 312 | ] 313 | } 314 | ], 315 | "metadata": { 316 | "kernelspec": { 317 | "display_name": "Python 3.11", 318 | "language": "python", 319 | "name": "python3" 320 | }, 321 | "language_info": { 322 | "codemirror_mode": { 323 | "name": "ipython", 324 | "version": 3 325 | }, 326 | "file_extension": ".py", 327 | "mimetype": "text/x-python", 328 | "name": "python", 329 | "nbconvert_exporter": "python", 330 | "pygments_lexer": "ipython3", 331 | "version": "3.11.0" 332 | } 333 | }, 334 | "nbformat": 4, 335 | "nbformat_minor": 5 336 | } 337 | --------------------------------------------------------------------------------