Installation and Deployment
Installation Guides
For installation instructions, please see the Installation tutorial for your platform.
Architecture
QuantRocket utilizes a Docker-based microservice architecture. Users who are unfamiliar with microservices or new to Docker may find it helpful to read the overview of QuantRocket's architecture.
License key
Activation
To activate QuantRocket, look up your license key on your account page and enter it in your deployment:
$ quantrocket license set 'XXXXXXXXXXXXXXXX'
>>> from quantrocket.license import set_license
>>> set_license("XXXXXXXXXXXXXXXX")
$ curl -X PUT 'http://houston/license-service/license/XXXXXXXXXXXXXXXX'
View your license
You can view the details of the currently installed license:
$ quantrocket license get
licensekey: XXXX....XXXX
software_license:
account:
account_limit: XXXXXX USD
concurrent_install_limit: XX
license_type: Professional
user_limit: XX
>>> from quantrocket.license import get_license_profile
>>> get_license_profile()
{'licensekey': 'XXXX....XXXX',
'software_license': {'license_type': 'Professional',
'user_limit': XX,
'concurrent_install_limit': XX,
'account': {'account_limit': 'XXXXXX USD'}}}
$ curl -X GET 'http://houston/license-service/license'
{"licensekey": "XXXX....XXXX", "software_license": {"license_type": "Professional", "user_limit": XX, "concurrent_install_limit": XX, "account": {"account_limit": "XXXXXX USD"}}}
The license service will re-query your subscriptions and permissions every 10 minutes. If you make a change to your billing plan and want your deployment to see the change immediately, you can force a refresh:
$ quantrocket license get --force-refresh
>>> from quantrocket.license import get_license_profile
>>> get_license_profile(force_refresh=True)
$ curl -X GET 'http://houston/license-service/license?force_refresh=true'
Account limit validation
The account limit displayed in your license profile output applies to live trading using the blotter and to real-time data. The account limit does not apply to historical data collection, research, or backtesting. For advisor accounts, the account size is the sum of all master and sub-accounts.
Paper trading is not subject to the account limit, however paper trading requires that the live account limit has previously been validated. Thus before paper trading it is first necessary to connect your live account at least once and let the software validate it.
To validate your account limit if you have only connected your paper account:
- Switch to your live account using the instructions for your broker
- Wait approximately 1 minute. The software queries your account balance every minute whenever your broker is connected.
To verify that account validation has occurred, refresh your license profile. It should now display your account balance and whether the balance is under the account limit:
$ quantrocket license get --force-refresh
licensekey: XXXX....XXXX
software_license:
account:
account_balance: 593953.42 USD
account_balance_details:
- Account: U12345
Currency: USD
NetLiquidation: 593953.42 USD
account_balance_under_limit: true
account_limit: XXXXXX USD
concurrent_install_limit: XX
license_type: Professional
user_limit: XX
>>> from quantrocket.license import get_license_profile
>>> get_license_profile(force_refresh=True)
{'licensekey': 'XXXX....XXXX',
'software_license': {'license_type': 'Professional',
'user_limit': XX,
'concurrent_install_limit': XX,
'account': {'account_limit': 'XXXXXX USD',
'account_balance': '593953.42 USD',
'account_balance_under_limit': True,
'account_balance_details': [{'Account': 'U12345',
'Currency': 'USD',
'NetLiquidation': 593953.42}]}}}
$ curl -X GET 'http://houston/license-service/license?force_refresh=true'
{"licensekey": "XXXX....XXXX", "software_license": {"license_type": "Professional", "user_limit": XX, "concurrent_install_limit": XX, "account": {"account_limit": "XXXXXX USD", "account_balance": "593953.42 USD", "account_balance_under_limit": true, "account_balance_details": [{"Account": "U12345", "Currency": "USD", "NetLiquidation": 593953.42}]}}}
If the command output is missing the account_balance
and account_balance_under_limit
keys, this indicates that the account limit has not yet been validated.
Now you can switch back to your paper account and begin paper trading.
User limit vs concurrent install limit
The output of your license profile displays your user limit and your concurrent install limit. User limit indicates the total number of distinct users who are licensed to use the software in any given month. Concurrent install limit indicates the total number of copies of the software that may be installed and running at any given time.
The concurrent install limit is set to (user limit + 1).
Rotate license key
You can rotate your license key at any time from your account page.
Connect from other applications
If you run other applications, you can connect them to your QuantRocket deployment for the purpose of querying data, submitting orders, etc.
Each remote connection to a cloud deployment counts against your plan's concurrent install limit. For example, if you run a single cloud deployment of QuantRocket and connect to it from a single remote application, this is counted as 2 concurrent installs, one for the deployment and one for the remote connection. (Connecting to a local deployment from a separate application running on your local machine does not count against the concurrent install limit.)
To utilize the Python API and/or CLI from outside of QuantRocket, install the client on the application or system you wish to connect from:
$ pip install 'quantrocket-client'
To ensure compatibility, the MAJOR.MINOR version of the client should match the MAJOR.MINOR version of your deployment. For example, if your deployment is version 2.1.x, you can install the latest 2.1.x client:
$ pip install 'quantrocket-client>=2.1,<2.2'
Don't forget to update your client version when you update your deployment version.
Next, set environment variables to tell the client how to connect to your QuantRocket deployment. For a cloud deployment, this means providing the deployment URL and credentials:
$
$ export HOUSTON_URL=https://quantrocket.123capital.com
$ export HOUSTON_USERNAME=myusername
$ export HOUSTON_PASSWORD=mypassword
$
$ [Environment]::SetEnvironmentVariable("HOUSTON_URL", "https://quantrocket.123capital.com", "User")
$ [Environment]::SetEnvironmentVariable("HOUSTON_USERNAME", "myusername", "User")
$ [Environment]::SetEnvironmentVariable("HOUSTON_PASSWORD", "mypassword", "User")
For connecting to a local deployment, only the URL is needed:
$
$ export HOUSTON_URL=http://localhost:1969
$
$ [Environment]::SetEnvironmentVariable("HOUSTON_URL", "http://localhost:1969", "User")
Environment variable syntax varies by operating system. Don't forget to make your environment variables persistent by adding them to .bashrc
(Linux) or .profile
(MacOS) and sourcing it (for example source ~/.bashrc
), or restarting PowerShell (Windows).
Finally, test that it worked:
$ quantrocket houston ping
msg: hello from houston
>>> from quantrocket.houston import ping
>>> ping()
{u'msg': u'hello from houston'}
$ curl -u myusername:mypassword https://quantrocket.123capital.com/ping
{"msg": "hello from houston"}
To connect from applications running languages other than Python, you can skip the client installation and use the HTTP API directly.
Broker and Data Connections
This section outlines how to connect to brokers and third-party data providers.
Because QuantRocket runs on your hardware, third-party credentials and API keys that you enter into the software are secure. They are encrypted at rest and never leave your deployment. They are used solely for connecting directly to the third-party API.
Interactive Brokers
Connecting to Interactive Brokers requires an IBKR Pro account. IBKR Lite accounts do not provide API access and will not work with QuantRocket. To switch from IBKR Lite to IBKR Pro, log in to the Client Portal for your Interactive Brokers account.
IBKR Account Structure
Multiple logins and data concurrency
The structure of your Interactive Brokers (IBKR) account has a bearing on the speed with which you can collect real-time and historical data with QuantRocket. In short, the more IB Gateways you run, the more data you can collect. The basics of account structure and data concurrency are outlined below:
- All interaction with the IBKR servers, including real-time and historical data collection, is routed through IB Gateway, IBKR's slimmed-down version of Trader Workstation.
- IBKR imposes rate limits on the amount of historical and real-time data that can be received through IB Gateway.
- Each IB Gateway is tied to a particular set of login credentials. Each login can be running only one active IB Gateway session at any given time.
- However, an account holder can have multiple logins—at least two logins or possibly more, depending on the account structure. Each login can run its own IB Gateway session. In this way, an account holder can potentially run multiple instances of IB Gateway simultaneously.
- QuantRocket is designed to take advantage of multiple IB Gateways. When running multiple gateways, QuantRocket will spread your market data requests among the connected gateways.
- Since each instance of IB Gateway is rate limited separately by IBKR, the combined data throughput from splitting requests among two IB Gateways is twice that of sending all requests to one IB Gateway.
- Each separate login must separately subscribe to the relevant market data in IBKR Client Portal.
Below are a few common ways to obtain additional logins.
IBKR account structures are complex and vary by subsidiary, local regulations, the person opening the account, etc. The following guidelines are suggestions only and may not be applicable to your situation.
Second user login
Individual account holders can add a second login to their account. This is designed to allow you to use one login for API trading while using the other login to use Trader Workstation for manual trading or account monitoring. However, you can use both logins to collect data with QuantRocket. Note that you can't use the same login to simultaneously run Trader Workstation and collect data with QuantRocket. However, QuantRocket makes it easy to start and stop IB Gateway on a schedule, so the following is an option:
- Login 1 (used for QuantRocket only)
- IB Gateway always running and available for data collection and placing API orders
- Login 2 (used for QuantRocket and Trader Workstation)
- automatically stop IB Gateway daily at 9:30 AM
- Run Trader Workstation during trading session for manual trading/account monitoring
- automatically start IB Gateway daily at 4:00 PM so it can be used for overnight data collection
Advisor/Friends and Family accounts
An advisor account or the similarly structured Friends and Family account offers the possibility to obtain additional logins. Even an individual trader can open a Friends and Family account, in which they serve as their own advisor. The account setup is as follows:
- Master/advisor account: no trading occurs in this account. The account is funded only with enough money to cover market data costs. This yields 1 IB Gateway login.
- Master/advisor second user login: like an individual account, the master account can create a second login, subscribe to market data with this login, and use it for data collection.
- Client account: this is main trading account where the trading funds are deposited. This account receives its own login (for 3 total). By default this account does not having trading permissions, but you can enable client trading permissions via the master account, then subscribe to market data in the client account and begin using the client login to run another instance of IB Gateway. (Note that it's not possible to add a second login for a client account.)
If you have other accounts such as retirement accounts, you can add them as additional client accounts and obtain additional logins.
Paper trading accounts
Each IBKR account holder can enable a paper trading account for simulated trading. You can share market data with your paper account and use the paper account login with QuantRocket to collect data, as well as to paper trade your strategies. You don't need to switch to using your live account until you're ready for live trading (although it's also fine to use your live account login from the start).
Note that, due to restrictions on market data sharing, it's not possible to run IB Gateway using the live account login and corresponding paper account login at the same time. If you try, one of the sessions will disconnect the other session.
IBKR market data permissions
To collect IBKR data using QuantRocket, you must subscribe to the relevant market data in your IBKR account. In IBKR Client Portal, click on Settings > User Settings > Market Data Subscriptions:

Click the edit icon then select and confirm the relevant subscriptions:

Market data for paper accounts
IBKR paper accounts do not directly subscribe to market data. Rather, to access market data using your IBKR paper account, subscribe to the data in your live account and share it with your paper account. Log in to IBKR Client Portal with your live account login and go to Settings > Account Settings > Paper Trading Account:

Then select the option to share your live account's market data with your paper account:

IB Gateway
QuantRocket uses the IBKR API to collect market data from IBKR, submit orders, and track positions and account balances. All communication with IBKR is routed through IB Gateway, a Java application which is a slimmed-down version of Trader Workstation (TWS) intended for API use. You can run one or more IB Gateway services through QuantRocket, where each gateway instance is associated with a different IBKR username and password.
Connect to IBKR
Your credentials are encrypted at rest and never leave your deployment.
IB Gateway runs inside the ibg1
container and connects to IBKR using your IBKR username and password. (If you have multiple IBKR usernames, you can run multiple IB Gateways.) The ibgrouter
container provides an API that allows you to start and stop IB Gateway inside the ibg
container(s).
Secure Login System (Two-Factor Authentication)
Interactive Brokers requires two-factor authentication for most live accounts. Interactive Brokers supports several different methods of two-factor authentication, but to use IB Gateway with QuantRocket you should enroll in mobile authentication, which involves receiving a notification on your mobile device to complete login.
Be sure to read the section about IB Gateway auto-restarts which outlines the need to perform two-factor authentication weekly on Sundays. You will also need to perform two-factor authentication any time you log back in to IB Gateway after having logged out, regardless of the day. You can set up alerts to avoid missing two-factor notifications on your mobile device.
Two-factor authentication is not required for paper accounts. For the convenience of omitting two-factor authentication, and as a general best practice, you can log into a paper account for data collection and only log into a live account when you are ready for live trading.
Enter IBKR login
To connect to your IBKR account, enter your IBKR login into your deployment, as well as the desired trading mode (live or paper). You'll be prompted for your password:
$ quantrocket ibg credentials 'ibg1' --username 'myuser' --paper
Enter IBKR Password:
status: successfully set ibg1 credentials
>>> from quantrocket.ibg import set_credentials
>>> set_credentials("ibg1", username="myuser", trading_mode="paper")
Enter IBKR Password:
{'status': 'successfully set ibg1 credentials'}
$ curl -X PUT 'http://houston/ibg1/credentials' -d 'username=myuser' -d 'password=mypassword' -d 'trading_mode=paper'
{"status": "successfully set ibg1 credentials"}
When setting your credentials, QuantRocket securely stores your credentials inside your deployment so you don't need to enter them again, then starts IB Gateway to verify that your credentials work. Starting IB Gateway takes approximately 30 seconds.
If you are connecting to a live IBKR account that requires second factor authentication, you will see an error message:
$ quantrocket ibg credentials 'ibg1' --username 'myuser' --live
Enter IBKR Password:
msg: Second factor authentication required to complete login, please check your mobile
device for a notification. See http://qrok.it/h/ib2fa for help.
status: error
>>> from quantrocket.ibg import set_credentials
>>> set_credentials("ibg1", username="myuser", trading_mode="live")
Enter IBKR Password:
HTTPError: ('401 Client Error: UNAUTHORIZED for url: http://houston/ibg1/credentials', {'status': 'error', 'msg': 'Second factor authentication required to complete login, please check your mobile device for a notification. See http://qrok.it/h/ib2fa for help.'})
$ curl -X PUT 'http://houston/ibg1/credentials' -d 'username=myuser' -d 'password=mypassword' -d 'trading_mode=live'
{"status": "error", "msg": "Second factor authentication required to complete login, please check your mobile device for a notification. See http://qrok.it/h/ib2fa for help."}
Complete the authentication using your mobile device. If you fail to complete authentication within 3 minutes, QuantRocket will stop and restart IB Gateway, resulting in a new mobile notification. This process will repeat indefinitely until you complete the authentication.
If you encounter errors trying to start IB Gateway, refer to a later section to learn how to
access the IB Gateway GUI for troubleshooting.
Querying your IBKR account balance is a good way to verify your IBKR connection:
$ quantrocket account balance --latest --fields 'NetLiquidation' | csvlook
| Account | Currency | NetLiquidation | LastUpdated |
| --------- | -------- | -------------- | ------------------- |
| DU12345 | USD | 500,000.00 | 2020-02-02 22:57:13 |
>>> from quantrocket.account import download_account_balances
>>> import io
>>> import pandas as pd
>>> f = io.StringIO()
>>> download_account_balances(f, latest=True, fields=["NetLiquidation"])
>>> balances = pd.read_csv(f, parse_dates=["LastUpdated"])
>>> balances.head()
Account Currency NetLiquidation LastUpdated
0 DU12345 USD 500000.0 2020-02-02 22:57:13
$ curl 'http://houston/account/balances.csv?latest=true&fields=NetLiquidation'
Account,Currency,NetLiquidation,LastUpdated
DU12345,USD,500000.0,2020-02-02 22:57:13
Switch between live and paper account
When you sign up for an IBKR paper account, IBKR provides login credentials for the paper account. However, it is also possible to login to the paper account by using your live account credentials and specifying the trading mode as "paper". Thus, technically the paper login credentials are unnecessary.
Using your live login credentials for both live and paper trading allows you to easily switch back and forth. Supposing you originally select the paper trading mode:
$ quantrocket ibg credentials 'ibg1' --username 'myliveuser' --paper
Enter IBKR Password:
status: successfully set ibg1 credentials
>>> from quantrocket.ibg import set_credentials
>>> set_credentials("ibg1", username="myliveuser", trading_mode="paper")
Enter IBKR Password:
{'status': 'successfully set ibg1 credentials'}
$ curl -X PUT 'http://houston/ibg1/credentials' -d 'username=myliveuser' -d 'password=mypassword' -d 'trading_mode=paper'
{"status": "successfully set ibg1 credentials"}
You can later switch to live trading mode without re-entering your credentials:
$ quantrocket ibg credentials 'ibg1' --live
msg: Second factor authentication required to complete login, please check your mobile
device for a notification. See http://qrok.it/h/ib2fa for help.
status: error
>>> set_credentials("ibg1", trading_mode="live")
HTTPError: ('401 Client Error: UNAUTHORIZED for url: http://houston/ibg1/credentials', {'status': 'error', 'msg': 'Second factor authentication required to complete login, please check your mobile device for a notification. See http://qrok.it/h/ib2fa for help.'})
$ curl -X PUT 'http://houston/ibg1/credentials' -d 'trading_mode=live'
{"status": "error", "msg": "Second factor authentication required to complete login, please check your mobile device for a notification. See http://qrok.it/h/ib2fa for help."}
If you forget which mode you're in (or which login you used), you can check:
$ quantrocket ibg credentials 'ibg1'
TRADING_MODE: live
TWSUSERID: myliveuser
>>> from quantrocket.ibg import get_credentials
>>> get_credentials("ibg1")
{'TWSUSERID': 'myliveuser', 'TRADING_MODE': 'live'}
$ curl -X GET 'http://houston/ibg1/credentials'
{"TWSUSERID": "myliveuser", "TRADING_MODE": "live"}
Start/stop IB Gateway
IB Gateway must be running whenever you want to collect market data or place or monitor orders. You can optionally stop IB Gateway when you're not using it. Interactive Brokers limits each unique IBKR login to one IB Gateway or Trader Workstation session at a time. Therefore, if you need to log in to Trader Workstation using the same login credentials you are using with QuantRocket, you must first stop IB Gateway.
To check the current status of your IB Gateway(s):
$ quantrocket ibg status
ibg1: stopped
>>> from quantrocket.ibg import list_gateway_statuses
>>> list_gateway_statuses()
{'ibg1': 'stopped'}
$ curl -X GET 'http://houston/ibgrouter/gateways'
{"ibg1": "stopped"}
You can start IB Gateway, optionally waiting for the startup process (and mobile authentication, if applicable) to complete:
$ quantrocket ibg start --wait
ibg1:
status: running
>>> from quantrocket.ibg import start_gateways
>>> start_gateways(wait=True)
{'ibg1': {'status': 'running'}}
$ curl -X POST 'http://houston/ibgrouter/gateways?wait=True'
{"ibg1": {"status": "running"}}
And later stop it:
$ quantrocket ibg stop --wait
ibg1:
status: stopped
>>> from quantrocket.ibg import stop_gateways
>>> stop_gateways(wait=True)
{'ibg1': {'status': 'stopped'}}
$ curl -X DELETE 'http://houston/ibgrouter/gateways?wait=True'
{"ibg1": {"status": "stopped"}}
IB Gateway Auto-Restart
IB Gateway automatically restarts itself once a day. This behavior is enforced by IB Gateway itself, not QuantRocket, and is designed to keep IB Gateway running smoothly.
The daily restart happens at 11:45 PM New York time. The restart takes about 30 seconds. If historical or fundamental data collection is in progress, the data collection services will detect the interrupted connection and automatically resume when the connection is restored. (If IB Gateway is not running at the time of the restart, no restart is required or occurs.)
If you need the restart to occur at a different time (for example because your strategy may be placing trades at 11:45 PM New York time), you can modify the restart time by opening the IB Gateway GUI and navigating to Configure > Settings > Lock and Exit. Each time you re-deploy QuantRocket or run a software update which creates or re-creates the ibg1
container, you will need to edit the setting again.
Alternatively, to avoid the need to edit the setting each time you re-deploy the ibg1
container, you can add an AUTO_RESTART_TIME
environment variable to your docker-compose.override.yml, which should specify the New York time in HH:MM format when you want the daily restart to occur:
version: '2.4'
services:
ibg1:
environment:
AUTO_RESTART_TIME: '21:00'
Then, re-deploy the ibg1 service:
$ cd /path/to/docker-compose.yml
$ docker compose -p quantrocket up -d ibg1
You can learn more about docker-compose.override.yml
in another section.
Auto-restart with two-factor authentication
For live accounts with two-factor authentication, the Sunday auto-restart will require two-factor authentication. On other days, the auto-restart will automatically log you back in without the need to perform two-factor authentication. Thus, accounts with two-factor authentication can remain logged in all week, with mobile authentication on Sundays.
The restart will happen automatically and you will only need to acknowledge the mobile notification to complete the login; thus you won't need access to QuantRocket itself. If you miss the mobile notification, QuantRocket will stop and restart IB Gateway every 3 minutes to trigger a new notification, until you eventually acknowledge one.
The timing of the daily auto-restart determines what time you will receive two-factor authentication notifications on your mobile device on Sunday. The default time is 11:45 PM New York time. You can adjust this time by setting the AUTO_RESTART_TIME
environment variable as shown above. Ideally, you should choose an auto-restart time that will be convenient for acknowledging two-factor authentication notifications on Sunday, and that won't interrupt any live trading on other days of the week.
Two-Factor Authentication alerts
Two-factor authentication notifications from the IBKR mobile app are typically silent: a banner will appear on your mobile device but no sound will play. This can result in missed notifications if you are not expecting a notification, as may be the case when the weekly auto-restart occurs.
You can use QuantRocket's Papertrail integration to generate a sound when two-factor authentication is required, to decrease the chance of missing a notification. Each time a two-factor notification is sent to your mobile device, a message will be logged to flightlog:
quantrocket.ibg1 WARNING Second factor authentication required to complete login, please check your mobile device for a notification. See http://qrok.it/h/ib2fa for help.
Setting up the Papertrail integration will cause this message to appear in Papertrail as well. Then, you can create an alert in Papertrail that monitors for the phrase "Second factor authentication required" and, when found, sends a notification to one of Papertrail's integrated notification services such as Pushover. Pushover will send its own notification to your device that will play a sound, drawing your attention to the two-factor notification from IBKR.
IB Gateway GUI
Normally you won't need to access the IB Gateway GUI. However, you might need access to troubleshoot a login issue.
To allow access to the IB Gateway GUI, QuantRocket uses NoVNC, which uses the WebSockets protocol to support VNC connections in the browser. To open an IB Gateway GUI connection in your browser, click the "IB Gateway GUI" button located on the JupyterLab Launcher or from the File menu. The IB Gateway GUI will open in a new window (make sure your browser doesn't block the pop-up).

If IB Gateway isn't currently running, the screen will be black.
To quit the VNC session but leave IB Gateway running, simply close your browser tab.
For improved security for cloud deployments, QuantRocket doesn't directly expose any VNC ports to the outside. By proxying VNC connections through houston using NoVNC, such connections are protected by Basic Auth and SSL, just like every other request sent through houston.
Multiple IB Gateways
QuantRocket support running multiple IB Gateways, each associated with a particular IBKR login. Two of the main reasons for running multiple IB Gateways are:
- To trade multiple accounts
- To increase market data concurrency
The default IB Gateway service is called ibg1
. To run multiple IB Gateways, create a file called docker-compose.override.yml
in the same directory as your docker-compose.yml
and add the desired number of additional services as shown below. In this example we are adding two additional IB Gateway services, ibg2
and ibg3
, which inherit from the definition of ibg1
:
version: '2.4'
services:
ibg2:
extends:
file: docker-compose.yml
service: ibg1
ibg3:
extends:
file: docker-compose.yml
service: ibg1
You can learn more about docker-compose.override.yml
in another section.
Then, deploy the new service(s):
$ cd /path/to/docker-compose.yml
$ docker compose -p quantrocket up -d
You can then enter your login for each of the new IB Gateways:
$ quantrocket ibg credentials 'ibg2' --username 'myuser' --paper
Enter IBKR Password:
status: successfully set ibg2 credentials
>>> from quantrocket.ibg import set_credentials
>>> set_credentials("ibg2", username="myuser", trading_mode="paper")
Enter IBKR Password:
{'status': 'successfully set ibg2 credentials'}
$ curl -X PUT 'http://houston/ibg2/credentials' -d 'username=myuser' -d 'password=mypassword' -d 'trading_mode=paper'
{"status": "successfully set ibg2 credentials"}
When starting and stopping gateways, the default behavior is start or stop all gateways. To target specific gateways, use the gateways
parameter:
$ quantrocket ibg start --gateways 'ibg2'
status: the gateways will be started asynchronously
>>> from quantrocket.ibg import start_gateways
>>> start_gateways(gateways=["ibg2"])
{'status': 'the gateways will be started asynchronously'}
$ curl -X POST 'http://houston/ibgrouter/gateways?gateways=ibg2'
{"status": "the gateways will be started asynchronously"}
Market data permission file
Generally, loading your market data permissions into QuantRocket is only necessary when you are running multiple IB Gateway services with different market data permissions for each.
To retrieve market data from IBKR, you must subscribe to the appropriate market data subscriptions in IBKR Client Portal. QuantRocket can't identify your subscriptions via API, so you must tell QuantRocket about your subscriptions by loading a YAML configuration file. If you don't load a configuration file, QuantRocket will assume you have market data permissions for any data you request through QuantRocket. If you only run one IB Gateway service, this is probably sufficient and you can skip the configuration file. However, if you run multiple IB Gateway services with separate market data permissions for each, you will probably want to load a configuration file so QuantRocket can route your requests to the appropriate IB Gateway service. You should also update your configuration file whenever you modify your market data permissions in IBKR Client Portal.
An example IB Gateway permissions template is available from the JupyterLab launcher.
QuantRocket looks for a market data permission file called quantrocket.ibg.permissions.yml
in the top-level of the Jupyter file browser (that is, /codeload/quantrocket.ibg.permissions.yml
). The format of the YAML file is shown below:
ibg1:
marketdata:
STK:
- NYSE
- ISLAND
- TSEJ
FUT:
- CME
- OSE
CASH:
- IDEALPRO
ibg2:
marketdata:
STK:
- NYSE
When you create or edit this file, QuantRocket will detect the change and load the configuration. It's a good idea to have flightlog open when you do this. If the configuration file is valid, you'll see a success message:
quantrocket.ibgrouter: INFO Successfully loaded /codeload/quantrocket.ibg.permissions.yml
If the configuration file is invalid, you'll see an error message:
quantrocket.ibgrouter: ERROR Could not load /codeload/quantrocket.ibg.permissions.yml:
quantrocket.ibgrouter: ERROR unknown key(s) for service ibg1: marketdata-typo
You can also dump out the currently loaded config to confirm it is as you expect:
$ quantrocket ibg config
ibg1:
marketdata:
CASH:
- IDEALPRO
FUT:
- CME
- OSE
STK:
- NYSE
- ISLAND
- TSEJ
ibg2:
marketdata:
STK:
- NYSE
>>> from quantrocket.ibg import get_ibg_config
>>> get_ibg_config()
{
'ibg1': {
'marketdata': {
'CASH': [
'IDEALPRO'
],
'FUT': [
'CME',
'OSE'
],
'STK': [
'NYSE',
'ISLAND',
'TSEJ'
]
}
},
'ibg2': {
'marketdata': {
'STK': [
'NYSE'
]
}
}
}
$ curl -X GET 'http://houston/ibgrouter/config'
{
"ibg1": {
"marketdata": {
"CASH": [
"IDEALPRO"
],
"FUT": [
"CME",
"OSE"
],
"STK": [
"NYSE",
"ISLAND",
"TSEJ"
]
}
},
"ibg2": {
"marketdata": {
"STK": [
"NYSE"
]
}
}
}
IB Gateway log files
There are two types of logs produced by IB Gateway: API logs and Gateway logs. The API logs show the API messages being sent back and forth between QuantRocket and IB Gateway. The Gateway logs show detailed debugging logs for the IB Gateway application.
The API logs are occasionally useful for troubleshooting QuantRocket and might be requested by QuantRocket support. The Gateway logs might occasionally be requested by Interactive Brokers support. If you need to send these files to QuantRocket or Interactive Brokers support for troubleshooting, you can generate and export the files as described below.
API logs
You can use the IB Gateway GUI to generate API logs, then export the logs to the Docker filesystem, then copy them to your local filesystem.
- With IB Gateway running, open the GUI.
- In the IB Gateway GUI, click Configure > Settings, navigate to API > Settings and check the box for "Create API message log file."
- IB Gateway will begin to generate API logs. Continue using the application until the messages you are interested in have been generated.
- Next, in the IB Gateway GUI, click File > API Logs, and select the day you're interested in.
- Click Export Logs or Export Today Logs. A file browser will open, showing the filesystem inside the Docker container.
- Export the log file to an easy-to-find location such as
/tmp/api-exported-logs.txt
. - From the host machine, copy the exported logs from the Docker container to your local filesystem. For
ibg1
logs saved to the above location, the command would be:
$ docker cp quantrocket_ibg1_1:/tmp/api-exported-logs.txt api-exported-logs.txt
After exporting the API logs, open IB Gateway GUI again and uncheck the box for "Create API message log file."
Gateway logs
You can use the IB Gateway GUI to export the Gateway logs to the Docker filesystem, then copy them to your local filesystem.
- With IB Gateway running, open the GUI.
- In the IB Gateway GUI, click File > Gateway Logs, and select the day you're interested in.
- Click Export Logs or Export Today Logs. A file browser will open, showing the filesystem inside the Docker container.
- Export the log file to an easy-to-find location such as
/tmp/ibgateway-exported-logs.txt
. - From the host machine, copy the exported logs from the Docker container to your local filesystem. For
ibg1
logs saved to the above location, the command would be:
$ docker cp quantrocket_ibg1_1:/tmp/ibgateway-exported-logs.txt ibgateway-exported-logs.txt
Alpaca
Your credentials are encrypted at rest and never leave your deployment.
You can connect to one or more paper Alpaca accounts and one or more live Alpaca accounts. Enter your API key and trading mode for each account you want to connect (you will be prompted for your secret key):
$ quantrocket license alpaca-key --api-key 'PXXXXXXXXXXXXXXXXXX' --paper
Enter Alpaca secret key:
status: successfully set Alpaca paper API key
>>> from quantrocket.license import set_alpaca_key
>>> set_alpaca_key(api_key="PXXXXXXXXXXXXXXXXXX", trading_mode="paper")
Enter Alpaca secret key:
{'status': 'successfully set Alpaca paper API key'}
$ curl -X PUT 'http://houston/license-service/credentials/alpaca' -d 'api_key=PXXXXXXXXXXXXXXXXXX&secret_key=XXXXXXXXXXXXXXXXXX&trading_mode=paper'
{"status": "successfully set Alpaca paper API key"}
If you plan to use Alpaca for real-time data and subscribe to Alpaca's unlimited data package which provides access to the full SIP data feed, you can indicate this by including the --realtime-data
/realtime_data
parameter and specifying 'sip' (if omitted, only Alpaca's free IEX data permission is assumed):
$ quantrocket license alpaca-key --api-key 'XXXXXXXXXXXXXXXXXX' --live --realtime-data 'sip'
Enter Alpaca secret key:
status: successfully set Alpaca live API key
>>> set_alpaca_key(api_key="XXXXXXXXXXXXXXXXXX", trading_mode="live", realtime_data="sip")
Enter Alpaca secret key:
{'status': 'successfully set Alpaca live API key'}
$ curl -X PUT 'http://houston/license-service/credentials/alpaca' -d 'api_key=XXXXXXXXXXXXXXXXXX&secret_key=XXXXXXXXXXXXXXXXXX&trading_mode=live&realtime_data=sip'
{"status": "successfully set Alpaca live API key"}
You can view the currently configured API keys, which are organized by account number:
$ quantrocket license alpaca-key
12345678:
api_key: XXXXXXXXXXXXXXXXXX
realtime_data: sip
trading_mode: live
P1234567:
api_key: PXXXXXXXXXXXXXXXXXX
realtime_data: iex
trading_mode: paper
>>> from quantrocket.license import get_alpaca_key
>>> get_alpaca_key()
{'12345678': {'api_key': 'XXXXXXXXXXXXXXXXXX', 'realtime_data': 'sip', 'trading_mode': 'live'},
'P1234567': {'api_key': 'PXXXXXXXXXXXXXXXXXX', 'realtime_data': 'iex','trading_mode': 'paper'}}
$ curl -X GET 'http://houston/license-service/credentials/alpaca'
{"12345678": {"api_key": "XXXXXXXXXXXXXXXXXX", 'realtime_data': 'sip',"trading_mode": "live"}, "P1234567": {"api_key": "PXXXXXXXXXXXXXXXXXX", 'realtime_data': 'iex', "trading_mode": "paper"}}
To later change your real-time data permission, simply re-enter the credentials with the new permission:
$ quantrocket license alpaca-key --api-key 'XXXXXXXXXXXXXXXXXX' --live --realtime-data 'iex'
Enter Alpaca secret key:
status: successfully set Alpaca live API key
>>> set_alpaca_key(api_key="XXXXXXXXXXXXXXXXXX", trading_mode="live", realtime_data="iex")
Enter Alpaca secret key:
{'status': 'successfully set Alpaca live API key'}
$ curl -X PUT 'http://houston/license-service/credentials/alpaca' -d 'api_key=XXXXXXXXXXXXXXXXXX&secret_key=XXXXXXXXXXXXXXXXXX&trading_mode=live&realtime_data=iex'
{"status": "successfully set Alpaca live API key"}
Polygon.io
Your credentials are encrypted at rest and never leave your deployment.
To enable access to Polygon.io data, enter your Polygon.io API key:
$ quantrocket license polygon-key 'XXXXXXXXXXXXXXXXXX'
status: successfully set Polygon API key
>>> from quantrocket.license import set_polygon_key
>>> set_polygon_key(api_key="XXXXXXXXXXXXXXXXXX")
{'status': 'successfully set Polygon API key'}
$ curl -X PUT 'http://houston/license-service/credentials/polygon' -d 'api_key=XXXXXXXXXXXXXXXXXX'
{"status": "successfully set Polygon API key"}
You can view the currently configured API key:
$ quantrocket license polygon-key
api_key: XXXXXXXXXXXXXXXXXX
>>> from quantrocket.license import get_polygon_key
>>> get_polygon_key()
{'api_key': 'XXXXXXXXXXXXXXXXXX'}
curl -X GET 'http://houston/license-service/credentials/polygon'
{"api_key": "XXXXXXXXXXXXXXXXXX"}
Nasdaq Data Link (Quandl)
Nasdaq acquired Quandl in 2018 and rebranded Quandl as Nasdaq Data Link in 2021. However, QuantRocket APIs reflect the original Quandl branding.
Your credentials are encrypted at rest and never leave your deployment.
Users who subscribe to Sharadar data through Nasdaq Data Link (formerly Quandl) can access Sharadar data in QuantRocket. To enable access, enter your Nasdaq/Quandl API key:
$ quantrocket license quandl-key 'XXXXXXXXXXXXXXXXXX'
status: successfully set Quandl API key
>>> from quantrocket.license import set_quandl_key
>>> set_quandl_key(api_key="XXXXXXXXXXXXXXXXXX")
{'status': 'successfully set Quandl API key'}
$ curl -X PUT 'http://houston/license-service/credentials/quandl' -d 'api_key=XXXXXXXXXXXXXXXXXX'
{"status": "successfully set Quandl API key"}
You can view the currently configured API key:
$ quantrocket license quandl-key
api_key: XXXXXXXXXXXXXXXXXX
>>> from quantrocket.license import get_quandl_key
>>> get_quandl_key()
{'api_key': 'XXXXXXXXXXXXXXXXXX'}
curl -X GET 'http://houston/license-service/credentials/quandl'
{"api_key": "XXXXXXXXXXXXXXXXXX"}
IDEs and Editors
JupyterLab is the primary user interface for QuantRocket and provides an ideal environment for interactive research. Alternatively, users who feel more at home in Visual Studio Code can connect it to QuantRocket with some basic setup.
JupyterLab
See the QuickStart for a hands-on overview of JupyterLab.

Visual Studio Code
If desired, you can install Visual Studio Code on your desktop and attach it to your local or cloud deployment. This allows you to edit code and open terminals from within VS Code. VS Code utilizes the environment provided by the QuantRocket container you attach to, so autocomplete and other features are based on the QuantRocket environment, meaning there's no need to manually replicate QuantRocket's environment on your local computer.
Follow these steps to use VS Code with QuantRocket.
- First, download and install VS Code for your operating system.
- In VS Code, open the extension manager and install the following extensions:
- Python
- Pylance
- Docker
- Remote - Containers
- Jupyter
- For cloud deployments only: By default, VS Code will be able to see any Docker containers running on your local machine. To make VS Code see your QuantRocket containers running remotely in the cloud, run
docker context use cloud
, just as you would to deploy QuantRocket to the cloud. This command points Docker to the remote host where you are running QuantRocket and causes VS Code to see the containers running remotely. (Alternatively, you can change the Docker context from the Contexts section of the Docker panel in VS Code.) - Open the Docker panel in the side bar, find the jupyter container, right-click, and choose "Attach Visual Studio Code". A new window opens.

- (The original VS Code window still points to your local computer and can be used to edit your local projects.)
- The new VS Code window that opened is attached to the jupyter container. VS code will automatically install itself on the jupyter container.
- Any extensions you may have installed on your local VS Code are not automatically installed on the remote VS Code, so you should install them. Open the Extensions Manager and install, at minimum, the Python extension, and anything else you like. VS Code remembers what you install in a local configuration file and restores your desired environment in the future even if you destroy and re-create the container.
- In the Explorer window, click Open Folder, type 'codeload', then Open Folder. The files on your jupyter container will now be displayed in the VS Code file browser.
Jupyter notebooks in VS Code
If you open a Jupyter notebook in VS Code and execute a cell, you will be prompted to enter the URL of a Jupyter server. Enter http://houston/jupyter
. When prompted for the Python interpreter to use, choose /opt/conda/bin/python
.
Support for running Jupyter notebooks in VS Code is experimental. If you encounter problems starting notebooks in VS Code, please use JupyterLab instead.
Terminal utilities
.bashrc
You can customize your JupyterLab Terminals by creating a .bashrc
file and storing it at /codeload/.bashrc
. This file will be run when you open a new terminal, just like on a standard Linux distribution.
An example use is to create aliases for commonly typed commands. For example, placing the following alias in your /codeload/.bashrc
file will allow you to check your balance by simply typing balance
:
alias balance="quantrocket account balance -l -f NetLiquidation | csvlook"
After adding or editing a .bashrc
file, you must open new Terminals for the changes to take effect.
csvkit
Many QuantRocket API endpoints return CSV files. csvkit
is a suite of utilities that makes it easier to work with CSV files from the command line. To make a CSV file more easily readable, use csvlook
:
$ quantrocket master get --exchanges 'XNAS' 'XNYS' | csvlook -I
| Sid | Symbol | Exchange | Country | Currency | SecType | Etf | Timezone | Name |
| -------------- | ------ | -------- | ------- | -------- | ------- | --- | ------------------- | -------------------------- |
| FIBBG000B9XRY4 | AAPL | XNAS | US | USD | STK | 0 | America/New_York | APPLE INC |
| FIBBG000BFWKC0 | MON | XNYS | US | USD | STK | 0 | America/New_York | MONSANTO CO |
| FIBBG000BKZB36 | HD | XNYS | US | USD | STK | 0 | America/New_York | HOME DEPOT INC |
| FIBBG000BMHYD1 | JNJ | XNYS | US | USD | STK | 0 | America/New_York | JOHNSON & JOHNSON |
Another useful utility is csvgrep
, which can be used to filter CSV files on fields not natively filterable by QuantRocket's API:
$
$ quantrocket master get --exchanges 'XNYS' --fields 'usstock_SecurityType2' | csvgrep --columns 'usstock_SecurityType2' --match 'Depositary Receipt' > nyse_adrs.csv
json2yml
For records which are too wide for the Terminal viewing area in CSV format, a convenient option is to request JSON and convert it to YAML using the json2yml
utility:
$ quantrocket master get --symbols 'AAPL' --json | json2yml
-
Sid: "FIBBG000B9XRY4"
Symbol: "AAPL"
Exchange: "XNAS"
Country: "US"
Currency: "USD"
SecType: "STK"
Etf: 0
Timezone: "America/New_York"
Name: "APPLE INC"
PriceMagnifier: 1
Multiplier: 1
Delisted: 0
DateDelisted: null
LastTradeDate: null
RolloverDate: null
Custom JupyterLab environments
Follow these steps to create a custom conda environment and make it available as a custom kernel from the JupyterLab launcher.
This is an advanced topic. Most users will not need to do this.
Keep in mind that QuantRocket has a distributed architecture and these steps will only create the custom environment within the jupyter
container, not in other containers where user code may run, such as the moonshot
, zipline
, and satellite
containers.
First-time install
First, in a JupyterLab terminal, initialize your bash shell then exit the terminal:
$ mamba init 'bash'
$ exit
Open a new JupyterLab terminal, then clone the base environment and activate your new environment:
$ mamba create --name 'myclone' --clone 'base'
$ mamba activate 'myclone'
Install new packages to customize your conda environment. For easier repeatability, list your packages in a text file in the /codeload
directory and install the packages from file. One of the packages should be ipykernel
:
$ (myclone) $ echo 'ipykernel' > /codeload/quantrocket.jupyter.conda.myclone.txt
$ (myclone) $
$ (myclone) $ mamba install --file '/codeload/quantrocket.jupyter.conda.myclone.txt'
Next, create a new kernel spec associated with your custom conda environment. For easier repeatability, create the kernel spec under the /codeload
directory instead of directly in the default location:
$ (myclone) $
$ (myclone) $ ipython kernel install --name 'mykernel' --display-name 'My Custom Kernel' --prefix '/codeload/kernels'
Install the kernel. This command copies the kernel spec to a location where JupyterLab looks:
$ (myclone) $ jupyter kernelspec install '/codeload/kernels/share/jupyter/kernels/mykernel'
Finally, to activate the change, open Terminal (MacOS/Linux) or PowerShell (Windows) and restart the jupyter container:
$ docker compose restart jupyter
The new kernel will appear in the Launcher menu:

Re-install after container redeploy
Whenever you redeploy the jupyter container (either due to updating the container version or force recreating the container), the filesystem is replaced and thus your custom conda environment and JupyterLab kernel will be lost. The re-install process can omit a few steps because you saved the conda package file and kernel spec to your /codeload
directory. The simplified process is as follows. Initialize your shell:
$ mamba init 'bash'
$ exit
Reopen a terminal, then:
$
$ mamba create --name 'myclone' --clone 'base'
$ mamba activate 'myclone'
$ (myclone) $
$ (myclone) $ mamba install --file '/codeload/quantrocket.jupyter.conda.myclone.txt'
$ (myclone) $
$ (myclone) $ jupyter kernelspec install '/codeload/kernels/share/jupyter/kernels/mykernel'
Then, restart the jupyter container to activate the change:
$ docker compose restart jupyter
Teams
Teams with a multi-user license can run more than one QuantRocket deployment. Because QuantRocket's primary user interface is JupyterLab, which is not designed to be a multi-user environment, teams should run a separate deployment for each user. The recommended deployment strategy is to run a primary deployment for third-party data collection and live trading, and one or more research deployments for research and backtesting.
| Deployed to | How many | Connects to Brokers and Data Providers | Used for | Used by |
---|
Primary deployment | Cloud | 1 | Yes | Third-party data collection, live trading | Team owner or administrator |
Research deployment(s) | Cloud or local | 1 or more | No | Research and backtesting | Quant researchers |
Cloud vs local
QuantRocket can either be installed locally or in the cloud. In the context of teams, the main tradeoff between cloud and local is cost vs control. Local deployments allow team members to utilize their existing workstations, saving on cloud costs. However, cloud deployments offer the team owner additional control and auditing by providing access to the team member's work environment.
The installation process also differs for cloud vs local deployments. For cloud deployments, the team owner or administrator installs Docker and deploys Quantrocket to the cloud, then provides the team member with login credentials to access the deployment. For local deployments, each team member installs Docker and deploys QuantRocket on his or her own machine.
A summary is shown below:
| Who performs installation | Incurs cloud costs | Easy to audit |
---|
Cloud | Team owner/administrator | yes | yes |
Local | Researcher | no | no |
Multiple cloud deployments
A team owner or administrator can deploy QuantRocket to multiple cloud servers from the administrator's own workstation. This provides a central place to manage multiple deployments.
To install multiple cloud deployments, follow the cloud installation tutorial, but observe the following modifications.
Unique deployment names
Wherever the tutorial uses the name quantrocket
or cloud
, you should instead choose a unique name for each deployment, for example quantrocket1
, quantrocket2
, etc. Apply the unique names in the following contexts:
| Single cloud deployment | Multiple cloud deployments |
---|
Docker Context name | cloud | cloud1 , cloud2 , etc. |
Domain name | quantrocket.abc-capital.com | quantrocket1.abc-capital.com , quantrocket2.abc-capital.com , etc. |
Local folder containing Compose file | ~/quantrocket | ~/quantrocket1 , ~/quantrocket2 , etc. |
(The names quantrocket1
etc. are only examples; you are free to choose different names.)
The following commands show how you would bring up two deployments by navigating to the appropriate local folder and specifying the corresponding Docker Context:
$
$ cd ~/quantrocket1
$ docker compose --context cloud1 up -d
$
$
$ cd ~/quantrocket2
$ docker compose --context cloud2 up -d
Unique Houston environment variables
The Houston domain, username, and password determine the URL and credentials your team members will use to log in to their cloud deployments. The installation tutorial suggests setting environment variables for your deployment's domain, username, and password. However, this approach is not as suitable when you need to set up multiple deployments with different variables for each.
Instead, the recommended approach for team administrators is to create a docker-compose.override.yml file in each of the local folders containing the Compose files (~/quantrocket1
, ~/quantrocket2
, etc.) and set the Houston variables directly in the override file. Each docker-compose.override.yml
should look similar to the following, with the appropriate variables for each deployment:
version: '2.4'
services:
houston:
environment:
BASIC_AUTH_USER: 'usernameyourteammemberwilluse'
BASIC_AUTH_PASSWD: 'passwordyourteammemberwilluse'
LETSENCRYPT_DOMAIN: 'quantrocket1.abc-capital.com'
Software activation
After deploying QuantRocket, the team administrator should access JupyterLab and enter the license key. (For security reasons, don't give the license key to your team members to enter themselves; see the section below for more on license key sharing.)
Team member access
Finally, provide your team members with the cloud deployment URL and login credentials you have established for them.
License key sharing
Sharing your license key with team members requires care because team members may leave your organization. An ex-team member with your license key could utilize one of your license seats for their own use, thus reducing the seats available for you. There are 3 options for securely sharing your license with team members.
Option 1: Administer cloud deployments
If you set up cloud deployments for your team members and enter your license key into each cloud deployment yourself, there is no security risk. The license key is encrypted at rest and is obfuscated in the display output (for example YXV0........ABCD
), so your team members will not have access to your full license key.
Option 2: Share and rotate
If your team members run QuantRocket locally on their own machines, you can share your license key with them, then whenever a team member leaves your organization, you can rotate your license key and distribute the new license key to your remaining team members.
Option 3: Link license keys
A third option is to instruct your team members to create their own QuantRocket accounts and link their accounts to yours. This allows the team members to activate the software by entering their own license key, rather than yours. The license profile output will display the team member's own license key, the team owner's email to which they are linked, and the team's software license:
$ quantrocket license get
licensekey: XXXX....XXXX
software_license:
account:
account_limit: XXXXXX USD
concurrent_install_limit: 4
license_type: Professional
user_limit: 3
team: team-owner@abc-capital.com
>>> from quantrocket.license import get_license_profile
>>> get_license_profile()
{'licensekey': 'XXXX....XXXX',
'software_license': {'license_type': 'Professional',
'user_limit': 3,
'concurrent_install_limit': 4,
'account': {'account_limit': 'XXXXXX USD'}},
'team': 'team-owner@abc-capital.com'}
$ curl -X GET 'http://houston/license-service/license'
{"licensekey": "XXXX....XXXX", "software_license": {"license_type": "Professional", "user_limit": 3, "concurrent_install_limit": 4, "account": {"account_limit": "XXXXXX USD"}}, "team": "team-owner@abc-capital.com"}
To link your team members to your account, follow these steps:
- Instruct each team member to register for their own QuantRocket account and generate their own license key.
- Open a support ticket and provide the emails your team members registered under. We will link their accounts to yours.
- Instruct your team members to enter their own license key into the software.
Data sharing
If your team members need access to third-party data such as data from your broker, the recommended approach is to collect the data on the primary deployment, push it to Amazon S3, then pull it from S3 onto the research deployments. That way, you only need to enable third-party API access on the primary deployment. This is not only a better security practice but is also necessary for third-party APIs such as IB Gateway which limit you to one concurrent connection.
For the primary deployment, create IAM credentials with read/write access to your S3 bucket. For the research deployments, you can create separate IAM credentials with read permission only. This ensures a one-way flow of data from the primary deployment to the research deployments.
See the Database Management section for more details on connecting to S3.
Code sharing
You can setup Git repositories to enable sharing of code and notebooks between team members, with access control managed directly on the Git repositories. See the Code Management section for more details on cloning from Git and pushing to Git.
Auditing
Team owners who need the ability to monitor their team members' activities should set up cloud deployments for their team members rather than having the team members run QuantRocket locally. To audit a cloud deployment, the team owner can simply log in to the deployment and review the code and notebooks or download the log files.
Securities Master
The securities master is the central repository of available assets. With QuantRocket's securities master, you can:
- Collect lists of all available securities from multiple data providers;
- Query reference data about securities, such as ticker symbol, currency, exchange, sector, expiration date (in the case of derivatives), and so on;
- Flexibly group securities into universes that make sense for your research or trading strategies.
QuantRocket assigns each security a unique ID known as its "Sid" (short for "security ID"). Sids allow securities to be uniquely and consistently referenced over time regardless of ticker changes or ticker symbol inconsistencies between vendors. Sids make it possible to mix-and-match data from different providers. QuantRocket Sids are primarily based on Bloomberg-sponsored OpenFIGI identifiers.
All components of the software, from historical and fundamental data collection to order and execution tracking, utilize Sids and thus depend on the securities master.
Collect listings
Generally, the first step before utilizing any dataset or sending orders to any broker is to collect the list of available securities for that provider.
Note on terminology: In QuantRocket, "collecting" data means retrieving it from a third-party or from the QuantRocket cloud and storing it in a local database. Once data has been collected, you can "download" it, which means to query the stored data from your local database for use in your analysis or trading strategies.
Because QuantRocket supports multiple data vendors and brokers, you may collect the same listing (for example AAPL stock) from multiple providers. QuantRocket will consolidate the overlapping records into a single, combined record, as explained in more detail below.
Alpaca
Alpaca customers should collect Alpaca's list of available securities before they begin live or paper trading:
$ quantrocket master collect-alpaca
msg: successfully loaded alpaca securities
status: success
>>> from quantrocket.master import collect_alpaca_listings
>>> collect_alpaca_listings()
{'status': 'success', 'msg': 'successfully loaded alpaca securities'}
$ curl -X POST 'http://houston/master/securities/alpaca'
{"status": "success", "msg": "successfully loaded alpaca securities"}
An example Alpaca record for AAPL is shown below:
Sid: "FIBBG000B9XRY4"
alpaca_AssetClass: "us_equity"
alpaca_AssetId: "b0b6dd9d-8b9b-48a9-ba46-b9d54906e415"
alpaca_EasyToBorrow: 1
alpaca_Exchange: "NASDAQ"
alpaca_Marginable: 1
alpaca_Name: null
alpaca_Shortable: 1
alpaca_Status: "active"
alpaca_Symbol: "AAPL"
alpaca_Tradable: 1
EDI
EDI listings are automatically collected when you collect EDI historical data, but they can also be collected separately. Specify one or MICs (market identifier codes):
$ quantrocket master collect-edi --exchanges 'XSHG' 'XSHE'
exchanges:
XSHE: successfully loaded XSHE securities
XSHG: successfully loaded XSHG securities
status: success
>>> from quantrocket.master import collect_edi_listings
>>> collect_edi_listings(exchanges=["XSHG", "XSHE"])
{'status': 'success',
'exchanges': {'XSHG': 'successfully loaded XSHG securities', 'XSHE': 'successfully loaded XSHE securities'}}
$ curl -X POST 'http://houston/master/securities/edi?exchanges=XSHG&exchanges=XSHE'
{"status": "success", "exchanges": {"XSHG": "successfully loaded XSHG securities", "XSHE": "successfully loaded XSHE securities"}}
For sample data, use the MIC code FREE
.
An example EDI record for AAPL is shown below:
Sid: "FIBBG000B9XRY4"
edi_Cik: 320193
edi_CountryInc: "United States of America"
edi_CountryListed: "United States of America"
edi_Currency: "USD"
edi_DateDelisted: null
edi_ExchangeListingStatus: "Listed"
edi_FirstPriceDate: "2007-01-03"
edi_GlobalListingStatus: "Active"
edi_Industry: "Information Technology"
edi_IsPrimaryListing: 1
edi_IsoCountryInc: "US"
edi_IsoCountryListed: "US"
edi_IssuerId: 30017
edi_IssuerName: "Apple Inc"
edi_LastPriceDate: null
edi_LocalSymbol: "AAPL"
edi_Mic: "XNAS"
edi_MicSegment: "XNGS"
edi_MicTimezone: "America/New_York"
edi_PreferredName: "Apple Inc"
edi_PrimaryMic: "XNAS"
edi_RecordCreated: "2001-05-05"
edi_RecordModified: "2020-02-10 13:17:27"
edi_SecId: 33449
edi_SecTypeCode: "EQS"
edi_SecTypeDesc: "Equity Shares"
edi_SecurityDesc: "Ordinary Shares"
edi_Sic: "Electronic Computers"
edi_SicCode: 3571
edi_SicDivision: "Manufacturing"
edi_SicIndustryGroup: "Computer And Office Equipment"
edi_SicMajorGroup: "Industrial And Commercial Machinery And Computer Equipment"
edi_StructureCode: null
edi_StructureDesc: null
Figi
QuantRocket Sids are based on FIGI identifiers. While the OpenFIGI API is primarily a way to map securities to FIGI identifiers, it also provides several useful security attributes including market sector, a detailed security type, and share class-level FIGI identifiers. You can collect FIGI fields for all available QuantRocket securities:
$ quantrocket master collect-figi
msg: successfully loaded FIGIs
status: success
>>> from quantrocket.master import collect_figi_listings
>>> collect_figi_listings()
{'status': 'success', 'msg': 'successfully loaded FIGIs'}
$ curl -X POST 'http://houston/master/securities/figi'
{"status": "success", "msg": "successfully loaded FIGIs"}
An example FIGI record for AAPL is shown below:
Sid: "FIBBG000B9XRY4"
figi_CompositeFigi: "BBG000B9XRY4"
figi_ExchCode: "US"
figi_Figi: "BBG000B9XRY4"
figi_IsComposite: 1
figi_MarketSector: "Equity"
figi_Name: "APPLE INC"
figi_SecurityDescription: "AAPL"
figi_SecurityType: "Common Stock"
figi_SecurityType2: "Common Stock"
figi_ShareClassFigi: "BBG001S5N8V8"
figi_Ticker: "AAPL"
figi_UniqueId: "EQ0010169500001000"
figi_UniqueIdFutOpt: null
Interactive Brokers
Interactive Brokers can be utilized both as a data provider and a broker. First, decide which exchange(s) you want to work with. You can view exchange listings on the IBKR website or use QuantRocket to summarize the IBKR website by security type:
$ quantrocket master list-ibkr-exchanges --regions 'asia' --sec-types 'STK'
STK:
Australia:
- ASX
- CHIXAU
Hong Kong:
- SEHK
- SEHKNTL
- SEHKSZSE
India:
- NSE
Japan:
- CHIXJ
- JPNNEXT
- TSEJ
Singapore:
- SGX
>>> from quantrocket.master import list_ibkr_exchanges
>>> list_ibkr_exchanges(regions=["asia"], sec_types=["STK"])
{'STK': {'Australia': ['ASX', 'CHIXAU'],
'Hong Kong': ['SEHK', 'SEHKNTL', 'SEHKSZSE'],
'India': ['NSE'],
'Japan': ['CHIXJ', 'JPNNEXT', 'TSEJ'],
'Singapore': ['SGX']}}
$ curl 'http://houston/master/exchanges/ibkr?sec_types=STK®ions=asia'
{"STK": {"Australia": ["ASX", "CHIXAU"], "Hong Kong": ["SEHK", "SEHKNTL", "SEHKSZSE"], "India": ["NSE"], "Japan": ["CHIXJ", "JPNNEXT", "TSEJ"], "Singapore": ["SGX"]}}
Specify the IBKR exchange code (not the MIC) to collect all listings on the exchange, optionally filtering by security type, symbol, or currency. For example, this would collect all stock listings on the Hong Kong Stock Exchange:
$ quantrocket master collect-ibkr --exchanges 'SEHK' --sec-types 'STK'
status: the IBKR listing details will be collected asynchronously
>>> from quantrocket.master import collect_ibkr_listings
>>> collect_ibkr_listings(exchanges="SEHK", sec_types=["STK"])
{'status': 'the IBKR listing details will be collected asynchronously'}
$ curl -X POST 'http://houston/master/securities/ibkr?exchanges=SEHK&sec_types=STK'
{"status": "the IBKR listing details will be collected asynchronously"}
QuantRocket uses the IB website to collect all symbols for the requested exchange then retrieves contract details from the IBKR API. The process runs asynchronously; check flightlog to monitor the progress:.$ quantrocket flightlog stream --hist 5
quantrocket.master: INFO Collecting SEHK STK listings from IBKR website
quantrocket.master: INFO Requesting details for 2630 SEHK listings found on IBKR website
quantrocket.master: INFO Saved 2630 SEHK listings to securities master database
The number of listings collected from the IBKR website might be larger than the number of listings actually saved to the database. This is because the IBKR website lists all symbols that trade on a given exchange, even if the exchange is not the primary listing exchange. For example, the primary listing exchange for Alcoa (AA) is NYSE, but the IBKR website also lists Alcoa under the BATS exchange because Alcoa also trades on BATS (and many other US exchanges). QuantRocket saves Alcoa's contract details when you collect NYSE listings, not when you collect BATS listings
For futures, the number of contracts saved to the database will typically be larger than the number of listings found on the IBKR website because the website only lists underlyings but QuantRocket saves all available expiries for each underlying.
For free sample data, specify the exchange code FREE
.
An example IBKR record for AAPL is shown below:
Sid: "FIBBG000B9XRY4"
ibkr_AggGroup: 1
ibkr_Category: "Computers"
ibkr_ComboLegs: null
ibkr_ConId: 265598
ibkr_ContractMonth: null
ibkr_Currency: "USD"
ibkr_Cusip: null
ibkr_DateDelisted: null
ibkr_Delisted: 0
ibkr_Etf: 0
ibkr_EvMultiplier: 0
ibkr_EvRule: null
ibkr_Industry: "Computers"
ibkr_Isin: "US0378331005"
ibkr_LastTradeDate: null
ibkr_LocalSymbol: "AAPL"
ibkr_LongName: "APPLE INC"
ibkr_MarketName: "NMS"
ibkr_MarketRuleIds: "26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26"
ibkr_MdSizeMultiplier: null
ibkr_MinSize: 1.0
ibkr_MinTick: 0.01
ibkr_Multiplier: null
ibkr_PriceMagnifier: 1
ibkr_PrimaryExchange: "NASDAQ"
ibkr_RealExpirationDate: null
ibkr_Right: null
ibkr_SecType: "STK"
ibkr_Sector: "Technology"
ibkr_SizeIncrement: 1.0
ibkr_StockType: "COMMON"
ibkr_Strike: 0
ibkr_SuggestedSizeIncrement: 100.0
ibkr_Symbol: "AAPL"
ibkr_Timezone: "America/New_York"
ibkr_TradingClass: "NMS"
ibkr_UnderConId: 0
ibkr_UnderSecType: null
ibkr_UnderSymbol: null
ibkr_ValidExchanges: "SMART,AMEX,NYSE,CBOE,PHLX,ISE,CHX,ARCA,ISLAND,DRCTEDGE,BEX,BATS,EDGEA,CSFBALGO,JEFFALGO,BYX,IEX,EDGX,FOXRIVER,TPLUS1,NYSENAT,PSX"
Option chains
To collect option chains from Interactive Brokers, first collect listings for the underlying securities:
$ quantrocket master collect-ibkr --exchanges 'NASDAQ' --sec-types 'STK' --symbols 'GOOG' 'FB' 'AAPL'
status: the IBKR listing details will be collected asynchronously
>>> from quantrocket.master import collect_ibkr_listings
>>> collect_ibkr_listings(exchanges="NASDAQ", sec_types=["STK"], symbols=["GOOG", "FB", "AAPL"])
{'status': 'the IBKR listing details will be collected asynchronously'}
$ curl -X POST 'http://houston/master/securities/ibkr?exchanges=NASDAQ&sec_types=STK&symbols=GOOG&symbols=FB&symbols=AAPL'
{"status": "the IBKR listing details will be collected asynchronously"}
Then request option chains by specifying the sids of the underlying stocks. In this example, we download a file of the underlying stocks and pass it as an infile to the options collection endpoint:
$ quantrocket master get -e 'NASDAQ' -t 'STK' -s 'GOOG' 'FB' 'AAPL' | quantrocket master collect-ibkr-options --infile -
status: the IBKR option chains will be collected asynchronously
>>> from quantrocket.master import download_master_file, collect_ibkr_option_chains
>>> import io
>>> f = io.StringIO()
>>> download_master_file(f, exchanges=["NASDAQ"], sec_types=["STK"], symbols=["GOOG", "FB", "AAPL"])
>>> collect_ibkr_option_chains(infilepath_or_buffer=f)
{'status': 'the IBKR option chains will be collected asynchronously'}
$ curl -X GET 'http://houston/master/securities.csv?exchanges=NASDAQ&sec_types=STK&symbols=GOOG&symbols=FB&symbols=AAPL' > nasdaq_mega.csv
$ curl -X POST 'http://houston/master/options/ibkr' --upload-file nasdaq_mega.csv
{"status": "the IBKR option chains will be collected asynchronously"}
Once the options collection has finished, you can query the options like any other security:
$ quantrocket master get -s 'GOOG' 'FB' 'AAPL' -t 'OPT' --outfile 'options.csv'
>>> from quantrocket.master import get_securities
>>> options = get_securities(symbols=["GOOG", "FB", "AAPL"], sec_types=["OPT"])
$ curl -X GET 'http://houston/master/securities.csv?symbols=GOOG&symbols=FB&symbols=AAPL&sec_types=OPT' > options.csv
Option chains often consist of hundreds, sometimes thousands of options per underlying security. Requesting option chains for large universes of underlying securities, such as all stocks on the NYSE, can take numerous hours to complete.
Sharadar
Sharadar listings are automatically collected when you collect Sharadar fundamental or price data, but they can also be collected separately. Specify the country (US
):
$ quantrocket master collect-sharadar --countries 'US'
countries:
US: successfully loaded US securities
status: success
>>> from quantrocket.master import collect_sharadar_listings
>>> collect_sharadar_listings(countries="US")
>>> {'status': 'success', 'countries': {'US': 'successfully loaded US securities'}}
$ curl -X POST 'http://houston/master/securities/sharadar?countries=US'
{"status": "success", "countries": {"US": "successfully loaded US securities"}}
For sample data, use the country code FREE
.
An example Sharadar record for AAPL is shown below:
Sid: "FIBBG000B9XRY4"
sharadar_Category: "Domestic"
sharadar_CompanySite: "http://www.apple.com"
sharadar_CountryListed: "US"
sharadar_Currency: "USD"
sharadar_Cusips: 37833100
sharadar_DateDelisted: null
sharadar_Delisted: 0
sharadar_Exchange: "NASDAQ"
sharadar_FamaIndustry: "Computers"
sharadar_FamaSector: null
sharadar_FirstAdded: "2014-09-24"
sharadar_FirstPriceDate: "1986-01-01"
sharadar_FirstQuarter: "1996-09-30"
sharadar_Industry: "Consumer Electronics"
sharadar_LastPriceDate: null
sharadar_LastQuarter: "2020-06-30"
sharadar_LastUpdated: "2020-07-03"
sharadar_Location: "California; U.S.A"
sharadar_Name: "Apple Inc"
sharadar_Permaticker: 199059
sharadar_RelatedTickers: null
sharadar_ScaleMarketCap: "6 - Mega"
sharadar_ScaleRevenue: "6 - Mega"
sharadar_SecFilings: "https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&CIK=0000320193"
sharadar_Sector: "Technology"
sharadar_SicCode: 3571
sharadar_SicIndustry: "Electronic Computers"
sharadar_SicSector: "Manufacturing"
sharadar_Ticker: "AAPL"
US Stock
All plans include access to historical intraday and end-of-day US stock prices. US stock listings are automatically collected when you collect the price data, but they can also be collected separately.
$ quantrocket master collect-usstock
msg: successfully loaded US stock listings
status: success
>>> from quantrocket.master import collect_usstock_listings
>>> collect_usstock_listings()
{'status': 'success', 'msg': 'successfully loaded US stock listings'}
$ curl -X POST 'http://houston/master/securities/usstock'
{"status": "success", "msg": "successfully loaded US stock listings"}
An example US stock record for AAPL is shown below:
Sid: "FIBBG000B9XRY4"
usstock_CIK: 320193
usstock_DateDelisted: null
usstock_FirstPriceDate: "2007-01-03"
usstock_Industry: "Hardware & Equipment"
usstock_LastPriceDate: null
usstock_Mic: "XNAS"
usstock_Name: "APPLE INC"
usstock_PrimaryShareSid: null
usstock_Sector: "Technology"
usstock_SecurityType: "Common Stock"
usstock_SecurityType2: "Common Stock"
usstock_Sic: "Electronic Computers"
usstock_SicCode: 3571
usstock_SicDivision: "Manufacturing"
usstock_SicIndustryGroup: "Computer And Office Equipment"
usstock_SicMajorGroup: "Industrial And Commercial Machinery And Computer Equipment"
usstock_Symbol: "AAPL"
US Stock security types
In order of granularity from least granular to most granular, the available security type fields are SecType
(always 'STK' for this dataset), usstock_SecurityType2
, and usstock_SecurityType
. The usstock_SecurityType2
field is the one most often used for filtering universes to certain security types. Among the most common values for usstock_SecurityType2
are "Common Stock", "Mutual Fund" (ETFs), "Depositary Receipt" (ADRs), and "Preferred Stock". To see all possible choices:
from quantrocket.master import get_securities
securities = get_securities(vendors="usstock", fields="usstock*")
securities.groupby([securities.usstock_SecurityType2, securities.usstock_SecurityType]).usstock_Symbol.count()
Primary share class
Some companies trade under multiple share classes. For example, Alphabet (Google) trades under two different share classes with different voting rights, "GOOGL" (A shares) and "GOOG" (C shares). The usstock_PrimaryShareSid
field provides a link from the secondary share to the primary share. In the case of Alphabet, "GOOGL" is considered the primary share and "GOOG" the secondary share, so the usstock_PrimaryShareSid
field for "GOOG" points to the Sid of "GOOGL". If usstock_PrimaryShareSid
is null, this indicates that the security is the primary share class (which could be because it is the only share class).
The most common use of the usstock_PrimaryShareSid
field is to deduplicate companies with multiple share classes, to avoid trading multiple highly correlated securities from the same company. This can be achieved by filtering your universe to securities where usstock_PrimaryShareSid
is null.
Note that usstock_PrimaryShareSid
is only populated when the secondary and primary shares have the same security type (based on usstock_SecurityType2
). Links between "Common Stock" and "Preferred Stock" (for example) are not provided. If you wish to determine links across security types, you can use the usstock_CIK
field for this purpose. The CIK (Central Index Key) is a company-level identifier used in SEC filings and thus is the same for all securities associated with a single company.
Master file
After you collect listings, you can download and inspect the master file, querying by symbol, exchange, currency, sid, or universe. When querying by exchange, you can use the MIC as in the following example (preferred), or the vendor-specific exchange code:
$ quantrocket master get --exchanges 'XNAS' 'XNYS' -o listings.csv
$ csvlook listings.csv
| Sid | Symbol | Exchange | Country | Currency | SecType | Etf | Timezone | Name |
| -------------- | ------ | -------- | ------- | -------- | ------- | --- | ------------------- | -------------------------- |
| FIBBG000B9XRY4 | AAPL | XNAS | US | USD | STK | 0 | America/New_York | APPLE INC |
| FIBBG000BFWKC0 | MON | XNYS | US | USD | STK | 0 | America/New_York | MONSANTO CO |
| FIBBG000BKZB36 | HD | XNYS | US | USD | STK | 0 | America/New_York | HOME DEPOT INC |
| FIBBG000BMHYD1 | JNJ | XNYS | US | USD | STK | 0 | America/New_York | JOHNSON & JOHNSON |
| FIBBG000BPH459 | MSFT | XNAS | US | USD | STK | 0 | America/New_York | MICROSOFT CORP |
>>> from quantrocket.master import get_securities
>>> securities = get_securities(exchanges=["XNYS", "XNAS"])
>>> securities.head()
Symbol Exchange Country Currency SecType Etf Timezone Name
Sid
FIBBG000B9XRY4 AAPL XNAS US USD STK False America/New_York APPLE INC
FIBBG000BFWKC0 MON XNYS US USD STK False America/New_York MONSANTO CO
FIBBG000BKZB36 HD XNYS US USD STK False America/New_York HOME DEPOT INC
FIBBG000BMHYD1 JNJ XNYS US USD STK False America/New_York JOHNSON & JOHNSON
FIBBG000BPH459 MSFT XNAS US USD STK False America/New_York MICROSOFT CORP
$ curl -X GET 'http://houston/master/securities.csv?exchanges=XNYS&exchanges=XNAS' > listings.csv
$ head listings.csv
Sid,Symbol,Exchange,Country,Currency,SecType,Etf,Timezone,Name
FIBBG000B9XRY4,AAPL,XNAS,US,USD,STK,0,America/New_York,"APPLE INC"
FIBBG000BFWKC0,MON,XNYS,US,USD,STK,0,America/New_York,"MONSANTO CO"
FIBBG000BKZB36,HD,XNYS,US,USD,STK,0,America/New_York,"HOME DEPOT INC"
FIBBG000BMHYD1,JNJ,XNYS,US,USD,STK,0,America/New_York,"JOHNSON & JOHNSON"
FIBBG000BPH459,MSFT,XNAS,US,USD,STK,0,America/New_York,"MICROSOFT CORP"
Core vs extended fields
By default, the securities master file returns a core set of fields:
Sid
: unique security IDSymbol
: ticker symbolExchange
: the MIC (market identifier code) of the primary exchangeCountry
: ISO country codeCurrency
: ISO currencySecType
: the security type. See available typesETF
: 1 if the security is an ETF, otherwise 0Timezone
: timezone of the exchangeName
: issuer name or security descriptionPriceMagnifier
: price divisor to use when prices are quoted in a different currency than the security's currency (for example GBP-denominated securities which trade in GBX will have an PriceMagnifier of 100). This is used by QuantRocket but users won't usually need to worry about it.Multiplier
: contract multiplier for derivativesDelisted
: 1 if the security is delisted, otherwise 0DateDelisted
: date security was delistedLastTradeDate
: last trade date for derivativesRolloverDate
: rollover date for futures contracts
These fields are consolidated from the available vendor records you've collected. In other words, QuantRocket will populate the core fields from any vendor that provides that field, based on the vendors you have collected listings from.
You can also access the extended fields, which are not consolidated but rather provide the exact values for a specific vendor. Extended fields are named like <vendor>_<FieldName>
and can be requested in several ways, including by field name (e.g. usstock_Mic
):
$ quantrocket master get --symbols 'AAPL' --fields 'Symbol' 'Exchange' 'usstock_Symbol' 'usstock_Mic' --json | json2yml
---
-
Sid: "FIBBG000B9XRY4"
Symbol: "AAPL"
Exchange: "XNAS"
usstock_Mic: "XNAS"
usstock_Symbol: "AAPL"
>>> securities = get_securities(symbols="AAPL", fields=["Symbol", "Exchange", "usstock_Symbol", "usstock_Mic"])
>>> securities.iloc[0]
Symbol AAPL
Exchange XNAS
usstock_Mic XNAS
usstock_Symbol AAPL
Name: FIBBG000B9XRY4, dtype: object
$ curl -X GET 'http://houston/master/securities.json?symbols=AAPL&fields=Symbol&fields=Exchange&fields=usstock_Symbol&fields=usstock_Mic' | json2yml
---
-
Sid: "FIBBG000B9XRY4"
Symbol: "AAPL"
Exchange: "XNAS"
usstock_Mic: "XNAS"
usstock_Symbol: "AAPL"
Use the wildcard <vendor>*
to return all fields for a vendor (see the command or function help for the available vendor prefixes):
$ quantrocket master get --symbols 'AAPL' --fields 'usstock\*' --json | json2yml
---
-
Sid: "FIBBG000B9XRY4"
usstock_CIK: 320193
usstock_DateDelisted: null
usstock_FirstPriceDate: "2007-01-03"
usstock_Industry: "Hardware & Equipment"
usstock_LastPriceDate: "2020-12-16"
usstock_Mic: "XNAS"
usstock_Name: "APPLE INC"
usstock_PrimaryShareSid: null
usstock_Sector: "Technology"
usstock_SecurityType: "Common Stock"
usstock_SecurityType2: "Common Stock"
usstock_Sic: "Electronic Computers"
usstock_SicCode: 3571
usstock_SicDivision: "Manufacturing"
usstock_SicIndustryGroup: "Computer And Office Equipment"
usstock_SicMajorGroup: "Industrial And Commercial Machinery And Computer Equipment"
usstock_Symbol: "AAPL"
>>> securities = get_securities(symbols="AAPL", fields="usstock\*")
>>> securities.iloc[0]
usstock_CIK 320193
usstock_DateDelisted NaT
usstock_FirstPriceDate 2007-01-03 00:00:00
usstock_Industry Hardware & Equipment
usstock_LastPriceDate 2020-12-16 00:00:00
usstock_Mic XNAS
usstock_Name APPLE INC
usstock_PrimaryShareSid NaN
usstock_Sector Technology
usstock_SecurityType Common Stock
usstock_SecurityType2 Common Stock
usstock_Sic Electronic Computers
usstock_SicCode 3571
usstock_SicDivision Manufacturing
usstock_SicIndustryGroup Computer And Office Equipment
usstock_SicMajorGroup Industrial And Commercial Machinery And Comput...
usstock_Symbol AAPL
Name: FIBBG000B9XRY4, dtype: object
$ curl -X GET 'http://houston/master/securities.json?symbols=AAPL&fields=usstock%2A' | json2yml
---
-
Sid: "FIBBG000B9XRY4"
usstock_CIK: 320193
usstock_DateDelisted: null
usstock_FirstPriceDate: "2007-01-03"
usstock_Industry: "Hardware & Equipment"
usstock_LastPriceDate: "2020-12-16"
usstock_Mic: "XNAS"
usstock_Name: "APPLE INC"
usstock_PrimaryShareSid: null
usstock_Sector: "Technology"
usstock_SecurityType: "Common Stock"
usstock_SecurityType2: "Common Stock"
usstock_Sic: "Electronic Computers"
usstock_SicCode: 3571
usstock_SicDivision: "Manufacturing"
usstock_SicIndustryGroup: "Computer And Office Equipment"
usstock_SicMajorGroup: "Industrial And Commercial Machinery And Computer Equipment"
usstock_Symbol: "AAPL"
Finally, use "*" to return all core and extended fields:
$ quantrocket master get --symbols 'AAPL' --fields '\*' --json | json2yml
---
-
Sid: "FIBBG000B9XRY4"
Symbol: "AAPL"
Exchange: "XNAS"
...
usstock_SicIndustryGroup: "Computer And Office Equipment"
usstock_SicMajorGroup: "Industrial And Commercial Machinery And Computer Equipment"
usstock_Symbol: "AAPL"
>>> securities = get_securities(symbols="AAPL", fields="\*")
>>> securities.iloc[0]
Symbol AAPL
Exchange XNAS
...
usstock_SicIndustryGroup Computer And Office Equipment
usstock_SicMajorGroup Industrial And Commercial Machinery And Comput...
usstock_Symbol AAPL
Name: FIBBG000B9XRY4, dtype: object
$ curl -X GET 'http://houston/master/securities.json?symbols=AAPL&fields=%2A' | json2yml
---
-
Sid: "FIBBG000B9XRY4"
Symbol: "AAPL"
Exchange: "XNAS"
...
usstock_SicIndustryGroup: "Computer And Office Equipment"
usstock_SicMajorGroup: "Industrial And Commercial Machinery And Computer Equipment"
usstock_Symbol: "AAPL"
Limit by vendor
In some cases, you might want to limit records to those provided by a specific vendor. For example, you might wish to create a universe of securities supported by your broker. For this purpose, use the --vendors/vendors
parameter. This will cause the query to search the requested vendors only:
$ quantrocket master get --exchanges 'XNYS' --vendors 'ibkr' -o ibkr_securities.csv
>>> securities = get_securities(exchanges="XNYS", vendors="ibkr")
$ curl -X GET 'http://houston/master/securities.csv?exchanges=XNYS&vendors=ibkr' -o ibkr_securities.csv
Don't confuse --vendors/vendors
with --fields/fields
. Limiting --fields/fields
to a specific vendor will search all vendors but only return the requested vendor's fields. Limiting --vendors/vendors
to a specific vendor will only search the requested vendor but may return all fields (depending on the --fields/fields
parameter). In other words, --vendors/vendors
controls what is searched, while --fields/fields
controls output.
Security types
The following security types or asset classes are available:
Code | Asset class |
---|
STK | stocks |
ETF | ETFs |
FUT | futures |
CASH | FX |
IND | indices |
OPT | options (see docs) |
FOP | futures options (see docs) |
BAG | combos (see docs) |
With the exception of ETFs, these security type codes are stored in the SecType
field of the master file. ETFs are a special case. Stocks and ETFs are distinguished as follows in the master file:
| SecType field | Etf field |
---|
ETF | STK | 1 |
Stock | STK | 0 |
More detailed security types are also available from many vendors. See the following fields:
edi_SecTypeCode
and edi_SecTypeDesc
figi_SecurityType
and figi_SecurityType2
sharadar_Category
usstock_SecurityType
and usstock_SecurityType2
Universes
Once you've collected listings that interest you, you can group them into meaningful universes. Universes provide a convenient way to refer to and manipulate groups of securities when collecting historical data, running a trading strategy, etc. You can create universes based on exchanges, security types, sectors, liquidity, or any criteria you like.
One way to create a universe is to download a master file that includes the securities you want, then create the universe from the master file:
$ quantrocket master get --exchanges 'XHKG' --sec-types 'STK' --outfile hongkong_securities.csv
$ quantrocket master universe 'hong-kong-stk' --infile hongkong_securities.csv
code: hong-kong-stk
inserted: 2216
provided: 2216
total_after_insert: 2216
>>> from quantrocket.master import download_master_file, create_universe
>>> download_master_file("hongkong_securities.csv", exchanges=["XHKG"], sec_types="STK")
>>> create_universe("hong-kong-stk", infilepath_or_buffer="hongkong_securities.csv")
{'code': 'hong-kong-stk',
'inserted': 2216,
'provided': 2216,
'total_after_insert': 2216}
$ curl -X GET 'http://houston/master/securities.csv?exchanges=XHKG&sec_types=STK' > hongkong_securities.csv
$ curl -X PUT 'http://houston/master/universes/hong-kong-stk' --upload-file hongkong_securities.csv
{"code": "hong-kong-stk", "provided": 2216, "inserted": 2216, "total_after_insert": 2216}
When uploading a file to create a universe, only the Sid
column matters. This means the CSV file need not be a master file; it can be any file with a Sid
column, such as a CSV file of fundamentals.
Using the CLI, you can create a universe in one-line by piping the downloaded CSV to the universe command, using --infile -
to specify reading the input file from stdin:
$ quantrocket master get --exchanges 'XCME' --symbols 'ES' --sec-types 'FUT' | quantrocket master universe 'es-fut' --infile -
code: es-fut
inserted: 12
provided: 12
total_after_insert: 12
Using the Python API, you can load securities with get_securities
, optionally filter the securities in pandas, then create the universe from the filtered sids:
>>> securities = get_securities(exchanges=["XNYS", "XNAS", "ARCX", "XASE"], sec_types="STK", fields="usstock*")
>>> adrs = securities[securities.usstock_SecurityType2=="Depositary Receipt"]
>>> create_universe("us-adrs", sids=adrs.index.tolist())
{'code': 'us-adrs',
'provided': 669,
'inserted': 669,
'total_after_insert': 669}
You can also manually edit a CSV file, deleting rows you don't want, before uploading the file to create a universe.
You can also create a universe from existing universes:
$ quantrocket master universe 'asx' --from-universes 'asx-sml' 'asx-mid' 'asx-lrg'
code: asx
inserted: 1604
provided: 1604
total_after_insert: 1604
>>> from quantrocket.master import create_universe
>>> create_universe("asx", from_universes=["asx-sml", "asx-mid", "asx-lrg"])
{'code': 'asx',
'inserted': 1604,
'provided': 1604,
'total_after_insert': 1604}
$ curl -X PUT 'http://houston/master/universes/asx?from_universes=asx-sml&from_universes=asx-mid&from_universes=asx-lrg'
{"code": "asx", "provided": 1604, "inserted": 1604, "total_after_insert": 1604}
Universes are static. If new securities become available that you want to include in your universe, you can add them to an existing universe using --append/append=True
:
$ quantrocket master get --exchanges 'XCME' --symbols 'ES' --sec-types 'FUT' | quantrocket master universe 'es-fut' --infile - --append
code: es-fut
inserted: 22
provided: 34
total_after_insert: 34
>>> futs = get_securities(exchanges="XCME", symbols="ES", sec_types="FUT")
>>> create_universe("es-fut", sids=futs.index.tolist(), append=True)
{'code': 'es-fut',
'provided': 34,
'inserted': 22,
'total_after_insert': 34}
$ curl -X GET 'http://houston/master/securities.csv?exchanges=XCME&sec_types=FUT&symbols=ES' > es_fut.csv
$ curl -X PATCH 'http://houston/master/universes/es-fut' --upload-file es_fut.csv
{"code": "es-fut", "provided": 34, "inserted": 22, "total_after_insert": 34}
You can list the universes you've created, which shows the number of securities in each universe:
$ quantrocket master list-universes
arca-etf: 1267
asx-stk: 2387
es-fut: 34
usa-stk: 6518
>>> from quantrocket.master import list_universes
>>> list_universes()
{'arca-etf': 1267,
'asx-stk': 2387,
'es-fut': 34,
'usa-stk': 6518}
curl -X GET 'http://houston/master/universes'
{"arca-etf": 1267, "asx-stk": 2387, "es-fut": 34, "usa-stk": 6518}
Deleting a universe does not delete any securities but simply deletes their grouping as a universe:
$ quantrocket master delete-universe 'es-fut'
code: es-fut
deleted: 34
>>> from quantrocket.master import delete_universe
>>> delete_universe("es-fut")
{"code": "es-fut",
"deleted": 34}
$ curl -X DELETE 'http://houston/master/universes/es-fut'
{"code": "es-fut", "deleted": 34}
Maintain listings
While securities master fields are relatively static, they do sometimes change. Stocks change ticker symbols or switch exchanges or are delisted. Although such changes do not affect a security's Sid, it's still a good idea to keep your securities master database up-to-date, especially as you transition from researching to trading.
To update the securities master database, simply collect the listings again.
Delist IBKR stocks
For most data vendors, you can keep the Delisted
and DateDelisted
fields up-to-date simply by re-collecting the listings from time to time. However, Interactive Brokers is a special case, because when stocks are delisted, Interactive Brokers removes them from its system. Thus, if you want the Delisted
and DateDelisted
fields in the securities master database to be accurate, you cannot simply re-collect the listings with the updated fields, since they are no longer available to collect.
To delist IBKR stocks, you can use the command quantrocket master diff-ibkr
. This command queries the IBKR API and compares securities as stored in the local database with the securities as reflected in IBKR's system. This command can be used to flag changes to fields (such as ibkr_PrimaryExchange
) and can also be used to detect securities that have been removed from IBKR's system.
A good way to use this command is to schedule it to run weekly on your countdown service crontab, as shown in the example below:
0 5 * * sun quantrocket ibg start --wait && quantrocket master get --sec-types 'STK' 'ETF' --vendors 'ibkr' --fields 'Sid' --exclude-delisted | quantrocket master diff-ibkr --infile - --fields 'ibkr_ConId' --delist-missing --delist-exchanges 'VALUE'
The explanation of the command is as follows:
0 5 * * sun
: run the command on Sundays at 5 AMquantrocket ibg start --wait
: start IB Gatewayquantrocket master get --sec-types 'STK' 'ETF' --vendors 'ibkr' --fields 'Sid' --exclude-delisted
: download a CSV of all IBKR stocks and ETFs that are not already marked as delisted| quantrocket master diff-ibkr --infile -
: query the IBKR API for each security in the downloaded CSV file--fields 'ibkr_ConId'
: only flag differences in the ibkr_ConId
field; this avoids the potential for noisy output--delist-missing
: delist securities that are no longer available from IBKR--delist-exchanges 'VALUE'
: delist securities associated with the 'VALUE' exchange (IBKR uses the "VALUE" exchange as a placeholder for some delisted symbols)
Delisting a security is a matter of proper record-keeping and also benefits data collection as it instructs QuantRocket not to waste time requesting data from IBKR for this security.
Understanding sids
You do not need to read or understand this section to use QuantRocket. It is provided for those who want a deeper understanding of where sids come from.
QuantRocket assigns each security a unique ID known as its "Sid" (short for "security ID"). This section provides background information on why sids are used, how they are assigned, and what their limitations are.
The problem with ticker symbols
Securities are commonly identified by ticker symbols. But ticker symbols are problematic identifiers for quantitative analysis for two main reasons.
The first problem is that ticker symbols can change or be recycled over time. A single security may be represented by multiple ticker symbols over its lifetime; conversely, a single ticker symbol may reference multiple distinct securities over time.
Example: Prior to December 2018, "GOLD" was the ticker symbol for Randgold Resources, and "ABX" was the ticker symbol for Barrick Gold. In December 2018, Barrick Gold acquired Randgold Resources. The stock for Randgold Resources was delisted, and Barrick Gold adopted the ticker symbol "GOLD".
In the above example, obtaining complete historical data for Barrick Gold requires combining the pre-merger data for the ticker symbol "ABX" with the post-merger data for the ticker symbol "GOLD". Naively analyzing historical data for the ticker symbol "GOLD" would conflate two different securities, the pre-merger Randgold Resources and the post-merger Barrick Gold.
The second common problem with ticker symbols is that different data providers use different conventions for preferred shares or for securities where the share class is indicated in the ticker symbol.
Example: Berkshire Hathaway Class B shares are variously referred to by the ticker symbol "BRK-B", "BRK.B", or "BRK B", depending on the data provider.
About FIGIs
Due to the inherent limitations of ticker symbols, a variety of different security identification schemes have been developed by standards agencies and governing bodies. These include ISIN, CUSIP, Sedol, and FIGI, among others. QuantRocket sids are primarily based on FIGI identifiers. FIGI is an open standard sponsored by Bloomberg. Its benefits are that, unlike many other identifiers, it has no licensing restrictions, and it provides an API for looking up FIGIs by ticker symbols or other identifiers.
The FIGI standard offers three different levels of granularity:
Granularity | Type of FIGI | Description | Example |
---|
most granular | exchange-level FIGI | unique to each security and exchange | AAPL trading on NASDAQ has a different exchange-level FIGI from AAPL trading on NYSE. |
country-level FIGI | unique to each security and country | AAPL has a single country-level FIGI covering all US exchanges but has different FIGIs for European countries where AAPL trades. | |
least granular | share-class FIGI | unique to each security, regardless of country and exchange | AAPL has a single share-class-level FIGI that covers all global exchanges where AAPL trades. |
QuantRocket utilizes country-level FIGIs. Exchange-level FIGIs are useful for back office purposes for banks and brokerages but are overly granular for the purposes of quantitative trading.
How QuantRocket assigns sids
For each data provider, QuantRocket looks up and assigns the appropriate FIGI for each security. The assignment process varies by data provider as it depends on the type of security information available from the data provider. For example, some data providers provide ISINs, some provide FIGIs, and some only provide ticker symbols.
Each sid has a prefix which specifies the type of identifier it is based on. For stocks, securities that have been successfully mapped to a FIGI have a prefix of FI
, followed by the 12-digit country-level FIGI. Securities which cannot be mapped to a FIGI due to limitations in the source data have a prefix of Q
. In general, FI
prefixes indicate a higher-quality mapping.
FIGIs are only used for stocks. They are not used for futures (prefix QF
), currencies (prefix FX
), or options (prefix IB
).
Why discrepancies between data providers can occur
Sids allow you to mix and match data from different providers. However, for equities, you shouldn't expect 100% perfect alignment between different data providers. There are many complexities surrounding the mapping of equities data, and outlining all of them is beyond the scope of this note, but the following scenario will provide an illustration.
If ticker symbols are not granular enough for the purpose of quantitative research, FIGIs are sometimes too granular. Companies often undergo corporate changes or restructurings that do not impact the share price or anything else relevant to quantitative research but nevertheless result in new identifiers being issued by the various standards agencies (ISIN, FIGI, etc.). Examples of such corporate events might include a real estate company converting to a REIT, a company moving its domicile from one country to another, or certain kinds of mergers and acquisitions. FIGIs are designed to support many different use cases. For typical back office purposes at banks and brokerages, the pre- and post-event companies really are two separate entities, so a new FIGI makes sense. But for research purposes this can split up what is logically a single security into multiple, artificially different securities.
Because FIGIs, ISINs, and other identifiers are highly granular, two different data providers may assign different identifiers to the same (logical) security, which can result in QuantRocket assigning different sids for each provider. For example, after a corporate event, one provider might continue to identify a security by its pre-event ISIN or FIGI, while another provider might use the post-event ISIN or FIGI. Because QuantRocket assigns sids based on whatever idenitifiers the source data provides, this may result in the security being assigned a different sid for one provider versus the other.
Thus, when mixing and matching data providers, it is best to picture a Venn diagram in which the great majority of sids lie within the overlapping region of the circles (that is, are identical for both providers), but a small number of sids lie in the areas outside the overlapping region.
Historical Price Data
Data collection overview
Historical data collection follows a common workflow for all data providers:
- Create an empty database that defines your historical data requirements (vendor, bar size, securities, etc.)
- Collect data from the data provider and store in the local database. The data will be collected according to the requirements you originally defined.
- Periodically collect data again to obtain updated history.
- Query data from the local database for use in your analysis and trading strategies.
You can create as many databases as you need.
This section describes the historical data collection workflow that is common to all vendors. For vendor-specific guidelines, see the respective section for each vendor.
Create history database
Create a database by choosing the vendor to use and defining the data collection parameters, which vary by vendor. You assign each database an alphanumeric code for easy reference. In this example, we create an end-of-day database for free sample US stock data:
$ quantrocket history create-usstock-db 'usstock-free-1d' --free
status: successfully created quantrocket.v2.history.usstock-free-1d.sqlite
>>> from quantrocket.history import create_usstock_db
>>> create_usstock_db("usstock-free-1d", free=True)
{'status': 'successfully created quantrocket.v2.history.usstock-free-1d.sqlite'}
$ curl -X PUT 'http://houston/history/databases/usstock-free-1d?vendor=usstock&free=true'
{"status": "successfully created quantrocket.v2.history.usstock-free-1d.sqlite"}
You can view the stored configuration parameters of a specific database:
$ quantrocket history config 'usstock-free-1d'
bar_size: 1 day
fields:
- Symbol
- Open
- High
- Low
- Close
- Volume
- Vwap
- TotalTrades
- UnadjOpen
- UnadjHigh
- UnadjLow
- UnadjClose
- UnadjVolume
- UnadjVwap
shard: year
universe: FREE
vendor: usstock
>>> from quantrocket.history import get_db_config
>>> get_db_config("usstock-free-1d")
{'vendor': 'usstock',
'universe': 'FREE',
'bar_size': '1 day',
'shard': 'year',
'fields': ['Symbol',
'Open',
'High',
'Low',
'Close',
'Volume',
'Vwap',
'TotalTrades',
'UnadjOpen',
'UnadjHigh',
'UnadjLow',
'UnadjClose',
'UnadjVolume',
'UnadjVwap']}
$ curl -X GET 'http://houston/history/databases/usstock-free-1d'
{"vendor": "usstock", "universe": "FREE", "bar_size": "1 day", "shard": "year", "fields": ["Symbol", "Open", "High", "Low", "Close", "Volume", "Vwap", "TotalTrades", "UnadjOpen", "UnadjHigh", "UnadjLow", "UnadjClose", "UnadjVolume", "UnadjVwap"]}
You can list your historical databases to see which ones you've created:
$ quantrocket history list
es-fut-1min
japan-stk-1d
uk-etf-15min
usstock-free-1d
usstock-1d
>>> from quantrocket.history import list_databases
>>> list_databases()
['es-fut-1min',
'japan-stk-1d',
'uk-etf-15min',
'usstock-free-1d',
'usstock-1d']
$ curl -X GET 'http://houston/history/databases'
["es-fut-1min", "japan-stk-1d", "uk-etf-15min", "usstock-free-1d", "usstock-1d"]
Collect history
After creating the database, you are ready to collect data:
$ quantrocket history collect 'usstock-free-1d'
status: the historical data will be collected asynchronously
>>> from quantrocket.history import collect_history
>>> collect_history("usstock-free-1d")
{'status': 'the historical data will be collected asynchronously'}
$ curl -X POST 'http://houston/history/queue?codes=usstock-free-1d'
{"status": "the historical data will be collected asynchronously"}
Data collection runs in the background. Progress is logged to flightlog, which you should monitor for completion status:
$ quantrocket flightlog stream
quantrocket.history: INFO [usstock-free-1d] Collecting FREE history from 2007-01 to present
quantrocket.history: INFO [usstock-free-1d] Collecting updated FREE securities listings
quantrocket.history: INFO [usstock-free-1d] Applying price adjustments for 6 securities
quantrocket.history: INFO [usstock-free-1d] Collected 160 monthly files in quantrocket.v2.history.usstock-free-1d.sqlite
Later, to bring the database current with new data, simply run data collection again. The update process will run faster than the initial data collection due to collecting fewer records.
You can use the countdown service to schedule your databases to be updated regularly.
Data collection queue
Multiple data collection requests will be queued and run sequentially. You can view the current queue, which is organized by vendor:
$ quantrocket history queue
edi: []
ibkr:
priority: []
standard: []
sharadar: []
usstock:
- usstock-free-1d
>>> quantrocket.history import get_history_queue
>>> get_history_queue()
{'edi': [],
'sharadar': [],
'usstock': ['usstock-free-1d'],
'ibkr': {'priority': [], 'standard': []}}
$ curl -X GET 'http://houston/history/queue'
{"edi": [], "sharadar": [], "usstock": ["usstock-free-1d"], "ibkr": {"priority": [], "standard": []}}
Delete history database
Once you've created a database, you can't edit the configuration; you can only add new databases. If you made a mistake or no longer need an old database, you can drop the database and its associated config:
$ quantrocket history drop-db 'usstock-free-1d' --confirm-by-typing-db-code-again 'usstock-free-1d'
status: deleted quantrocket.v2.history.usstock-free-1d.sqlite
>>> from quantrocket.history import drop_db
>>> drop_db("usstock-free-1d", confirm_by_typing_db_code_again="usstock-free-1d")
{'status': 'deleted quantrocket.v2.history.usstock-free-1d.sqlite'}
$ curl -X DELETE 'http://houston/history/databases/usstock-free-1d?confirm_by_typing_db_code_again=usstock-free-1d'
{"status": "deleted quantrocket.v2.history.usstock-free-1d.sqlite"}
Historical data file
The most convenient way to load historical data into Python is using the get_prices
function, which parses the data into a Pandas DataFrame and works for history databases, real-time aggregate databases, and Zipline bundles. This function is outlined in the Research section.
Alternatively, for a more raw approach, you can download a CSV file of historical data:
$ quantrocket history get 'usstock-free-1d' --start-date '2020-01-01' --fields 'Open' 'High' 'Low' 'Close' 'Volume' 'Vwap' | csvlook --max-rows 5
| Sid | Date | Open | High | Low | Close | Volume | Vwap |
| -------------- | ---------- | -------- | -------- | -------- | -------- | ---------- | -------- |
| FIBBG000GZQ728 | 2020-01-02 | 69.246… | 70.015… | 69.243… | 69.896… | 12,681,101 | 69.771… |
| FIBBG000BPH459 | 2020-01-02 | 158.348… | 160.292… | 157.899… | 160.182… | 22,634,546 | 159.341… |
| FIBBG000BMHYD1 | 2020-01-02 | 144.946… | 145.095… | 144.161… | 145.045… | 5,769,137 | 144.702… |
| FIBBG000B9XRY4 | 2020-01-02 | 295.539… | 299.888… | 294.491… | 299.639… | 33,911,864 | 297.733… |
| FIBBG00B3T3HD3 | 2020-01-02 | 21.860… | 21.860… | 21.315… | 21.420… | 3,097,556 | 21.474… |
| ... | ... | ... | ... | ... | ... | ... | ... |
>>> import pandas as pd
>>> from quantrocket.history import download_history_file
>>> download_history_file("usstock-free-1d",
start_date="2020-01-01",
fields=["Open", "High", "Low", "Close", "Volume", "Vwap"],
filepath_or_buffer="usstock_free_1d.csv")
>>> prices = pd.read_csv("usstock_free_1d.csv", parse_dates=["Date"])
>>> prices.head()
Sid Date Open High Low Close Volume Vwap
0 FIBBG000GZQ728 2020-01-02 69.2459 70.0148 69.2427 69.8965 12681101 69.7712
1 FIBBG000BPH459 2020-01-02 158.3475 160.2922 157.8987 160.1825 22634546 159.3413
2 FIBBG000BMHYD1 2020-01-02 144.9457 145.0948 144.1607 145.0451 5769137 144.7020
3 FIBBG000B9XRY4 2020-01-02 295.5386 299.8883 294.4911 299.6389 33911864 297.7330
4 FIBBG00B3T3HD3 2020-01-02 21.8600 21.8600 21.3150 21.4200 3097556 21.4739
$ curl -X GET 'http://houston/history/usstock-free-1d.csv?start_date=2020-01-01&fields=Open&fields=High&fields=Low&fields=Close&fields=Volume&fields=Vwap' | head
FIBBG000GZQ728,2020-01-02,69.2459,70.0148,69.2427,69.8965,12681101,69.7712
FIBBG000BPH459,2020-01-02,158.3475,160.2922,157.8987,160.1825,22634546,159.3413
FIBBG000BMHYD1,2020-01-02,144.9457,145.0948,144.1607,145.0451,5769137,144.702
FIBBG000B9XRY4,2020-01-02,295.5386,299.8883,294.4911,299.6389,33911864,297.733
FIBBG00B3T3HD3,2020-01-02,21.86,21.86,21.315,21.42,3097556,21.4739
EDI
To collect EDI price data, create a database by specifying one or more MICs (market identifier codes) to include in the database (for sample data, use the exchange code FREE
). This example creates a database that includes prices from the Shanghai Stock Exchange (XSHG) and Shenzhen Stock Exchange (XSHE):
$ quantrocket history create-edi-db 'china-1d' --exchanges 'XSHG' 'XSHE'
status: successfully created quantrocket.v2.history.china-1d.sqlite
>>> from quantrocket.history import create_edi_db
>>> create_edi_db("china-1d", exchanges=["XSHG", "XSHE"])
{'status': 'successfully created quantrocket.v2.history.china-1d.sqlite'}
$ curl -X PUT 'http://houston/history/databases/china-1d?vendor=edi&exchanges=XSHG&exchanges=XSHE'
{"status": "successfully created quantrocket.v2.history.china-1d.sqlite"}
Then collect the data:
$ quantrocket history collect 'china-1d'
status: the historical data will be collected asynchronously
>>> from quantrocket.history import collect_history
>>> collect_history("china-1d")
{'status': 'the historical data will be collected asynchronously'}
$ curl -X POST 'http://houston/history/queue?codes=china-1d'
{"status": "the historical data will be collected asynchronously"}
Monitor the status in flightlog:
quantrocket.history: INFO [china-1d] Collecting EDI XSHG history from 2007-01 to present
quantrocket.history: INFO [china-1d] Collecting updated EDI XSHG securities listings
quantrocket.history: INFO [china-1d] Collecting EDI XSHE history from 2007-01 to present
quantrocket.history: INFO [china-1d] Collecting updated EDI XSHE securities listings
quantrocket.history: INFO [china-1d] Applying price adjustments for 3648 securities
quantrocket.history: INFO [china-1d] Collected 320 monthly files in quantrocket.v2.history.china-1d.sqlite
For EDI databases, QuantRocket loads the raw prices and adjustments, then applies the adjustments in your local database. This design is optimized for efficiently collecting new data on an ongoing basis. However, the first time data is collected, applying adjustments can take awhile for large exchanges. For this reason, pre-built databases with adjustments already applied are available for select exchanges; QuantRocket will automatically check if this is the case.
EDI data guide
A sample record from the dataset is shown below:
Sid: "FIBBG000Q13NZ6"
Date: "2020-04-07"
Symbol: 510010
Open: 1.077
High: 1.105
Low: 1.077
Close: 1.093
Mid: 0
Ask: 1.093
Last: 0
Bid: 1.082
BidSize: 0
AskSize: 0
Volume: 86100
TradedValue: 93110
TotalTrades: 0
UnadjOpen: 1.077
UnadjHigh: 1.105
UnadjLow: 1.077
UnadjClose: 1.093
UnadjMid: 0
UnadjAsk: 1.093
UnadjLast: 0
UnadjBid: 1.082
UnadjVolume: 86100
Confirmed: 1
Note: VWAP can easily be calculated as TradedValue
/ Volume
. (For unadjusted VWAP, use TradedValue
/ UnadjVolume
.)
Split and dividend adjustments
EDI price data is split- and dividend-adjusted.
Primary vs consolidated prices
EDI price data is from the primary exchange.
Learn more about the difference between consolidated and primary exchange prices.
Delisted stocks
EDI price data includes stocks that delisted due to bankruptcies, mergers and acquisitions, etc.
Update schedule
EDI is updated on a rolling basis as the data becomes available from the exchange.
Point-in-time ticker symbols
There is a Symbol
column in the EDI price data as well as a Symbol
column (and edi_LocalSymbol
column) in the securities master file. The Symbol
column in the price data contains the ticker code provided by the exchange, while the Symbol
/edi_LocalSymbol
column in the securities master file contains the canonical ticker for the security as determined by EDI. Usually these are the same but sometimes they may differ. In addition, the price data Symbol
column is point-in-time, that is, it does not change even if the security subsequently undergoes a ticker change. In contrast, the securities master Symbol
/edi_LocalSymbol
columns always reflect the security's latest ticker symbol.
Interactive Brokers
To collect historical data from Interactive Brokers, you must first collect securities master listings from Interactive Brokers. It is not sufficient to have collected the listings from another vendor; specific IBKR fields must be present in the securities master database. To check if you have collected IBKR listings, query the securities master and make sure the ibkr_ConId
field is populated:
$ quantrocket master get --symbols 'AAPL' --fields 'Symbol' 'ibkr_ConId' | csvlook -I
| Sid | Symbol | ibkr_ConId |
| -------------- | ------ | ---------- |
| FIBBG000B9XRY4 | AAPL | 265598 |
>>> from quantrocket.master import get_securities
>>> securities = get_securities(symbols="AAPL", fields=["Symbol", "ibkr_ConId"])
>>> securities.head()
Symbol ibkr_ConId
Sid
FIBBG000B9XRY4 AAPL 265598
$ curl -X GET 'http://houston/master/securities.csv?symbols=AAPL&fields=Symbol&fields=ibkr_ConId' | csvlook -I
| Sid | Symbol | ibkr_ConId |
| -------------- | ------ | ---------- |
| FIBBG000B9XRY4 | AAPL | 265598 |
Once you have collected securities master listings from IBKR for the securities that interest you, you can create your historical database. Interactive Brokers provides a large variety of historical market data and thus there are numerous configuration options for IBKR history databases. At minimum, you must specify a bar size and one or more sids or universes:
$ quantrocket history create-ibkr-db 'japan-bank-eod' --universes 'japan-bank' --bar-size '1 day'
status: successfully created quantrocket.v2.history.japan-bank-eod.sqlite
>>> from quantrocket.history import create_ibkr_db
>>> create_ibkr_db("japan-bank-eod", universes=["japan-bank"], bar_size="1 day")
{'status': 'successfully created quantrocket.v2.history.japan-bank-eod.sqlite'}
$ curl -X PUT 'http://houston/history/databases/japan-bank-eod?universes=japan-bank&bar_size=1+day&vendor=ibkr'
{"status": "successfully created quantrocket.v2.history.japan-bank-eod.sqlite"}
Then collect the data:
$ quantrocket history collect 'japan-bank-eod'
status: the historical data will be collected asynchronously
>>> from quantrocket.history import collect_history
>>> collect_history("japan-bank-eod")
{'status': 'the historical data will be collected asynchronously'}
$ curl -X POST 'http://houston/history/queue?codes=japan-bank-eod'
{"status": "the historical data will be collected asynchronously"}
QuantRocket will first query the IBKR API to determine how far back historical data is available for each security, then query the IBKR API again to collect the data for that date range. Depending on the bar size and the number of securities in the universe, collecting data can take from several minutes to several hours. If you're running multiple IB Gateway services, QuantRocket will spread the requests among the services to speed up the process. Based on how quickly the IBKR API is responding to requests, QuantRocket will periodically estimate how long it will take to collect the data. Monitor flightlog to track progress:
$ quantrocket flightlog stream
quantrocket.history: INFO [japan-bank-eod] Determining how much history is available from IBKR for japan-bank-eod
quantrocket.history: INFO [japan-bank-eod] Collecting history from IBKR for japan-bank-eod
quantrocket.history: INFO [japan-bank-eod] Expected remaining runtime to collect japan-bank-eod history based on IBKR response times so far: 0:23:11
quantrocket.history: INFO [japan-bank-eod] Saved 468771 total records for 85 total securities to quantrocket.v2.history.japan-bank-eod.sqlite
In addition to bar size and universe(s), you can optionally define the type of data you want (for example, trades, bid/ask, midpoint, etc.), a fixed start date instead of "as far back as possible", whether to include trades from outside regular trading hours, whether to use consolidated prices or primary exchange prices, and more. For a complete list of options, view the command or function help or the API Reference.
Cancel collections
Because IBKR historical data collection can be long-running, there is support for canceling a pending or running collection:
$ quantrocket history cancel 'japan-bank-eod'
edi: []
ibkr:
priority: []
standard: []
sharadar: []
usstock: []
>>> from quantrocket.history import cancel_collections
>>> cancel_collections(codes="japan-bank-eod")
{'edi': [],
'sharadar': [],
'usstock': [],
'ibkr': {'priority': [], 'standard': []}}
$ curl -X DELETE 'http://houston/history/queue?codes=japan-bank-eod'
{"edi": [], "sharadar": [], "usstock": [], "ibkr": {"priority": [], "standard": []}}
The output returns the data collection queue after cancellation.
Priority queue
Due to rate limits on data collection enforced by the IBKR API, only one IBKR data collection can run at a time (additional requests will be queued). To maximize flexibility, there is a standard queue and a priority queue for Interactive Brokers. The standard queue will only be processed when the priority queue is empty. This can be useful when you're trying to collect a large amount of historical data for backtesting but you don't want it to interfere with daily updates to the databases you use for trading. First, schedule your daily updates on your countdown (cron) service, using the --priority
flag to route them to the priority queue:
30 17 * * mon-fri quantrocket history collect --priority 'es-fut-1min'
Then, queue your long-running requests on the standard queue:
$ quantrocket history collect 'asx-stk-15min'
At 5:30pm, when a request is queued on the priority queue, the long-running request on the standard queue will pause until the priority queue is empty again, and then resume.
IBKR data guide
Split adjustments
All IBKR historical data is split-adjusted.
If a split occurs after the initial data collection, the locally stored data needs to be adjusted for the split. QuantRocket handles this by comparing a recent price in the database to the equivalently-timestamped price from IBKR. If the prices differ, this indicates either that a split has occurred or in some other way the vendor has adjusted their data since QuantRocket stored it. Regardless of the reason, QuantRocket deletes the data for that particular security and re-collects the entire history from IBKR, in order to make sure the database stays synced with IBKR.
Dividend adjustments
By default, IBKR historical data is not dividend-adjusted. However, dividend-adjusted data is available using the ADJUSTED_LAST
bar type. This bar type has an important limitation: it is only available with a 1 day
bar size.
$ quantrocket history create-ibkr-db 'asx-stk-1d' --universes 'asx-stk' --bar-size '1 day' --bar-type 'ADJUSTED_LAST'
status: successfully created quantrocket.v2.history.asx-stk-1d.sqlite
>>> from quantrocket.history import create_ibkr_db
>>> create_ibkr_db("asx-stk-1d", universes=["asx-stk"], bar_size="1 day", bar_type="ADJUSTED_LAST")
{'status': 'successfully created quantrocket.v2.history.asx-stk-1d.sqlite'}
$ curl -X PUT 'http://houston/history/databases/asx-stk-1d?universes=asx-stk&bar_size=1+day&bar_type=ADJUSTED_LAST&vendor=ibkr'
{"status": "successfully created quantrocket.v2.history.us-stk-1d.sqlite"}
With ADJUSTED_LAST
, QuantRocket handles dividend adjustments in the same way it handles split adjustments: whenever IBKR applies a dividend adjustment, QuantRocket will detect the discrepancy between the IBKR data and the locally stored data, and will delete the stored data and re-sync with IBKR.
Primary vs consolidated prices
By default, IBKR returns consolidated prices for equities. You can instruct QuantRocket to collect primary exchange prices instead of consolidated prices using the --primary-exchange
option. This instructs IBKR to filter out trades that didn't take place on the primary listing exchange for the security:
$ quantrocket history create-ibkr-db 'us-stk-1d-primary' --universes 'us-stk' --bar-size '1 day' --primary-exchange
status: successfully created quantrocket.v2.history.us-stk-1d-primary.sqlite
>>> from quantrocket.history import create_ibkr_db
>>> create_ibkr_db("us-stk-1d-primary", universes=["us-stk"], bar_size="1 day", primary_exchange=True)
{'status': 'successfully created quantrocket.v2.history.us-stk-1d-primary.sqlite'}
$ curl -X PUT 'http://houston/history/databases/us-stk-1d-primary?universes=us-stk&bar_size=1 day&primary_exchange=true&vendor=ibkr'
{"status": "successfully created quantrocket.v2.history.us-stk-1d-primary.sqlite"}
Learn more about the tradeoffs between consolidated and primary exchange prices.
Collecting consolidated historical data typically requires IBKR market data permissions for all the exchanges where trades occurred. Collecting data with the primary exchange filter typically only requires IBKR market data permission for the primary exchange.
Bar sizes
IBKR offers over 20 bar sizes ranging from 1 month to 1 second. The full list includes: 1 month, 1 week, 1 day, 8 hours, 4 hours, 3 hours, 2 hours, 1 hour, 30 mins, 20 mins, 15 mins, 10 mins, 5 mins, 3 mins, 2 mins, 1 min, 30 secs, 15 secs, 10 secs, 5 secs, and 1 secs.
Types of data
You can use the --bar-type
parameter with create-ibkr-db
to indicate what type of historical data you want:
Bar type | Description | Available for | Notes |
---|
TRADES | traded price | stocks, futures, options, FX, indexes | adjusted for splits but not dividends |
ADJUSTED_LAST | traded price | stocks | adjusted for splits and dividends |
MIDPOINT | bid-ask midpoint | stocks, futures, options, FX | the open, high, low, and closing midpoint price |
BID | bid | stocks, futures, options, FX | the open, high, low, and closing bid price |
ASK | ask | stocks, futures, options, FX | the open, high, low, and closing ask price |
BID_ASK | time-average bid and ask | stocks, futures, options, FX | time-average bid is stored in the Open field, and time-average ask is stored in the Close field; the High and Low fields contain the max ask and min bid, respectively |
HISTORICAL_VOLATILITY | historical volatility | stocks, indexes | 30 day Garman-Klass volatility of corporate action adjusted data |
OPTION_IMPLIED_VOLATILITY | implied volatility | stocks, indexes | IBKR calculates implied volatility as follows: "The IBKR 30-day volatility is the at-market volatility estimated for a maturity thirty calendar days forward of the current trading day, and is based on option prices from two consecutive expiration months." |
If --bar-type
is omitted, it defaults to MIDPOINT
for FX and TRADES
for everything else.
How far back historical data goes
For stocks and currencies, IBKR historical data depth varies by exchange and bar size. End of day prices go back as far as 1980 for some exchanges, while intraday prices down to 1-minute bars go back as far as 2004. The amount of data available from the IBKR API is the same as the amount of data available when viewing the corresponding chart in Trader Workstation.
For futures, historical data is available for contracts that expired no more than 2 years ago. IBKR removes historical futures data from its system 2 years after the contract expiration date. Deeper historical data is available for indices. Thus, for futures contracts with a corresponding index (and for which backwardation and contango are negligible factors), you can run deeper backtests on the index then switch to the futures contract for recent backtests or live trading.
For bar sizes of 30 seconds or smaller, historical data goes back 6 months only.
Intraday data collection
Initial data collection runtime
Depending on the bar size, number of securities, and date range of your historical database, initial data collection from the IBKR API can take some time. After the initial data collection, keeping your database up to date is much faster and much easier.
QuantRocket fills your historical database by making a series of requests to the IBKR API to get a portion of the data, from earlier data to later data. The smaller the bars, the more requests are required to collect all the data.
If you run multiple IB Gateways, each with appropriate IB market data subscriptions, QuantRocket splits the requests between the gateways which results in a proportionate reduction in runtime.
IBKR API response times also vary by the monthly commissions generated on the account. Accounts with monthly commissions of several thousand USD/month or higher will see response times which are about twice as fast as those for small accounts (or for large accounts with small commissions).
The following table shows estimated runtimes and database sizes for a variety of historical database configurations:
Bar size | Number of stocks | Years of data | Example universes | Runtime (high commission account, 4 IB Gateways) | Runtime (standard account, 2 IB Gateways) | Database size |
---|
1 day | 3,000 | all available (1980-present) | Tokyo Stock Exchange or London Stock Exchange | 1.5 hours | 6 hours | 1.25 GB |
15 minutes | 3,000 | all available (2004-present) | Tokyo Stock Exchange or London Stock Exchange | 1.5 days | 1 week | 25 GB |
1 minute | 3,000 | 5 years | Tokyo Stock Exchange or London Stock Exchange | 1 week | 1 month | 150 GB |
You can use the table above to infer the collection times for other bar sizes and universe sizes.
Data collection strategies
Below are several data collection strategies that may help speed up data collection, reduce the amount of data you need to collect, or allow you to begin working with a subset of data while collecting the full amount of data.
Run multiple IB Gateways
You can cut down initial data collection time by running multiple IB gateways. See the section on obtaining and using multiple IB logins.
Daily bars before intraday bars
Suppose you want to collect intraday bars for the top 500 liquid securities trading on ASX. Instead of collecting intraday bars for all ASX securities then filtering out illiquid ones, you could try this approach:
- collect a year's worth of daily bars for all ASX securities (this requires only 1 request to the IBKR API per security and will run much faster than collecting multiple years of intraday bars)
- in a notebook, query the daily bars and use them to calculate dollar volume, then create a universe of liquid securities only
- collect intraday bars for the universe of liquid securities only
You can periodically repeat this process to update the universe constituents.
Filter by availability of fundamentals
Suppose you have a strategy that requires intraday bars and fundamental data and utilizes a universe of small-cap stocks. For some small-cap stocks, fundamental data might not be available, so it doesn't make sense to spend time collecting intraday historical data for stocks that won't have fundamental data. Instead, collect the fundamental data first and filter your universe to stocks with fundamentals, then collect the historical intraday data. For example:
- create a universe of all Japanese small-cap stocks called 'japan-sml'
- collect fundamentals for the universe 'japan-sml'
- in a notebook, query the fundamentals for 'japan-sml' and use the query results to create a new universe called 'japan-sml-with-fundamentals'
- collect intraday price history for 'japan-sml-with-fundamentals'
Earlier history before later history
Suppose you want to collect numerous years of intraday bars. But you'd like to test your ideas on a smaller date range first in order to decide if collecting the full history is worthwhile. This can be done as follows. First, define your desired start date when you create the database:
$ quantrocket history create-ibkr-db 'hong-kong-liquid-15min' -u 'hong-kong-liquid' -z '15 mins' -s '2011-01-01'
The above database is designed to collect data back to 2011-01-01 and up to the present. However, you can temporarily specify an end date when collecting the data:
$ quantrocket history collect 'hong-kong-liquid-15min' -e '2012-01-01'
In this example, only a year of data will be collected (that is, from the start date of 2011-01-01 specified when the database was created to the end date of 2012-01-01 specified in the above command). That way you can start your research sooner. Later, you can repeat this command with a later end date or remove the end date entirely to bring the database current.
In contrast, it's a bad idea to use a temporary start date to shorten the date range and speed up the data collection, with the intention of going back later to get the earlier data. Since data is filled from back to front (that is, from older dates to newer), once you've collected a later portion of data for a given security, you can't append an earlier portion of data without starting over.
Database per decade
Data for some securities goes back 30 years or more. After testing on recent data, you might want to explore earlier years. While you can't append earlier data to an existing database, you can collect the earlier data in a completely separate database. Depending on your bar size and universe size, you might create a separate database for each decade. These databases would be for backtesting only and, after the initial data collection, would not need to be updated. Only your database of the most recent decade would need to be updated.
Small universes before large universes
Another option to get you researching and backtesting sooner is to collect a subset of your target universe before collecting the entire universe. For example, instead of collecting intraday bars for 1000 securities, collect bars for 100 securities and start testing with those while collecting the remaining data.
Time filters
When creating a historical database of intraday bars, you can use the times
or between-times
options to filter out unwanted bars.
For example, it's usually a good practice to explicitly specify the session start and end times, as the IBKR API sometimes sends a small number of bars from outside regular trading hours, and any trading activity from these bars will be included in the cumulative daily totals calculated by QuantRocket. The following command instructs QuantRocket to keep only those bars that fall between 9:00 and 14:45, inclusive. (Note that bar times correspond to the start of the bar, so the final bar for Japan stocks using 15-min bars would be 14:45:00
, since the Tokyo Stock Exchange closes at 15:00.)
$ quantrocket history create-ibkr-db 'japan-stk-15min' --universes 'japan-stk' --bar-size '15 mins' --between-times '09:00:00' '14:45:00'--shard 'time'
status: successfully created quantrocket.v2.history.japan-stk-15min.sqlite
>>> from quantrocket.history import create_ibkr_db
>>> create_ibkr_db("japan-stk-15min", universes=["japan-stk"], bar_size="15 mins", between_times=["09:00:00", "14:45:00"], shard="time")
{'status': 'successfully created quantrocket.v2.history.japan-stk-15min.sqlite'}
$ curl -X PUT 'http://houston/history/databases/japan-stk-15min?universes=japan-stk&bar_size=15+mins&between_times=09%3A00%3A00&between_times=14%3A45%3A00&shard=time&vendor=ibkr'
{"status": "successfully created quantrocket.v2.history.japan-stk-15min.sqlite"}
You can view the database config to see how QuantRocket expanded the between-times
values into an explicit list of times to keep:
$ quantrocket history config 'japan-stk-15min'
bar_size: 15 mins
fields:
- Open
- High
- Low
- Close
- Volume
- Wap
- TradeCount
- DayHigh
- DayLow
- DayVolume
shard: time
times:
- '09:00:00'
- '09:15:00'
- '09:30:00'
- '09:45:00'
- '10:00:00'
- '10:15:00'
- '10:30:00'
- '10:45:00'
- '11:00:00'
- '11:15:00'
- '11:30:00'
- '11:45:00'
- '12:00:00'
- '12:15:00'
- '12:30:00'
- '12:45:00'
- '13:00:00'
- '13:15:00'
- '13:30:00'
- '13:45:00'
- '14:00:00'
- '14:15:00'
- '14:30:00'
- '14:45:00'
universes:
- japan-stk
vendor: ibkr
>>> from quantrocket.history import get_db_config
>>> get_db_config("japan-stk-15min")
{'universes': ['japan-stk'],
'vendor': 'ibkr',
'bar_size': '15 mins',
'shard': 'time',
'times': ['09:00:00',
'09:15:00',
'09:30:00',
'09:45:00',
'10:00:00',
'10:15:00',
'10:30:00',
'10:45:00',
'11:00:00',
'11:15:00',
'11:30:00',
'11:45:00',
'12:00:00',
'12:15:00',
'12:30:00',
'12:45:00',
'13:00:00',
'13:15:00',
'13:30:00',
'13:45:00',
'14:00:00',
'14:15:00',
'14:30:00',
'14:45:00'],
'fields': ['Open',
'High',
'Low',
'Close',
'Volume',
'Wap',
'TradeCount',
'DayHigh',
'DayLow',
'DayVolume']}
$ curl 'http://houston/history/databases/japan-stk-15min'
{"universes": ["japan-stk"], "vendor": "ibkr", "bar_size": "15 mins", "shard": "time", "times": ["09:00:00", "09:15:00", "09:30:00", "09:45:00", "10:00:00", "10:15:00", "10:30:00", "10:45:00", "11:00:00", "11:15:00", "11:30:00", "11:45:00", "12:00:00", "12:15:00", "12:30:00", "12:45:00", "13:00:00", "13:15:00", "13:30:00", "13:45:00", "14:00:00", "14:15:00", "14:30:00", "14:45:00"], "fields": ["Open", "High", "Low", "Close", "Volume", "Wap", "TradeCount", "DayHigh", "DayLow", "DayVolume"]}
More selectively, if you know you only care about particular times, you can keep only those times, which will result in a smaller, faster database:
$ quantrocket history create-ibkr-db 'japan-stk-15min' --universes 'japan-stk' --bar-size '15 mins' --times '09:00:00' '09:15:00' '10:00:00' '14:45:00' --shard 'time'
status: successfully created quantrocket.v2.history.japan-stk-15min.sqlite
>>> from quantrocket.history import create_ibkr_db
>>> create_ibkr_db("japan-stk-15min", universes=["japan-stk"], bar_size="15 mins", times=["09:00:00", "09:15:00", "10:00:00", "14:45:00"], shard="time")
{'status': 'successfully created quantrocket.v2.history.japan-stk-15min.sqlite'}
$ curl -X PUT 'http://houston/history/databases/japan-stk-15min?universes=japan-stk&bar_size=15+mins×=09%3A00%3A00×=09%3A15%3A00×=10%3A00%3A00×=14%3A45%3A00&shard=time&vendor=ibkr'
{"status": "successfully created quantrocket.v2.history.japan-stk-15min.sqlite"}
The downside of keeping only a few times is that you'll have to collect data again if you later decide you want to analyze prices at other times of the session. An alternative is to save all the times but filter by time when querying the data.
Database sharding
Database sharding is only applicable to intraday databases.
Summary of sharding options
| Suitable for queries that | Suitable for backtesting |
---|
shard by year, month, or day | load many securities and many bar times but only a small date range at a time | Moonshot strategies that trade throughout the day, and/or segmented backtests |
shard by time of day | load many securities but only a few bar times at a time | intraday Moonshot strategies that trade once a day |
shard by sid | load a few securities but many bar times and a large date range at a time | Zipline strategies |
shard by sid and time (uses 2x disk space) | load many securities but only a few bar times, or load a few securities but many bar times | intraday Moonshot strategies that trade once a day, or Zipline strategies |
no sharding | load small universes | strategies that use small universes |
More detailed descriptions are provided below.
What is sharding?
In database design, "sharding" refers to dividing a large database into multiple smaller databases, with each smaller database or "shard" containing a subset of the total database rows. A collection of database shards typically performs better than a single large database by allowing more efficient queries. When a query is run, the rows from each shard are combined into a single result set as if they came from a single database.
Very large databases are too large to load entirely into memory, and sharding doesn't circumvent this. Rather, the purpose of sharding is to allow you to efficiently query the particular subset of data you're interested in at the moment.
When you query a sharded database using a filter that corresponds to the sharding scheme (for example, filtering by time for a time-sharded database, or filtering by sid for a sid-sharded database), the query runs faster because it only needs to look in the subset of relevant shards based on the query parameters.
To get the benefit of improved query performance, the sharding scheme must correspond to how you will usually query the database; thus it is necessary to think about this in advance.
A secondary benefit of sharding is that smaller database files are easier to move around, including copying them to and from S3.
Choose sharding option
For intraday databases, you must indicate your sharding option at the time you create the database:
$
$ quantrocket history create-ibkr-db 'uk-stk-15min' --universes 'uk-stk' --bar-size '15 mins' --shard 'sid,time'
status: successfully created quantrocket.v2.history.uk-stk-15min.sqlite
>>>
>>> from quantrocket.history import create_ibkr_db
>>> create_ibkr_db("uk-stk-15min", universes=["uk-stk"], bar_size="15 mins", shard="sid,time")
{'status': 'successfully created quantrocket.v2.history.uk-stk-15min.sqlite'}
$
$ curl -X PUT 'http://houston/history/databases/uk-stk-15min?universes=uk-stk&bar_size=15%20mins&shard=sid,time'
{"status": "successfully created quantrocket.v2.history.uk-stk-15min.sqlite"}
The choices are:
- year
- month
- day
- time
- sid
- sid,time
- off
Sharded database storage
If you list a sharded database using the --expand
/expand=True
parameter, you'll see a separate database file for each time or sid shard:
$
$ quantrocket db list --services 'history' --codes 'uk-stk-15min' --expand
quantrocket.v2.history.uk-stk-15min.093000.sqlite
quantrocket.v2.history.uk-stk-15min.094500.sqlite
...
$
$ quantrocket db list --services 'history' --codes 'uk-stk-1min' --expand
quantrocket.v2.history.uk-stk-1min.100248135.sqlite
quantrocket.v2.history.uk-stk-1min.100296007.sqlite
quantrocket.v2.history.uk-stk-1min.100296028.sqlite
...
Shard by year, month, or day
Sharding by year, month, or day results in a separate database shard for each year, month, or day of data, with each separate database containing all securities for only that time period. The number of shards is equal to the number of years, months, or days of data collected, respectively.
As a broad guideline, if collecting 1-minute bars, sharding by year would be suitable for a universe of tens of securities, sharding by month would be suitable for a universe of hundreds of securities, and sharding by day would be suitable for a universe of thousands of securities.
Sharding by year, month, or day is a sensible approach when you need to analyze the entire universe of securities but only for a small date range at a time. This approach pairs well with segmented backtests in Moonshot.
Shard by time
Sharding by time results in a separate database shard for each time of day. For example, assuming 15-minute bars, there will be a separate database for 09:30:00 bars, 09:45:00 bars, etc. (with each separate database containing all dates and all securities for only that bar time). The number of shards is equal to the number of bar times per day.
Sharding by time is an efficient approach when you are working with a large universe of securities but only need to query a handful of times for any given analysis. For example, the following query would run efficiently on a time-sharded database because it only needs to look in 3 shards:
>>> prices = get_prices("uk-stk-15min", times=["09:30:00", "12:00:00", "15:45:00"])
Sharding by time is well-suited to intraday Moonshot strategies that trade once a day, since such strategies typically only utilize a subset of bar times.
Sharding by sid
Sharding by sid results in a separate database shard for each security. Each shard will contain the entire date range and all bar times for a single security. The number of shards is equal to the number of securities in the universe.
Sharding by sid is an efficient approach when you need to query bars for all times of day but can do so for one or a handful of securities at a time. For example, the following query would run efficiently on a sid-sharded database because it only needs to look in 1 shard:
>>> bp_prices = get_prices("uk-stk-1min", sids="FIBBG000C059M6")
Sharding by sid is well-suited for ingesting data into Zipline for backtesting because Zipline ingests data one security at a time.
Sharding by sid and time
Sharding by sid and time results in duplicate copies of the database, one sharded by time and one by sid. QuantRocket will look in whichever copy of the database allows for the most efficient query based on your query parameters, that is, whichever copy allows looking in the fewest number of shards. For example, if you query prices at a few times of day for many securities, QuantRocket will use the time-sharded database to satisfy your request; if you query prices for many times of day for a few securities, QuantRocket will use the sid-sharded database to satisfy your request:
>>>
>>>
>>>
>>>
>>> prices = get_prices("uk-stk-15min", times=["09:30:00", "12:00:00", "15:45:00"])
>>>
>>>
>>>
>>> prices = get_prices("usa-stk-15min", sids=["FIBBG000C059M6", "FIBBG000BF46K3"])
Sharding by time and by sid allows for more flexible querying but requires double the disk space. It may also increase collection runtime due to the larger volume of data that must be written to disk.
Sharadar
Sharadar price data can be collected as a history database or a Zipline bundle. Generally, the Zipline bundle is preferred because it allows you to collect stocks and ETFs in the same bundle (assuming you have the appropriate data subscriptions), while the Sharadar history database only supports one security type per database (stocks OR ETFs) and thus requires maintaining two databases to access the full US stock market.
Sharadar Zipline bundle
To collect the Sharadar Zipline bundle for stocks and ETFs, first create the bundle:
$ quantrocket zipline create-sharadar-bundle 'sharadar-1d'
msg: successfully created sharadar-1d bundle
status: success
>>> from quantrocket.zipline import create_sharadar_bundle
>>> create_sharadar_bundle("sharadar-1d")
{'status': 'success', 'msg': 'successfully created sharadar-1d bundle'}
$ curl -X PUT 'http://houston/zipline/bundles/sharadar-1d?ingest_type=sharadar'
{"status": "success", "msg": "successfully created sharadar-1d bundle"}
If you only subscribe to a single security type (stocks or ETFs), use the --sec-types
/sec_types
parameter to specify the appropriate choice:
$ quantrocket zipline create-sharadar-bundle 'sharadar-stk-1d' --sec-types 'STK'
msg: successfully created sharadar-stk-1d bundle
status: success
>>> create_sharadar_bundle("sharadar-stk-1d", sec_types="STK")
{'status': 'success', 'msg': 'successfully created sharadar-stk-1d bundle'}
$ curl -X PUT 'http://houston/zipline/bundles/sharadar-stk-1d?ingest_type=sharadar&sec_types=STK'
{"status": "success", "msg": "successfully created sharadar-stk-1d bundle"}
Alternatively, for free sample data, use the --free
/free=True
parameter:
$ quantrocket zipline create-sharadar-bundle 'sharadar-free-1d' --free
msg: successfully created sharadar-free-1d bundle
status: success
>>> create_sharadar_bundle("sharadar-free-1d", free=True)
{'status': 'success', 'msg': 'successfully created sharadar-free-1d bundle'}
$ curl -X PUT 'http://houston/zipline/bundles/sharadar-free-1d?ingest_type=sharadar&free=true'
{"status": "success", "msg": "successfully created sharadar-free-1d bundle"}
The bundle is empty when created, so the next step is to ingest (i.e. collect) the actual data, using the bundle name you specified:
$ quantrocket zipline ingest 'sharadar-1d'
status: the data will be ingested asynchronously
>>> from quantrocket.zipline import ingest_bundle
>>> ingest_bundle("sharadar-1d")
{'status': 'the data will be ingested asynchronously'}
$ curl -X POST 'http://houston/zipline/ingestions/sharadar-1d'
{"status": "the data will be ingested asynchronously"}
Collecting the data takes a minute or two. Monitor the status in flightlog:
quantrocket.zipline: INFO [sharadar-1d] Ingesting daily bars for sharadar-1d bundle
quantrocket.zipline: INFO [sharadar-1d] Ingesting adjustments for sharadar-1d bundle
quantrocket.zipline: INFO [sharadar-1d] Ingesting assets for sharadar-1d bundle
quantrocket.zipline: INFO [sharadar-1d] Completed ingesting data for sharadar-1d bundle
Sharadar history database
To collect Sharadar price data in a history database, specify the security type (STK
or ETF
) and the country (US
for the full dataset, or FREE
for sample data):
$ quantrocket history create-sharadar-db 'sharadar-us-stk-1d' --sec-type 'STK' --country 'US'
status: successfully created quantrocket.v2.history.sharadar-us-stk-1d.sqlite
>>> from quantrocket.history import create_sharadar_db
>>> create_sharadar_db("sharadar-us-stk-1d", sec_type="STK", country="US")
{'status': 'successfully created quantrocket.v2.history.sharadar-us-stk-1d.sqlite'}
$ curl -X PUT 'http://houston/history/databases/sharadar-us-stk-1d?vendor=sharadar&sec_type=STK&country=US'
{"status": "successfully created quantrocket.v2.history.sharadar-us-stk-1d.sqlite"}
Then collect the data:
$ quantrocket history collect 'sharadar-us-stk-1d'
status: the historical data will be collected asynchronously
>>> from quantrocket.history import collect_history
>>> collect_history("sharadar-us-stk-1d")
{'status': 'the historical data will be collected asynchronously'}
$ curl -X POST 'http://houston/history/queue?codes=sharadar-us-stk-1d'
{"status": "the historical data will be collected asynchronously"}
Collecting the full dataset the first time takes approximately 10-15 minutes. Monitor the status in flightlog:
quantrocket.history: INFO [sharadar-us-stk-1d] Collecting Sharadar US STK prices
quantrocket.history: INFO [sharadar-us-stk-1d] Collecting updated Sharadar US securities listings
quantrocket.history: INFO [sharadar-us-stk-1d] Finished collecting Sharadar US STK prices
Sharadar data guide
A snippet of the dataset is shown below:
| Sid | Date | Open | High | Low | Close | Volume | CloseUnadj | Dividends | LastUpdated |
| -------------- | ---------- | ----- | ------ | ------ | ------ | ---------- | ---------- | --------- | ----------- |
| FIBBG000C2V3D6 | 2020-04-06 | 72.97 | 74.990 | 72.245 | 74.360 | 2,311,703 | 74.360 | | 2020-04-06 |
| FIBBG00B3T3HD3 | 2020-04-06 | 6.37 | 6.840 | 6.250 | 6.550 | 9,887,881 | 6.550 | | 2020-04-06 |
| FIBBG000V2S3P6 | 2020-04-06 | 0.95 | 0.950 | 0.936 | 0.945 | 3,532 | 0.945 | | 2020-04-06 |
| FIBBG001R3QP52 | 2020-04-06 | 35.62 | 37.110 | 35.620 | 37.110 | 414,424 | 37.110 | | 2020-04-06 |
| FIBBG005P7Q881 | 2020-04-06 | 9.72 | 9.940 | 9.110 | 9.500 | 93,272,261 | 9.500 | | 2020-04-06 |
(Note that the Dividends
column included in the dataset is always empty. Historically, Sharadar data was not dividend-adjusted but provided dividends in a separate column. Now, Sharadar data is dividend-adjusted and the Dividends
column is empty, but the column is retained for backwards compatibility.)
Split and dividend adjustments
Sharadar price data is split- and dividend-adjusted.
There is a subtle difference in how adjustments are applied in the Sharadar history database vs the Sharadar Zipline bundle.
In the history database, all available adjustments are applied to the data at the time of collection, and the data are stored in an adjusted state. In the Zipline bundle, data are stored unadjusted, and adjustments are applied on-the-fly at query time. Moreover, Zipline only applies those adjustments that would have occurred on or before the end date of your query.
Both of these approaches result in a continuous price series that is free of artificial jumps and is suitable for quantitative analysis. However, depending on the date range of your query, the absolute price level may differ based on whether you query the Zipline bundle or the history database. To illustrate with an example, Apple stock underwent a 4-for-1 split on August 31, 2020. The price before the split was around $500, while the price after the split was around $125. If you query the period just before (but not including) the split date, the history database will return a price of around $125 (the split-adjusted price), because the 4-for-1 split will have already been applied to the stored data. In contrast, the Zipline bundle will return a price of around $500, because the 4-for-1 split falls after the query window and thus Zipline does not apply that particular split at query time. For most use cases, this distinction is immaterial. But if your analysis depends on the absolute price level, the Zipline bundle may be preferred because the absolute prices more accurately reflect their historical point-in-time values.
Primary vs consolidated prices
Sharadar price data is consolidated, that is, represents the combined trading activity across US exchanges.
Learn more about the difference between consolidated and primary exchange prices.
Delisted stocks
Sharadar price data includes stocks that delisted due to bankruptcies, mergers and acquisitions, etc.
Update schedule
The Sharadar dataset is usually updated by 7 PM New York time. Occasionally it is delayed, in which case it will be updated by 5 AM the following morning.
US Stock
The US Stock dataset is available to all QuantRocket customers and provides end-of-day and 1-minute intraday historical prices, with history back to 2007.
US Stock data guide
A sample record from the end-of-day dataset is shown below:
Sid: "FIBBG000B9XRY4"
Date: "2020-04-06"
Symbol: "AAPL"
Open: 250.9
High: 263.11
Low: 249.38
Close: 262.47
Volume: 50455071
Vwap: 256.1566
TotalTrades: 486681
UnadjOpen: 250.9
UnadjHigh: 263.11
UnadjLow: 249.38
UnadjClose: 262.47
UnadjVolume: 50455071
UnadjVwap: 256.1566
A snippet from the intraday dataset is shown below:
| Field | Date | FIBBG00B3T3HD3 | FIBBG000B9XRY4 | FIBBG000BKZB36 | FIBBG000BMHYD1 |
| ------ | ------------------------- | -------------- | -------------- | -------------- | -------------- |
| Close | 2020-03-20 09:31:00-04:00 | 6.04 | 248.08 | 163.35 | 125.98 |
| High | 2020-03-20 09:31:00-04:00 | 6.145 | 248.96 | 163.4 | 126.25 |
| Low | 2020-03-20 09:31:00-04:00 | 5.96 | 246.84 | 162.075 | 125.73 |
| Open | 2020-03-20 09:31:00-04:00 | 6.13 | 247.63 | 162.696 | 126.0 |
| Volume | 2020-03-20 09:31:00-04:00 | 23756.0 | 208466.0 | 31806.0 | 50147.0 |
Split and dividend adjustments
US Stock price data is split- and dividend-adjusted.
Primary vs consolidated prices
US Stock price data is consolidated, that is, represents the combined trading activity across US exchanges.
Learn more about the difference between consolidated and primary exchange prices.
Delisted stocks
US Stock price data includes stocks that delisted due to bankruptcies, mergers and acquisitions, etc.
Update schedule
The US Stock dataset is usually updated by 1 AM New York time with the previous day's prices, but in rare cases may not be updated until 7 AM. For users collecting daily incremental updates of either the end-of-day or intraday dataset, the recommended time to schedule the data collection is 7:30 AM each weekday.
Point-in-time ticker symbols
There is a Symbol
column in the end-of-day US stock price data as well as a Symbol
column (and usstock_Symbol
column) in the securities master file. The Symbol
column in the price data contains the point-in-time ticker symbol, that is, the ticker symbol as of that date. This field does not change if a security subsequently undergoes a ticker change. In contrast, the Symbol
/usstock_Symbol
column in the securities master file always reflects the security's latest ticker symbol.
US Stock end-of-day
There are three different ways to access end-of-day prices for US stocks:
- You can collect an end-of-day US Stock history database, managed by QuantRocket's
history
service; - You can collect the full end-of-day and intraday US Stock dataset, provided as a Zipline bundle, and query daily data from the bundle; or
- You can collect only the end-of-day portion of the Zipline bundle.
You can collect the data using whichever approach is most convenient to your use case. If you are planning to collect the minute data bundle, you may find it simpler to query daily bars from the minute bundle and not have to collect end-of-day data separately. If you are only interested in daily data and are planning to use it in Zipline backtests or in the Pipeline API, collecting only the end-of-day portion of the Zipline bundle would be a good choice. If you are not planning to use Zipline or minute data, the history database may be the most convenient choice.
You are free to collect and access the data using multiple approaches, if desired.
While the history database and Zipline bundle are constructed from the same source data, there are a few differences which are noted below.
Storage space
The end-of-day history database requires approximately 5 GB of disk space. The minute bundle requires approximately 50 GB. Collecting only the daily portion of the Zipline bundle requires less than 500 MB.
Initial collection runtime
Initial collection of the end-of-day history database takes approximately 15 minutes. Initial collection of the minute bundle takes 12-15 hours. Collecting only the daily portion of the Zipline bundle takes about a minute.
Fields
The end-of-day history database offers an expanded set of fields, while the Zipline bundle is limited to OHLCV (Open, High, Low, Close, and Volume).
Adjustments
There is a subtle difference in how adjustments are applied in the history database vs the Zipline bundle.
In the history database, all available adjustments are applied to the data at the time of collection, and the data are stored in an adjusted state. In the Zipline bundle, data are stored unadjusted, and adjustments are applied on-the-fly at query time. Moreover, Zipline only applies those adjustments that would have occurred on or before the end date of your query.
Both of these approaches result in a continuous price series that is free of artificial jumps and is suitable for quantitative analysis. However, depending on the date range of your query, the absolute price level may differ based on whether you query the Zipline bundle or the history database. To illustrate with an example, Apple stock underwent a 4-for-1 split on August 31, 2020. The price before the split was around $500, while the price after the split was around $125. If you query the period just before (but not including) the split date, the history database will return a price of around $125 (the split-adjusted price), because the 4-for-1 split will have already been applied to the stored data. In contrast, the Zipline bundle will return a price of around $500, because the 4-for-1 split falls after the query window and thus Zipline does not apply that particular split at query time. For most use cases, this distinction is immaterial. But if your analysis depends on the absolute price level, the Zipline bundle may be preferred because the absolute prices more accurately reflect their historical point-in-time values.
US Stock EOD history database
To collect the end-of-day US Stock history database, first create the database (include the --free
/free=True
parameter if requesting free sample data):
$ quantrocket history create-usstock-db 'usstock-1d'
status: successfully created quantrocket.v2.history.usstock-1d.sqlite
>>> from quantrocket.history import create_usstock_db
>>> create_usstock_db("usstock-1d")
{'status': 'successfully created quantrocket.v2.history.usstock-1d.sqlite'}
$ curl -X PUT 'http://houston/history/databases/usstock-1d?vendor=usstock'
{"status": "successfully created quantrocket.v2.history.usstock-1d.sqlite"}
Then collect the data:
$ quantrocket history collect 'usstock-1d'
status: the historical data will be collected asynchronously
>>> from quantrocket.history import collect_history
>>> collect_history("usstock-1d")
{'status': 'the historical data will be collected asynchronously'}
$ curl -X POST 'http://houston/history/queue?codes=usstock-1d'
{"status": "the historical data will be collected asynchronously"}
Monitor the status in flightlog:
quantrocket.history: INFO [usstock-1d] Collecting US history from 2007 to present
quantrocket.history: INFO [usstock-1d] Collecting updated US securities listings
quantrocket.history: INFO [usstock-1d] Collecting additional US history from 2020-04 to present
quantrocket.history: INFO [usstock-1d] Applying price adjustments for 52 securities
quantrocket.history: INFO [usstock-1d] Collected 161 monthly files in quantrocket.v2.history.usstock-1d.sqlite
The data is collected by loading pre-built 1-year chunks of data in which split and dividend adjustments have already been applied, then loading any additional price and adjustment history that has occurred since the pre-built chunks were last generated.
US Stock EOD Zipline bundle
To collect only the end-of-day portion of the Zipline bundle, specify "daily" as the data frequency when you define the bundle:
$ quantrocket zipline create-usstock-bundle 'usstock-1d-bundle' --data-frequency 'daily'
msg: successfully created usstock-1d-bundle bundle
status: success
>>> from quantrocket.zipline import create_usstock_bundle
>>> create_usstock_bundle("usstock-1d-bundle", data_frequency="daily")
{'status': 'success', 'msg': 'successfully created usstock-1d-bundle bundle'}
$ curl -X PUT 'http://houston/zipline/bundles/usstock-1d-bundle?ingest_type=usstock&data_frequency=daily'
{"status": "success", "msg": "successfully created usstock-1d-bundle bundle"}
Alternatively, for free sample data, use the --free
/free=True
parameter:
$ quantrocket zipline create-usstock-bundle 'free-usstock-1d-bundle' --data-frequency 'daily' --free
msg: successfully created free-usstock-1d-bundle bundle
status: success
>>> create_usstock_bundle("free-usstock-1d-bundle", data_frequency="daily", free=True)
{'status': 'success', 'msg': 'successfully created free-usstock-1d-bundle bundle'}
$ curl -X PUT 'http://houston/zipline/bundles/free-usstock-1d-bundle?ingest_type=usstock&data_frequency=daily&free=true'
{"status": "success", "msg": "successfully created free-usstock-1d-bundle bundle"}
This creates an empty bundle. Then, ingest the actual data, using the bundle name you specified:
$ quantrocket zipline ingest 'usstock-1d-bundle'
status: the data will be ingested asynchronously
>>> from quantrocket.zipline import ingest_bundle
>>> ingest_bundle("usstock-1d-bundle")
{'status': 'the data will be ingested asynchronously'}
$ curl -X POST 'http://houston/zipline/ingestions/usstock-1d-bundle'
{"status": "the data will be ingested asynchronously"}
For a fuller discussion of the US Stock Zipline bundle, see the following section on the full intraday dataset.
US Stock intraday
The intraday US Stock dataset provides 1-minute prices with history back to 2007. Daily prices are also automatically included with the intraday dataset.
Unlike other historical price datasets which are stored in SQLite databases and managed by the history
service, the intraday US Stock dataset is stored in a Zipline bundle and managed by the zipline
service. Although Zipline is primarily a backtesting engine, it includes a storage backend which was originally designed for 1-minute US stock prices and thus is very well suited for this dataset.
Storage requirements
A particular advantage of Zipline's storage backend is that it utilizes a highly compressed columnar storage format called bcolz. This makes the otherwise very large size of the dataset much more manageable.
The total bundle size is about 50 GB for all listed US stocks. You are free to load a subset of securities in which case the size will be smaller.
Data collection runtime
The full dataset consists of several million small files which are synced from the cloud to your local deployment. Collecting the entire dataset the first time takes approximately 12-15 hours depending on network speed. Collecting the incremental daily updates takes approximately 10-15 minutes. (See the data guide section above for the dataset's update schedule and the recommended time to schedule collection of daily updates.)
Collect minute bundle
The workflow for collecting the US Stock minute bundle is similar to the workflow for history databases, but adapted to Zipline:
- Create an empty database ("bundle" in Zipline terminology) which defines your data requirements.
- Collect ("ingest" in Zipline terminology) the historical data.
- Periodically collect/ingest the data again to obtain updated history.
- Query the minute data in your anlaysis or trading.
First, define the bundle you want. If you are interested in all US stocks, create the bundle with no parameters:
$ quantrocket zipline create-usstock-bundle 'usstock-1min'
msg: successfully created usstock-1min bundle
status: success
>>> from quantrocket.zipline import create_usstock_bundle
>>> create_usstock_bundle("usstock-1min")
{'status': 'success', 'msg': 'successfully created usstock-1min bundle'}
$ curl -X PUT 'http://houston/zipline/bundles/usstock-1min?ingest_type=usstock'
{"status": "success", "msg": "successfully created usstock-1min bundle"}
Or you can create a bundle for free sample data:
$ quantrocket zipline create-usstock-bundle 'free-usstock-1min' --free
msg: successfully created free-usstock-1min bundle
status: success
>>> create_usstock_bundle("free-usstock-1min", free=True)
{'status': 'success', 'msg': 'successfully created free-usstock-1min bundle'}
$ curl -X PUT 'http://houston/zipline/bundles/free-usstock-1min?ingest_type=usstock&free=true'
{"status": "success", "msg": "successfully created free-usstock-1min bundle"}
If you are interested in a subset of stocks other than free sample data, there are two options. You can specify sids and/or universes at the time of bundle creation (using the sids
and universes
parameters) or at the time of data ingestion. Any sids or universes that you specify at the time of bundle creation can be considered the default parameters, while any sids or universes you specify at data ingestion time will override the default parameters.
The next step is to ingest the data. If your bundle definition is for the full dataset, consider using the sids
or universes
parameters to collect a subset of data so you can begin experimenting while waiting for the full dataset to be collected:
$
$ quantrocket zipline ingest 'usstock-1min' --sids 'FIBBG000B9XRY4' 'FIBBG000BKZB36' 'FIBBG000BMHYD1' 'FIBBG00B3T3HD3'
status: the data will be ingested asynchronously
$
$ quantrocket zipline ingest 'usstock-1min'
status: the data will be ingested asynchronously
>>> from quantrocket.zipline import ingest_bundle
>>>
>>> ingest_bundle("usstock-1min", sids=["FIBBG000B9XRY4", "FIBBG000BKZB36", "FIBBG000BMHYD1", "FIBBG00B3T3HD3"])
{'status': 'the data will be ingested asynchronously'}
>>>
>>> ingest_bundle("usstock-1min")
{'status': 'the data will be ingested asynchronously'}
$
$ curl -X POST 'http://houston/zipline/ingestions/usstock-1min?sids=FIBBG000B9XRY4&sids=FIBBG000BKZB36&sids=FIBBG000BMHYD1&sids=FIBBG00B3T3HD3'
{"status": "the data will be ingested asynchronously"}
$
$ curl -X POST 'http://houston/zipline/ingestions/usstock-1min'
{"status": "the data will be ingested asynchronously"}
Monitor flightlog for completion status:
quantrocket.zipline: INFO [usstock-1min] Ingesting minute bars for 4 securities in usstock-1min bundle
quantrocket.zipline: INFO [usstock-1min] Ingesting daily bars for usstock-1min bundle
quantrocket.zipline: INFO [usstock-1min] Ingesting adjustments for usstock-1min bundle
quantrocket.zipline: INFO [usstock-1min] Ingesting assets for usstock-1min bundle
quantrocket.zipline: INFO [usstock-1min] Completed ingesting data for 4 securities in usstock-1min bundle
Update minute bundle
To update the minute bundle with new data, simply run the ingestion again (with or without specifying sids or universes, depending on your needs):
$ quantrocket zipline ingest 'usstock-1min'
status: the data will be ingested asynchronously
>>> ingest_bundle("usstock-1min")
{'status': 'the data will be ingested asynchronously'}
$ curl -X POST 'http://houston/zipline/ingestions/usstock-1min'
{"status": "the data will be ingested asynchronously"}
Because only the new data will be ingested, updating the bundle runs much faster than the initial ingestion.
For more on the Zipline bundle API, see the Zipline docs.
Query bundle file
The most convenient way to load minute data into Python is using the get_prices
function, which parses the data into a Pandas DataFrame and also works for history databases and real-time aggregate databases in addition to Zipline bundles. This function is outlined in the Research section.
Alternatively, for a more raw approach, you can download a CSV file of minute data:
$ quantrocket zipline get 'usstock-1min' --sids 'FIBBG000B9XRY4' 'FIBBG000BKZB36' --start-date '2020-04-06' --end-date '2020-04-06' --times '09:31:00' '09:32:00' | csvlook
| Field | Date | FIBBG000B9XRY4 | FIBBG000BKZB36 |
| ------ | ------------------------- | -------------- | -------------- |
| Close | 2020-04-06 09:31:00-04:00 | 250.780 | 186.635 |
| Close | 2020-04-06 09:32:00-04:00 | 250.330 | 185.730 |
| High | 2020-04-06 09:31:00-04:00 | 251.535 | 187.425 |
| High | 2020-04-06 09:32:00-04:00 | 250.960 | 186.940 |
| Low | 2020-04-06 09:31:00-04:00 | 250.560 | 186.120 |
| Low | 2020-04-06 09:32:00-04:00 | 250.200 | 185.127 |
| Open | 2020-04-06 09:31:00-04:00 | 250.850 | 186.650 |
| Open | 2020-04-06 09:32:00-04:00 | 250.689 | 186.640 |
| Volume | 2020-04-06 09:31:00-04:00 | 221,336.000 | 29,524.000 |
| Volume | 2020-04-06 09:32:00-04:00 | 185,522.000 | 23,366.000 |
>>> from quantrocket.zipline import download_bundle_file
>>> download_bundle_file("usstock-1min",
sids=["FIBBG000B9XRY4", "FIBBG000BKZB36"],
start_date="2020-04-06", end_date="2020-04-06",
times=["09:31:00", "09:32:00"],
filepath_or_buffer="minute_prices.csv")
>>> prices = pd.read_csv("minute_prices.csv", parse_dates=["Date"], index_col=["Field","Date"])
>>> prices.head()
FIBBG000B9XRY4 FIBBG000BKZB36
Field Date
Close 2020-04-06 09:31:00-04:00 250.780 186.635
2020-04-06 09:32:00-04:00 250.330 185.730
High 2020-04-06 09:31:00-04:00 251.535 187.425
2020-04-06 09:32:00-04:00 250.960 186.940
Low 2020-04-06 09:31:00-04:00 250.560 186.120
$ curl -X GET 'http://houston/zipline/bundles/data/usstock-1min.csv?start_date=2020-04-06&end_date=2020-04-06&sids=FIBBG000B9XRY4&sids=FIBBG000BKZB36×=09%3A31%3A00×=09%3A32%3A00' | csvlook
| Field | Date | FIBBG000B9XRY4 | FIBBG000BKZB36 |
| ------ | ------------------------- | -------------- | -------------- |
| Close | 2020-04-06 09:31:00-04:00 | 250.780 | 186.635 |
| Close | 2020-04-06 09:32:00-04:00 | 250.330 | 185.730 |
| High | 2020-04-06 09:31:00-04:00 | 251.535 | 187.425 |
| High | 2020-04-06 09:32:00-04:00 | 250.960 | 186.940 |
| Low | 2020-04-06 09:31:00-04:00 | 250.560 | 186.120 |
| Low | 2020-04-06 09:32:00-04:00 | 250.200 | 185.127 |
| Open | 2020-04-06 09:31:00-04:00 | 250.850 | 186.650 |
| Open | 2020-04-06 09:32:00-04:00 | 250.689 | 186.640 |
| Volume | 2020-04-06 09:31:00-04:00 | 221,336.000 | 29,524.000 |
| Volume | 2020-04-06 09:32:00-04:00 | 185,522.000 | 23,366.000 |
Be sure to use query parameters that will sufficiently limit the size of the query result to fit in memory. QuantRocket doesn't prevent you from trying to load too much data. If you load too much and the query is taking too long,
restart the Zipline service to kill the query.
You can query daily data from the minute bundle by using the --data-frequency
/data_frequency
parameter:
$ quantrocket zipline get 'usstock-1min' --data-frequency 'daily' --sids 'FIBBG000B9XRY4' 'FIBBG000BKZB36' --start-date '2020-04-06' --end-date '2020-04-06' | csvlook
| Field | Date | FIBBG000B9XRY4 | FIBBG000BKZB36 |
| ------ | ---------- | -------------- | -------------- |
| Close | 2020-04-06 | 262.47 | 191.330 |
| High | 2020-04-06 | 263.11 | 192.410 |
| Low | 2020-04-06 | 249.38 | 185.127 |
| Open | 2020-04-06 | 250.90 | 188.000 |
| Volume | 2020-04-06 | 50,455,071.00 | 7,582,690.000 |
>>> from quantrocket.zipline import download_bundle_file
>>> download_bundle_file("usstock-1min",
data_frequency="daily",
sids=["FIBBG000B9XRY4", "FIBBG000BKZB36"],
start_date="2020-04-06", end_date="2020-04-06",
filepath_or_buffer="daily_prices.csv")
>>> prices = pd.read_csv("daily_prices.csv", parse_dates=["Date"], index_col=["Field","Date"])
>>> prices.head()
FIBBG000B9XRY4 FIBBG000BKZB36
Field Date
Close 2020-04-06 262.47 191.330
High 2020-04-06 263.11 192.410
Low 2020-04-06 249.38 185.127
Open 2020-04-06 250.90 188.000
Volume 2020-04-06 50455071.00 7582690.000
$ curl -X GET 'http://houston/zipline/bundles/data/usstock-1min.csv?start_date=2020-04-06&end_date=2020-04-06&sids=FIBBG000B9XRY4&sids=FIBBG000BKZB36&data_frequency=daily' | csvlook
| Field | Date | FIBBG000B9XRY4 | FIBBG000BKZB36 |
| ------ | ---------- | -------------- | -------------- |
| Close | 2020-04-06 | 262.47 | 191.330 |
| High | 2020-04-06 | 263.11 | 192.410 |
| Low | 2020-04-06 | 249.38 | 185.127 |
| Open | 2020-04-06 | 250.90 | 188.000 |
| Volume | 2020-04-06 | 50,455,071.00 | 7,582,690.000 |
When omitted, the --data-frequency
/data_frequency
parameter defaults to "daily" for daily bundles and "minute" for minute bundles. Thus, the parameter is only needed to request daily data from a minute bundle.
Primary vs consolidated prices
Pricing data can either be "consolidated" or from the "primary exchange". Consolidated prices provide combined trading activity from all exchanges within a country. Primary exchange prices provide trading activity from the primary listing exchange only. Both have pros and cons.
Primary exchange prices provide a truer indication of the opening and closing auction price. This can result in more accurate backtests for trading strategies that enter and exit in the opening or closing auction. This issue is especially significant in US markets due to after-hours trading and the large number of exchanges and ECNs. The closing or opening price in consolidated data may represent small trades from an ECN that would be hard to obtain, rather than the opening or closing auction price. For more on this topic, see this blog post by Ernie Chan.
However, consolidated prices provide a more complete picture of total trading volume. In the US market, for example, trading volume on the primary exchange often accounts for only 25% of total daily volume.
Fundamental Data
Alpaca ETB
Alpaca publishes a daily list of easy-to-borrow (ETB) stocks, which indicates whether the stock is shortable through Alpaca. QuantRocket maintains a historical archive dating back to March 2019.
Collect Alpaca ETB
To collect the data:
$ quantrocket fundamental collect-alpaca-etb
status: the easy-to-borrow data will be collected asynchronously
>>> from quantrocket.fundamental import collect_alpaca_etb
>>> collect_alpaca_etb()
{'status': 'the easy-to-borrow data will be collected asynchronously'}
$ curl -X POST 'http://houston/fundamental/alpaca/stockloan/etb'
{"status": "the easy-to-borrow data will be collected asynchronously"}
QuantRocket will collect the data in 1-month batches and save it to your database. Monitor flightlog for progress:
quantrocket.fundamental: INFO Collecting alpaca usa easy-to-borrow data from 2019-03-01 to present
quantrocket.fundamental: INFO Saved 216389 total alpaca easy-to-borrow records to quantrocket.v2.fundamental.alpaca.stockloan.etb.sqlite
Query Alpaca ETB
You can query the ETB data by universe or sid. The returned data is a boolean value (1 or 0) indicating whether the security was on the easy-to-borrow list on a given date:
$ quantrocket fundamental alpaca-etb --sids 'FIBBG000B9XRY4' 'FIBBG00LBLDHJ2' --start-date '2020-03-01' -o etb.csv
$ csvlook -I --max-rows 5 etb.csv
| Sid | Date | EasyToBorrow |
| -------------- | ---------- | ------------ |
| FIBBG000B9XRY4 | 2020-03-02 | 1 |
| FIBBG000B9XRY4 | 2020-04-01 | 1 |
| FIBBG00LBLDHJ2 | 2020-03-02 | 0 |
| FIBBG00LBLDHJ2 | 2020-03-05 | 1 |
| FIBBG00LBLDHJ2 | 2020-03-11 | 0 |
>>> from quantrocket.fundamental import download_alpaca_etb
>>> import pandas as pd
>>> download_alpaca_etb("etb.csv", start_date="2020-03-01", sids=["FIBBG000B9XRY4", "FIBBG00LBLDHJ2"])
>>> etb = pd.read_csv("etb.csv", parse_dates=["Date"])
>>> etb.head()
Sid Date EasyToBorrow
0 FIBBG000B9XRY4 2020-03-02 1
1 FIBBG000B9XRY4 2020-04-01 1
2 FIBBG00LBLDHJ2 2020-03-02 0
3 FIBBG00LBLDHJ2 2020-03-05 1
4 FIBBG00LBLDHJ2 2020-03-11 0
$ curl -X GET 'http://houston/fundamental/alpaca/stockloan/etb.csv?start_date=2020-03-01&sids=FIBBG000B9XRY4&sids=FIBBG00LBLDHJ2' --output etb.csv
$ head etb.csv
Sid,Date,EasyToBorrow
FIBBG000B9XRY4,2020-03-02,1
FIBBG000B9XRY4,2020-04-01,1
FIBBG00LBLDHJ2,2020-03-02,0
FIBBG00LBLDHJ2,2020-03-05,1
FIBBG00LBLDHJ2,2020-03-11,0
In Python, you can use a DataFrame of prices (or any DataFrame with a DatetimeIndex and sids as columns) to get easy-to-borrow status that is aligned to the price data:
>>> from quantrocket import get_prices
>>> prices = get_prices("usstock-1d", start_date="2020-03-04", fields="Close")
>>> closes = prices.loc["Close"]
>>> from quantrocket.fundamental import get_alpaca_etb_reindexed_like
>>> etb = get_alpaca_etb_reindexed_like(closes)
The resulting boolean DataFrame has an index and columns matching the input DataFrame:
>>> etb.head()
Sid FIBBG000B9XRY4 FIBBG000BVPV84 FIBBG000CL9VN6 FIBBG00LBLDHJ2
Date
2020-03-04 True True True False
2020-03-05 True True True True
2020-03-06 True True True True
2020-03-09 True True True True
2020-03-10 True True True True
2020-03-11 True True True False
This function will return False for all dates prior to 2019-03-01, which is as far back as the Alpaca ETB dataset extends. For dates after 2019-03-01, False means "not on the easy-to-borrow list", but for earlier dates False is simply a fill value.
Alpaca ETB data guide
Data storage
Alpaca updates the easy-to-borrow list daily, but the data for any given stock doesn't always change that frequently. To conserve disk space, QuantRocket stores the data sparsely. That is, the data for any given security is stored only when the data changes. The following example illustrates:
Date | ETB status reported by Alpaca for ABC stock | stored in QuantRocket database |
---|
2019-05-01 | 1 | yes |
2019-05-02 | 1 | - |
2019-05-03 | 1 | - |
2019-05-04 | 0 | yes |
2019-05-05 | 0 | - |
With this data storage design, the data is intended to be forward-filled after you query it. (The function get_alpaca_etb_reindexed_like
does this for you.)
QuantRocket stores the first data point of each month for each stock regardless of whether it changed from the previous data point. This is to ensure that the data is not stored so sparsely that stocks are inadvertently omitted from date range queries. When querying and forward-filling the data you should request an initial 1-month buffer to ensure that infrequently-changing data is included in the query results. For example, if you want results back to June 17, 2019, you should query back to June 1, 2019 or earlier, as this ensures you will get the first-of-month data point for any infrequently changing securities. The function get_alpaca_etb_reindexed_like
takes care of this for you.
Update schedule
Daily updates to the Alpaca ETB dataset are made available each weekday morning by 8:15 AM New York time.
IBKR short sale data
QuantRocket provides current and historical short sale availability data from Interactive Brokers. The dataset includes the number of shortable shares available and the associated borrow fees. You can use this dataset to model the constraints and costs of short selling.
IBKR updates short sale availability data every 15 minutes. IBKR does not provide a historical archive of data but QuantRocket maintains a historical archive dating from April 16, 2018.
No IBKR market data subscriptions are required to access this dataset.
Collect IBKR short sale data
Shortable shares data and borrow fee data are stored separately but have similar APIs. Both datasets are organized by the country where the security trades. The available country names are:
| | |
---|
australia | france | mexico |
austria | germany | spain |
belgium | hongkong | swedish |
british | india | swiss |
canada | italy | usa |
dutch | japan | |
To use the data, first collect the desired dataset and countries from QuantRocket's archive into your local database. For shortable shares:
$ quantrocket fundamental collect-ibkr-shortshares --countries 'japan' 'usa'
status: the shortable shares will be collected asynchronously
>>> from quantrocket.fundamental import collect_ibkr_shortable_shares
>>> collect_ibkr_shortable_shares(countries=["japan","usa"])
{'status': 'the shortable shares will be collected asynchronously'}
$ curl -X POST 'http://houston/fundamental/ibkr/stockloan/shares?countries=japan&countries=usa'
{"status": "the shortable shares will be collected asynchronously"}
Similarly for borrow fees:
$ quantrocket fundamental collect-ibkr-borrowfees --countries 'japan' 'usa'
status: the borrow fees will be collected asynchronously
>>> from quantrocket.fundamental import collect_ibkr_borrow_fees
>>> collect_ibkr_borrow_fees(countries=["japan","usa"])
{'status': 'the borrow fees will be collected asynchronously'}
$ curl -X POST 'http://houston/fundamental/ibkr/stockloan/fees?countries=japan&countries=usa'
{"status": "the borrow fees will be collected asynchronously"}
You can pass an invalid country such as "?" to either of the above endpoints to see the available country names.
QuantRocket will collect the data in 1-month batches and save it to your database. For shortable shares, intraday data as well as aggregated daily data will be collected. Monitor flightlog for progress:
quantrocket.fundamental: INFO Collecting ibkr usa shortable shares from 2018-04-01 to present
quantrocket.fundamental: INFO Saved 2993493 total ibkr shortable shares records to quantrocket.v2.fundamental.ibkr.stockloan.shares.sqlite
quantrocket.fundamental: INFO Collecting ibkr usa daily aggregate shortable shares from 2018-04-01 to present
quantrocket.fundamental: INFO Saved 2993493 total ibkr daily aggregate shortable shares records to quantrocket.v2.fundamental.ibkr.stockloan.shares.aggregate.sqlite
To update the data later, re-run the same command(s) you ran originally. QuantRocket will collect any new data since your last update and add it to your database.
Query IBKR short sale data
You can query the shortable shares data by universe or sid. By default, intraday data is returned:
$ quantrocket fundamental ibkr-shortshares -u 'usa-stk' -o usa_shortable_shares.csv
$ csvlook -I --max-rows 5 usa_shortable_shares.csv
| Sid | Date | Quantity |
| -------------- | ------------------- | -------- |
| FIBBG000C1XSP8 | 2018-04-15T21:45:02 | 450000 |
| FIBBG000C1XSP8 | 2018-04-16T13:15:03 | 200000 |
| FIBBG000C1XSP8 | 2018-04-16T14:15:03 | 250000 |
| FIBBG000C1XSP8 | 2018-04-17T11:15:02 | 15000 |
| FIBBG000C1XSP8 | 2018-04-17T11:30:02 | 40000 |
>>> from quantrocket.fundamental import download_ibkr_shortable_shares
>>> import pandas as pd
>>> download_ibkr_shortable_shares("usa_shortable_shares.csv", universes=["usa-stk"])
>>> shortable_shares = pd.read_csv("usa_shortable_shares.csv", parse_dates=["Date"])
>>> shortable_shares.head()
Sid Date Quantity
0 FIBBG000C1XSP8 2018-04-15 21:45:02 450000
1 FIBBG000C1XSP8 2018-04-16 13:15:03 200000
2 FIBBG000C1XSP8 2018-04-16 14:15:03 250000
3 FIBBG000C1XSP8 2018-04-17 11:15:02 15000
4 FIBBG000C1XSP8 2018-04-17 11:30:02 40000
$ curl -X GET 'http://houston/fundamental/ibkr/stockloan/shares.csv?&universes=usa-stk' --output usa_shortable_shares.csv
$ head usa_shortable_shares.csv
Sid,Date,Quantity
FIBBG000C1XSP8,2018-04-15T21:45:02,450000
FIBBG000C1XSP8,2018-04-16T13:15:03,200000
FIBBG000C1XSP8,2018-04-16T14:15:03,250000
FIBBG000C1XSP8,2018-04-17T11:15:02,15000
FIBBG000C1XSP8,2018-04-17T11:30:02,40000
Alternatively, you can query aggregated daily data instead using the --aggregate
/aggregate=True
parameter. Aggregate data is less voluminous and thus easier to work with for large universes:
$ quantrocket fundamental ibkr-shortshares -u 'usa-stk' --aggregate -o usa_shortable_shares.csv
$ csvlook -I --max-rows 5 usa_shortable_shares.csv
| Sid | Date | MinQuantity | MaxQuantity | MeanQuantity | LastQuantity |
| -------------- | ---------- | ----------- | ----------- | ------------ | ------------ |
| FIBBG000C1XSP8 | 2018-04-15 | 450000 | 450000 | 450000 | 450000 |
| FIBBG000C1XSP8 | 2018-04-16 | 200000 | 450000 | 250000 | 250000 |
| FIBBG000C1XSP8 | 2018-04-17 | 15000 | 700000 | 450000 | 700000 |
| FIBBG000C1XSP8 | 2018-04-18 | 15000 | 750000 | 463777 | 500000 |
| FIBBG000C1XSP8 | 2018-04-19 | 55000 | 800000 | 642604 | 800000 |
>>> download_ibkr_shortable_shares("usa_shortable_shares.csv", aggregate=True, universes=["usa-stk"])
>>> shortable_shares = pd.read_csv("usa_shortable_shares.csv", parse_dates=["Date"])
>>> shortable_shares.head()
Sid Date MinQuantity MaxQuantity MeanQuantity LastQuantity
0 FIBBG000C1XSP8 2018-04-15 450000 450000 450000 450000
1 FIBBG000C1XSP8 2018-04-16 200000 450000 250000 250000
2 FIBBG000C1XSP8 2018-04-17 15000 700000 450000 700000
3 FIBBG000C1XSP8 2018-04-18 15000 750000 463777 500000
4 FIBBG000C1XSP8 2018-04-19 55000 800000 642604 800000
$ curl -X GET 'http://houston/fundamental/ibkr/stockloan/shares.csv?&universes=usa-stk&aggregate=True' --output usa_shortable_shares.csv
$ head usa_shortable_shares.csv
Sid,Date,MinQuantity,MaxQuantity,MeanQuantity,LastQuantity
FIBBG000C1XSP8,2018-04-15,450000,450000,450000,450000
FIBBG000C1XSP8,2018-04-16,200000,450000,250000,250000
FIBBG000C1XSP8,2018-04-17,15000,700000,450000,700000
FIBBG000C1XSP8,2018-04-18,15000,750000,463777,500000
FIBBG000C1XSP8,2018-04-19,55000,800000,642604,800000
The borrow fees data can be queried similarly. Unlike the shortable shares data which is available at intraday or daily granularity, borrow fees are returned as daily values, with each value representing the borrow fee assessed on overnight positions:
$ quantrocket fundamental ibkr-borrowfees -u 'usa-stk' -o usa_borrow_fees.csv
$ csvlook -I --max-rows 5 usa_borrow_fees.csv
| Sid | Date | FeeRate |
| -------------- | ---------- | ------- |
| FIBBG000C1XSP8 | 2018-04-15 | 15.6739 |
| FIBBG000C1XSP8 | 2018-04-16 | 15.5991 |
| FIBBG000C1XSP8 | 2018-04-17 | 15.8005 |
| FIBBG000C1XSP8 | 2018-04-18 | 16.037 |
| FIBBG000C1XSP8 | 2018-04-19 | 15.7627 |
>>> from quantrocket.fundamental import download_ibkr_borrow_fees
>>> import pandas as pd
>>> download_ibkr_borrow_fees("usa_borrow_fees.csv", universes=["usa-stk"])
>>> borrow_fees = pd.read_csv("usa_borrow_fees.csv", parse_dates=["Date"])
>>> borrow_fees.head()
Sid Date FeeRate
0 FIBBG000C1XSP8 2018-04-15 15.6739
1 FIBBG000C1XSP8 2018-04-16 15.5991
2 FIBBG000C1XSP8 2018-04-17 15.8005
3 FIBBG000C1XSP8 2018-04-18 16.0370
4 FIBBG000C1XSP8 2018-04-19 15.7627
$ curl -X GET 'http://houston/fundamental/ibkr/stockloan/fees.csv?&universes=usa-stk' --output usa_borrow_fees.csv
$ head usa_borrow_fees.csv
Sid,Date,FeeRate
FIBBG000C1XSP8,2018-04-15,15.6739
FIBBG000C1XSP8,2018-04-16,15.5991
FIBBG000C1XSP8,2018-04-17,15.8005
FIBBG000C1XSP8,2018-04-18,16.037
FIBBG000C1XSP8,2018-04-19,15.7627
In Python, you can use a DataFrame of prices (or any DataFrame with a DatetimeIndex and sids as columns) to get shortable shares or borrow fees data that is aligned to the price data:
>>> from quantrocket import get_prices
>>> prices = get_prices("usstock-1d", start_date="2018-04-16", fields="Close")
>>> closes = prices.loc["Close"]
>>> from quantrocket.fundamental import get_ibkr_shortable_shares_reindexed_like, get_ibkr_borrow_fees_reindexed_like
>>> shortable_shares = get_ibkr_shortable_shares_reindexed_like(closes)
>>> borrow_fees = get_ibkr_borrow_fees_reindexed_like(closes)
The resulting DataFrame has an index and columns matching the input DataFrame:
>>> shortable_shares.head()
Sid FIBBG000006F71 FIBBG000006L78 FIBBG000006LG8 FIBBG000006RN7
Date
2018-04-16 3000.0 2000.0 100.0 20000.0
2018-04-17 4000.0 2000.0 100.0 20000.0
2018-04-18 4000.0 3000.0 0.0 20000.0
2018-04-19 3000.0 3000.0 0.0 20000.0
2018-04-20 3000.0 3000.0 0.0 20000.0
By default, the shortable shares data in the resulting DataFrame is as of midnight UTC. To request shortable shares data as of a different time of day (for example, the time when your strategy trades), you can specify a time and timezone using the time
parameter:
>>>
>>> shortable_shares = get_ibkr_shortable_shares_reindexed_like(closes, time="09:30:00 America/New_York")
Alternatively, you can specify aggregate=True
to request aggregated shortable shares data. The resulting DataFrame can be thought of as several stacked DataFrames, with a MultiIndex consisting of the field (by default all fields are returned), and the date. Use .loc
to select a specific field:
>>> shortables = get_ibkr_shortable_shares_reindexed_like(closes, aggregate=True)
>>> min_quantities = shortables.loc["MinQuantity"]
>>> max_quantities = shortables.loc["MaxQuantity"]
>>> mean_quantities = shortables.loc["MeanQuantity"]
>>> last_quantities = shortables.loc["LastQuantity"]
Dates prior to April 16, 2018 (the start date of QuantRocket's historical archive) will have NaNs in the resulting DataFrame.
Borrow fees are stored as annualized interest rates. For example, 1.0198 indicates an annualized interest rate of 1.0198%:
>>> borrow_fees.head()
Sid FIBBG000B9XRY4 FIBBG000BVPV84 FIBBG000CL9VN6 FIBBG009S3NB30
Date
2018-04-16 0.25 1.3575 0.25 0.3388
2018-04-17 0.25 1.3348 0.25 0.3291
2018-04-18 0.25 0.2500 0.25 0.2533
2018-04-19 0.25 0.2500 0.25 0.2500
2018-04-20 0.25 0.2500 0.25 0.3865
Below is an example of calculating borrow fees for a DataFrame of positions (adapted from Moonshot's IBKRBorrowFees
slippage class):
borrow_fees = get_ibkr_borrow_fees_reindexed_like(positions)
borrow_fees = borrow_fees / 100
daily_borrow_fees = borrow_fees / 360
dates = borrow_fees.apply(lambda x: borrow_fees.index)
days_held = (dates - dates.shift()).fillna(pd.Timedelta('1d')).apply(lambda x: x.dt.days)
daily_borrow_fees *= days_held
assessed_fees = positions.where(positions < 0, 0).abs() * 1.02 * daily_borrow_fees
IBKR short sale data guide
Data granularity
Shortable shares
IBKR updates short sale availability data every 15 minutes. QuantRocket provides the shortable shares data at native 15-minute granularity as well as aggregated daily granularity. An example intraday record is shown below:
Sid: "FIBBG000C1XSP8"
Date: "2018-04-15T21:45:02"
Quantity: 450000
The aggregated data provides the min, max, mean, and last values for each security for each day:
Sid: "FIBBG000C1XSP8"
Date: "2018-04-18"
MinQuantity: 15000
MaxQuantity: 750000
MeanQuantity: 463777
LastQuantity: 500000
Using the intraday records allows you to model shortable share availability at the time of your trade. The aggregate data provides a convenient way to analyze shortable shares over large universes of securities, due to its less voluminous size.
Borrow fees
IBKR updates borrow fees every 15 minutes, but QuantRocket only stores the last value for each date. This is because borrow fees are assessed on overnight positions; the day's last value is therefore the only applicable value. Values from earlier in the day are "indicative," that is, they provide an indication of what the overnight fee is likely to be. QuantRocket updates the borrow fee data continuously, so if you collect the data before the end of the day, it will reflect the current intraday indicative borrow fee. Later, when you collect the data again, this value will be overwritten by the day's final borrow fee amount.
An example borrow fee record is shown below:
Sid: "FIBBG000C1XSP8"
Date: "2018-04-15"
FeeRate: 15.6739
In this example, the annual borrow fee is 15.6739%.
Data storage
IBKR updates short sale availability data every 15 minutes, but the data for any given stock doesn't always change that frequently. To conserve disk space, QuantRocket stores the shortable shares and borrow fees data sparsely. That is, the data for any given security is stored only when the data changes. The following example illustrates:
Timestamp (UTC) | Shortable shares reported by IBKR for ABC stock | stored in QuantRocket database |
---|
2018-05-01T09:15:02 | 70,900 | yes |
2018-05-01T09:30:03 | 70,900 | - |
2018-05-01T09:45:02 | 70,900 | - |
2018-05-01T10:00:03 | 84,000 | yes |
2018-05-01T10:15:02 | 84,000 | - |
With this data storage design, the data is intended to be forward-filled after you query it. (The functions get_ibkr_shortable_shares_reindexed_like
and get_ibkr_borrow_fees_reindexed_like
do this for you.)
QuantRocket stores the first data point of each month for each stock regardless of whether it changed from the previous data point. This is to ensure that the data is not stored so sparsely that stocks are inadvertently omitted from date range queries. When querying and forward-filling the data you should request an initial 1-month buffer to ensure that infrequently-changing data is included in the query results. For example, if you want results back to June 17, 2018, you should query back to June 1, 2018 or earlier, as this ensures you will get the first-of-month data point for any infrequently changing securities. The functions get_ibkr_shortable_shares_reindexed_like
and get_ibkr_borrow_fees_reindexed_like
take care of this for you.
Missing data
The shortable shares and borrow fees datasets represent IBKR's comprehensive list of shortable stocks. If stocks are missing from the data, that means they were never available to short. Stocks that were available to short and later became unavailable will be present in the shortable shares data and will have values of 0 when they became unavailable (possibly followed by nonzero values if they later became available again).
Timestamps and latency
The intraday shortable shares data timestamps are in UTC and indicate the time at which IBKR made the data available. It takes approximately two minutes for the data to be processed and made available in QuantRocket's archive. Once available, the data will be added to your local database the next time you collect it.
Stocks with >10M shortable shares
In the shortable shares dataset, 10000000 (10 million) is the largest number reported and means "10 million or more."
IBKR margin requirements
QuantRocket provides current and historical margin requirements data from Interactive Brokers. Only securities with special margin requirements are included in the dataset. Default margin requirements apply to stocks that are omitted from the dataset.
IBKR updates margin requirements data whenever changes occur, usually several times per day. IBKR does not provide a historical archive of data but QuantRocket maintains a historical archive dating from April 16, 2018.
No IBKR market data subscriptions are required to access this dataset.
The special margin requirements in the margin requirements dataset apply to rules-based margin accounts, such as Reg T accounts in the US. For portfolio margin accounts, a more accurate way to check margin requirements is by placing
what-if orders.
Collect IBKR margin requirements
The special margin requirements dataset is organized by the country of the IBKR subsidiary where your account is located. Note that this differs from the IBKR short sale datasets, which are organized by the country where the security trades rather than the country where your account is located. The available country names are:
- canada
- hongkong
- india
- japan
- usa
To use the data, first collect the dataset for the appropriate country from QuantRocket's archive into your local database:
$ quantrocket fundamental collect-ibkr-margin --country 'usa'
status: the margin requirements data will be collected asynchronously
>>> from quantrocket.fundamental import collect_ibkr_margin_requirements
>>> collect_ibkr_margin_requirements(country="usa")
{'status': 'the margin requirements data will be collected asynchronously'}
$ curl -X POST 'http://houston/fundamental/ibkr/stockloan/margin?countries=usa'
{"status": "the margin requirements data will be collected asynchronously"}
QuantRocket will collect the data in 1-month batches and save it to your database. Monitor flightlog for progress:
quantrocket.fundamental: INFO Collecting ibkr usa margin requirements data from 2018-04-01 to present
quantrocket.fundamental: INFO Saved 2590884 total margin requirements records to quantrocket.v2.fundamental.ibkr.stockloan.margin.sqlite
To update the data later, re-run the same command you ran originally. QuantRocket will collect any new data since your last update and add it to your database.
Query IBKR margin requirements
You can export the margin requirements data to CSV (or JSON), querying by universe or sid. The dataset provides both the initial and maintenance margin requirements for both long and short positions:
$ quantrocket fundamental ibkr-margin -u 'usa-stk' -o usa_margin_requirements.csv
$ csvlook -I --max-rows 5 usa_margin_requirements.csv
| Sid | Date | LongInitialMargin | LongMaintenanceMargin | ShortInitialMargin | ShortMaintenanceMargin |
| -------------- | ------------------- | ----------------- | --------------------- | ------------------ | ---------------------- |
| FIBBG0000014K6 | 2018-04-13T08:31:24 | 25 | 20 | 20 | 20 |
| FIBBG0000014K6 | 2018-05-01T00:17:26 | 25 | 20 | 20 | 20 |
| FIBBG0000014K6 | 2018-06-01T00:11:52 | 25 | 20 | 20 | 20 |
| FIBBG0000014K6 | 2018-07-01T22:55:24 | 25 | 20 | 20 | 20 |
| FIBBG0000014K6 | 2018-08-01T00:07:07 | 25 | 20 | 20 | 20 |
>>> from quantrocket.fundamental import download_ibkr_margin_requirements
>>> import pandas as pd
>>> download_ibkr_margin_requirements("usa_margin_requirements.csv", universes=["usa-stk"])
>>> margin_requirements = pd.read_csv("usa_margin_requirements.csv", parse_dates=["Date"])
>>> margin_requirements.head()
Sid Date LongInitialMargin LongMaintenanceMargin ShortInitialMargin ShortMaintenanceMargin
0 FIBBG0000014K6 2018-04-13 08:31:24 25 20 20 20
1 FIBBG0000014K6 2018-05-01 00:17:26 25 20 20 20
2 FIBBG0000014K6 2018-06-01 00:11:52 25 20 20 20
3 FIBBG0000014K6 2018-07-01 22:55:24 25 20 20 20
4 FIBBG0000014K6 2018-08-01 00:07:07 25 20 20 20
$ curl -X GET 'http://houston/fundamental/ibkr/stockloan/margin.csv?&universes=usa-stk' --output usa_margin_requirements.csv
$ head usa_margin_requirements.csv
Sid,Date,LongInitialMargin,LongMaintenanceMargin,ShortInitialMargin,ShortMaintenanceMargin
FIBBG0000014K6,2018-04-13T08:31:24,25,20,20,20
FIBBG0000014K6,2018-05-01T00:17:26,25,20,20,20
FIBBG0000014K6,2018-06-01T00:11:52,25,20,20,20
FIBBG0000014K6,2018-07-01T22:55:24,25,20,20,20
FIBBG0000014K6,2018-08-01T00:07:07,25,20,20,20
Margin requirements are expressed in percentages, as whole numbers. For example, 25 means 25% margin requirement, which is equivalent to 0.25.
0 in the dataset is a placeholder value that indicates that default margin requirements apply. In other words, default margin requirements apply to stocks that are absent from the dataset and also to stocks that are present in the dataset with a value of 0.
In Python, you can use a DataFrame of prices (or any DataFrame with a DatetimeIndex and sids as columns) to get margin requirement data that is aligned to the price data:
>>> from quantrocket import get_prices
>>> prices = get_prices("usstock-1d", start_date="2018-04-16", fields="Close")
>>> closes = prices.loc["Close"]
>>> from quantrocket.fundamental import get_ibkr_margin_requirements_reindexed_like
>>> margin_requirements = get_ibkr_margin_requirements_reindexed_like(closes)
The resulting DataFrame can be thought of as several stacked DataFrames, one for each field (LongInitialMargin
, LongMaintenanceMargin
, ShortInitialMargin
, ShortMaintenanceMargin
). Use .loc
to isolate a particular field:
>>> short_initial_margin = margin_requirements.loc["ShortInitialMargin"]
>>> short_initial_margin.head()
Sid FIBBG000C2V3D6 FIBBG00B3T3HD3 QI000000004076 FIBBG006T1NZ18
Date
2018-04-16 0.0 0.0 100.0 100.0
2018-04-17 0.0 0.0 100.0 100.0
2018-04-18 0.0 0.0 100.0 100.0
2018-04-19 0.0 0.0 100.0 100.0
2018-04-20 0.0 0.0 100.0 100.0
The following code calculates the higher of initial and maintenance margin for short positions:
>>> short_initial_margins = margin_requirements.loc["ShortInitialMargin"]
>>> short_maintenance_margins = margin_requirements.loc["ShortMaintenanceMargin"]
>>> short_margins = short_initial_margins.where(short_initial_margins > short_maintenance_margins, short_maintenance_margins)
Dates prior to April 16, 2018 (the start date of QuantRocket's historical archive) will have NaNs in the resulting DataFrame.
IBKR margin requirements data guide
Data storage
IBKR updates margin requirements data whenever changes occur, usually several times per day across the whole dataset, but the data for any given stock doesn't usually change very frequently. To conserve disk space, QuantRocket stores the margin requirements data sparsely. That is, the data for any given security is stored only when the data changes. With this data storage design, the data is intended to be forward-filled after you query it. (The function get_ibkr_margin_requirements_reindexed_like
does this for you.)
QuantRocket stores the first data point of each month for each stock regardless of whether it changed from the previous data point. This is to ensure that the data is not stored so sparsely that stocks are inadvertently omitted from date range queries. When querying and forward-filling the data you should request an initial 1-month buffer to ensure that infrequently-changing data is included in the query results. For example, if you want results back to June 17, 2018, you should query back to June 1, 2018 or earlier, as this ensures you will get the first-of-month data point for any infrequently changing securities. The function get_ibkr_margin_requirements_reindexed_like
takes care of this for you.
Missing data
The margin requirements dataset only includes securities with special margin requirements. Default margin requirements apply to stocks that are omitted from the dataset. Stocks that previously had special margin requirements but later reverted to default margin requirements will have values of 0 to indicate the return to default requirements (possibly followed by nonzero values if special margin requirements were later applied).
Sharadar fundamentals
Updated daily, the Sharadar fundamentals dataset provides up to 20 years of history, for 150 essential fundamental indicators and financial ratios, for more than 14,000 US public companies.
Key features:
- More than 5,000 active and 9,000 delisted companies.
- Continuously expanding ticker and indicator coverage, and history extensions.
- Data including or excluding restatements.
- Point-in-time dimension to data with time-indexing to the filing date or the fiscal/report period.
- Includes foreign issuers (ADRs and Canadian) that trade publicly on US markets.
- Annual, Trailing Twelve month, and Quarterly (domestic-only) datasets available.
Collect Sharadar fundamentals
To collect Sharadar fundamental data, specify a country (use FREE
for sample data):
$ quantrocket fundamental collect-sharadar-fundamentals --country 'US'
status: the fundamental data will be collected asynchronously
>>> from quantrocket.fundamental import collect_sharadar_fundamentals
>>> collect_sharadar_fundamentals(country="US")
{'status': 'the fundamental data will be collected asynchronously'}
$ curl -X POST 'http://houston/fundamental/sharadar/fundamentals?country=US'
{"status": "the fundamental data will be collected asynchronously"}
Collecting the full dataset takes less than 5 minutes. Monitor flightlog for completion:
quantrocket.fundamental: INFO Collecting Sharadar US fundamentals
quantrocket.fundamental: INFO Collecting updated Sharadar US securities listings
quantrocket.fundamental: INFO Finished collecting Sharadar US fundamentals
Query Sharadar fundamentals
The data can be queried by sid, universe, date range, and dimension:
$ quantrocket fundamental sharadar-fundamentals --sids "FIBBG000B9XRY4" --dimensions 'ART' -o aapl_fundamentals.csv
$ csvlook aapl_fundamentals.csv --max-columns 6 --max-rows 3
| Sid | DATEKEY | DIMENSION | CALENDARDATE | REVENUE | EPS |
| -------------- | ---------- | --------- | ------------ | ------------- | ----- |
| FIBBG000B9XRY4 | 2000-02-01 | ART | 1999-12-31 | 6,767,000,000 | 0.150 |
| FIBBG000B9XRY4 | 2000-05-11 | ART | 2000-03-31 | 7,182,000,000 | 0.166 |
| FIBBG000B9XRY4 | 2000-07-31 | ART | 2000-06-30 | 7,449,000,000 | 0.160 |
>>> from quantrocket.fundamental import download_sharadar_fundamentals
>>> download_sharadar_fundamentals(filepath_or_buffer="aapl_fundamentals.csv", sids="FIBBG000B9XRY4", dimensions="ART")
>>> fundamentals = pd.read_csv("aapl_fundamentals.csv", parse_dates=["REPORTPERIOD", "DATEKEY", "CALENDARDATE"])
>>> fundamentals.tail()
Sid DATEKEY DIMENSION CALENDARDATE REVENUE EPS
0 FIBBG000B9XRY4 2000-02-01 ART 1999-12-31 6.767000e+09 0.150
1 FIBBG000B9XRY4 2000-05-11 ART 2000-03-31 7.182000e+09 0.166
2 FIBBG000B9XRY4 2000-07-31 ART 2000-06-30 7.449000e+09 0.160
3 FIBBG000B9XRY4 2000-12-14 ART 2000-09-30 7.983000e+09 0.173
4 FIBBG000B9XRY4 2001-02-12 ART 2000-12-31 6.647000e+09 0.091
$ curl -X GET 'http://houston/fundamental/sharadar/fundamentals.csv?sids=FIBBG000B9XRY4&dimensions=ART' > aapl_fundamentals.csv
$ csvlook aapl_fundamentals.csv --max-columns 6 --max-rows 3
| Sid | DATEKEY | DIMENSION | CALENDARDATE | REVENUE | EPS |
| -------------- | ---------- | --------- | ------------ | ------------- | ----- |
| FIBBG000B9XRY4 | 2000-02-01 | ART | 1999-12-31 | 6,767,000,000 | 0.150 |
| FIBBG000B9XRY4 | 2000-05-11 | ART | 2000-03-31 | 7,182,000,000 | 0.166 |
| FIBBG000B9XRY4 | 2000-07-31 | ART | 2000-06-30 | 7,449,000,000 | 0.160 |
In Python, you can use a DataFrame of prices (or any DataFrame with a DatetimeIndex and sids as columns) to get Sharadar fundamental data that is aligned to the price data. This makes it easy to perform matrix operations using fundamental data.
>>> from quantrocket import get_prices
>>> prices = get_prices("usstock-1d", start_date="2018-04-16", fields="Close")
>>> closes = prices.loc["Close"]
>>> from quantrocket.fundamental import get_sharadar_fundamentals_reindexed_like
>>> fundamentals = get_sharadar_fundamentals_reindexed_like(
closes,
fields=["EPS", "REVENUE", "EVEBITDA"],
dimension="ARQ")
The resulting DataFrame can be thought of as several stacked DataFrames, with a MultiIndex consisting of the field (indicator code) and the date. The columns are sids, matching the input DataFrame. The DataFrame gives each indicator's current value as of the given date. The function get_sharadar_fundamentals_reindexed_like
shifts values forward by one day (based on the DATEKEY
field) to avoid lookahead bias.
>>> fundamentals.head()
Sid FIBBG000B9XRY4 FIBBG000BFWKC0 FIBBG000BKZB36 FIBBG000BMHYD1
Field Date
EPS 2018-04-16 00:00:00 3.92 3.31 1.54 -3.98
2018-04-17 00:00:00 3.92 3.31 1.54 -3.98
2018-04-18 00:00:00 3.92 3.31 1.54 -3.98
2018-04-19 00:00:00 3.92 3.31 1.54 -3.98
2018-04-20 00:00:00 3.92 3.31 1.54 -3.98
...
EVEBITDA 2020-03-31 00:00:00 18.297 13.724 12.712 16.342
2020-04-01 00:00:00 18.297 13.724 12.712 16.342
2020-04-02 00:00:00 18.297 13.724 12.712 16.342
2020-04-03 00:00:00 18.297 13.724 12.712 16.342
2020-04-06 00:00:00 18.297 13.724 12.712 16.342
You can use .loc
to isolate a particular indicator:
>>> enterprise_multiples = fundamentals.loc["EVEBITDA"]
For best performance, make two separate calls to get_sharadar_fundamentals_reindexed_like
to retrieve numeric (integer or float) vs non-numeric (string or date) fields. Pandas loads numeric fields in an optimized format compared to non-numeric fields, but mixing numeric and non-numeric fields prevents Pandas from using this optimized format, resulting in slower loads and higher memory consumption.
>>>
>>> fundamentals = get_sharadar_fundamentals_reindexed_like(
closes,
fields=["EPS", "REPORTPERIOD"],
dimension="ARQ")
>>> eps = fundamentals.loc["EPS"]
>>> fiscal_period_end_dates = fundamentals.loc["REPORTPERIOD"]
>>>
>>> fundamentals = get_sharadar_fundamentals_reindexed_like(
closes,
fields=["EPS"],
dimension="ARQ")
>>> eps = fundamentals.loc["EPS"]
>>> fundamentals = get_sharadar_fundamentals_reindexed_like(
closes,
fields=["REPORTPERIOD"],
dimension="ARQ")
>>> fiscal_period_end_dates = fundamentals.loc["REPORTPERIOD"]
You can use the period_offset
argument to control which fiscal period to return data for. This allows you to compare current and previous fiscal periods and calculate changes in fundamental metrics over time. The default period_offset
of 0 returns data for the most recently reported fiscal period as of each date in the input DataFrame. A negative period_offset
means to return data for a previous fiscal period: -1 means the immediately preceding fiscal period, -2 means two fiscal periods ago, etc. For quarterly and trailing-twelve-month dimensions, previous period means previous quarter, while for annual dimensions, previous period means previous year. The following example creates a boolean DataFrame indicating whether assets increased in the current quarter vs the prior quarter:
>>> current_fundamentals = get_sharadar_fundamentals_reindexed_like(
closes,
fields=["ASSETS"],
dimension="ARQ")
>>> previous_fundamentals = get_sharadar_fundamentals_reindexed_like(
closes,
fields=["ASSETS"],
dimension="ARQ",
period_offset=-1)
>>> total_assets = current_fundamentals.loc["ASSETS"]
>>> previous_total_assets = previous_fundamentals.loc["ASSETS"]
>>> assets_increased = total_assets > previous_total_assets
Sharadar fundamentals data guide
Dimensions
The two primary dimensions to the database are the As Reported (AR) and Most-Recent Reported (MR) dimensions:
As Reported view (AR)
- excludes restatements
- point-in-time view with data time-indexed to the date the form 10 regulatory filing was submitted to the SEC
- presents data for the latest reporting period at that filing date
- may include multiple observations in a quarter if more than one filing is made during the quarter
- on limited occassion may not have any observations in a particular quarter. Sometimes companies are delayed in reporting for up to 18 months. On such occassions they may report multiple documents on the same date to catch up, in which case these datasets will only provide date for the most recent reporting period.
- most suitable for back-testing
Most-Recent Reported view (MR)
- includes restatements
- time indexed to the financial/report period presents the most recently reported data for that reporting period
- typically suitable for assessing business performance after restatements for mergers/divestitures
In addition there are 3 time dimensions:
- Annual (Y): Annual observations of one year duration
- Trailing Twelve Months (T): Quarterly observations of one year duration
- Quarterly (Q): Quarterly observations of quarterly duration (available only for US domestic companies, unavailable for foreign companies)
DIMENSIONS | AS REPORTED | MOST-RECENT REPORTED |
---|
Annual | ARY | MRY |
Quarterly | ARQ | MRQ |
Trailing Twelve Months | ART | MRT |
Time-indexing
As previously noted, the As-Reported dimensions present a point-in-time view with data time-indexed to the date of the form 10 regulatory filing to the SEC. This is in order to more closely align with the date that information was disseminated to the market, and the corresponding market impact. This is is a more accurate measure than the reporting period which the Most-Recent Reported dimensions utilize, which are typically months before the information reaches the market, and subject to restatement. However, it must be noted that the information contained in the form 10 may have been separately disclosed to the market days (or on rare occasion - weeks) earlier under separate form 8 regulatory filing. It is safe to assume that the information would have been available the day after the As-Reported date (at the latest). We source our data from a company's form 10 filing rather than their form 8 filing since the form 8 filings do not consistently contain full consolidated financial statements.
Negative P/E Ratios
Where a company reports negative earnings it's calculated PE (or PE1) ratio will be negative - please be aware of this when filtering for low P/E ratios.
Exception Handling
SHARESWADIL
and EPSDIL
are not consistently reported by all companies, and there is a higher incidence of non-availability of both these indicators, and the DILUTIONRATIO
indicator which is subsequently derived.
Ratios which have zero in the denominator cannot be calculated and will be blank. For example, where a company's trailing twelve month EPS
sums to 0.0 the subsequently derived PE1
indicator cannot be calculated. Therefore due to the unavailability of "N/A" values there will be no observation returned. This also applies to ROS
, NETMARGIN
, PS
, PS1
, GROSSMARGIN
and EBITDAMARGIN
for companies that have zero REVENUE
. Companies that have zero revenue are generally, but not exclusively, early stage Biotech firms.
Not all companies operate a classified Balance Sheet, approximately 20% of the companies in the database do not, most of which are financial firms. As such: ASSETSC
(Current Assets) & LIABILITIESC
(Current Liabilities), and the subsequently derived ASSETSNC
, LIABILITIESNC
, CURRENTRATIO
and WORKINGCAPITAL
, are not reported for all companies. In addition, companies can change their financial statement presentation and start or stop operating a classified Balance Sheet, therefore there may be gaps in the availability of these indicators.
Newly listed companies may not have the four quarters of reporting history required to calculate the trailing twelve month dimension, therefore the dataset may be blank until this history is available.
On limited occasion Annual and Quarterly financial statement presentation does not conform. For example, sometimes companies only report DEPAMOR
, INTEXP
and/or TAXEXP
annually and not quarterly. In these instances the quarterly values will not sum to the annual values.
Update schedule
Data is updated daily by 5 AM New York time.
How soon after a company reports will the database be updated? The database is updated within 24 hours of the form 10 SEC filing. Note that companies may report abbreviated financial statements via a separate form 8 SEC filing days or on occasion weeks before the form 10 filing. We do not source our data from the form 8 filing since it does not reliably contain full consolidated financial statements (income statement, balance sheet & cash flow statement).
"N/A" values (non-reported items)
The treatment of N/A values depends on the indicator. For example, if a company has no DEBT
on it's balance sheet then this means the value is zero. If a company doesn't report ASSETSC
(Current Assets) on it's balance sheet - this does not mean that the value is zero. In this instance the appropriate value is "N/A".
Sharadar fundamental indicators
Income Statement
Code | Name | Description | Unit type |
---|
CONSOLINC | Consolidated Income | The portion of profit or loss for the period; net of income taxes; which is attributable to the consolidated entity; before the deduction of [NetIncNCI]. | currency |
COR | Cost of Revenue | The aggregate cost of goods produced and sold and services rendered during the reporting period. | currency |
DPS | Dividends per Basic Common Share | Aggregate dividends declared during the period for each split-adjusted share of common stock outstanding. | USD/share |
EBIT | Earning Before Interest & Taxes (EBIT) | Earnings Before Interest and Tax is calculated by adding [TAXEXP] and [INTEXP] back to [NETINC]. | currency |
EBITUSD | Earning Before Interest & Taxes (USD) | [EBIT] in USD; converted by [FXUSD]. | USD |
EPS | Earnings per Basic Share | Earnings per share as calculated and reported by the company. Approximates to the amount of [NetIncCmn] for the period per each [SharesWA]. | currency/share |
EPSDIL | Earnings per Diluted Share | Earnings per diluted share as calculated and reported by the company. Approximates to the amount of [NetIncCmn] for the period per each [SharesWADil]. | currency/share |
EPSUSD | Earnings per Basic Share (USD) | [EPS] in USD; converted by [FXUSD]. | USD/share |
GP | Gross Profit | Aggregate revenue [REVENUE] less cost of revenue [COR] directly attributable to the revenue generation activity. | currency |
INTEXP | Interest Expense | Amount of the cost of borrowed funds accounted for as interest expense. | currency |
NETINC | Net Income | The portion of profit or loss for the period; net of income taxes; which is attributable to the parent after the deduction of [NetIncNCI] from [ConsolInc]; and before the deduction of [PrefDivIS]. | currency |
NETINCCMN | Net Income Common Stock | The amount of net income (loss) for the period due to common shareholders. Typically differs from [NetInc] to the parent entity due to the deduction of [PrefDivIS]. | currency |
NETINCCMNUSD | Net Income Common Stock (USD) | [NETINCCMN] in USD; converted by [FXUSD]. | USD |
NETINCDIS | Net Income from Discontinued Operations | Amount of income (loss) from a disposal group; net of income tax; reported as a separate component of income. | currency |
NETINCNCI | Net Income to Non-Controlling Interests | The portion of income which is attributable to non-controlling interest shareholders; subtracted from [ConsolInc] in order to obtain [NetInc]. | currency |
OPEX | Operating Expenses | Operating expenses represents the total expenditure on [SGnA]; [RnD] and other operating expense items; it excludes [CoR]. | currency |
OPINC | Operating Income | Operating income is a measure of financial performance before the deduction of [INTEXP]; [TAXEXP] and other Non-Operating items. It is calculated as [GP] minus [OPEX]. | currency |
PREFDIVIS | Preferred Dividends Income Statement Impact | Income statement item reflecting dividend payments to preferred stockholders. Subtracted from Net Income to Parent [NetInc] to obtain Net Income to Common Stockholders [NetIncCmn]. | currency |
REVENUE | Revenues | Amount of Revenue recognized from goods sold; services rendered; insurance premiums; or other activities that constitute an earning process. Interest income for financial institutions is reported net of interest expense and provision for credit losses. | currency |
REVENUEUSD | Revenues (USD) | [REVENUE] in USD; converted by [FXUSD]. | USD |
RND | Research and Development Expense | A component of [OpEx] representing the aggregate costs incurred in a planned search or critical investigation aimed at discovery of new knowledge with the hope that such knowledge will be useful in developing a new product or service. | currency |
SGNA | Selling General and Administrative Expense | A component of [OpEx] representing the aggregate total costs related to selling a firm's product and services; as well as all other general and administrative expenses. Direct selling expenses (for example; credit; warranty; and advertising) are expenses that can be directly linked to the sale of specific products. Indirect selling expenses are expenses that cannot be directly linked to the sale of specific products; for example telephone expenses; Internet; and postal charges. General and administrative expenses include salaries of non-sales personnel; rent; utilities; communication; etc. | currency |
SHARESWA | Weighted Average Shares | The weighted average number of shares or units issued and outstanding that are used by the company to calculate [EPS]; determined based on the timing of issuance ofshares or units in the period. | units |
SHARESWADIL | Weighted Average Shares Diluted | The weighted average number of shares or units issued and outstanding that are used by the company to calculate [EPSDil]; determined based on the timing of issuance of shares or units in the period. | units |
TAXEXP | Income Tax Expense | Amount of current income tax expense (benefit) and deferred income tax expense (benefit) pertaining to continuing operations. | currency |
Cash Flow Statement
Code | Name | Description | Unit type |
---|
CAPEX | Capital Expenditure | A component of [NCFI] representing the net cash inflow (outflow) associated with the acquisition & disposal of long-lived; physical & intangible assets that are used in the normal conduct of business to produce goods and services and are not intended for resale. Includes cash inflows/outflows to pay for construction of self-constructed assets & software. | currency |
DEPAMOR | Depreciation Amortization & Accretion | A component of operating cash flow representing the aggregate net amount of depreciation; amortization; and accretion recognized during an accounting period. As a non-cash item; the net amount is added back to net income when calculating cash provided by or used in operations using the indirect method. | currency |
NCF | Net Cash Flow / Change in Cash & Cash Equivalents | Principal component of the cash flow statement representing the amount of increase (decrease) in cash and cash equivalents. Includes [NCFO]; investing [NCFI] and financing [NCFF] for continuing and discontinued operations; and the effect of exchange rate changes on cash [NCFX]. | currency |
NCFBUS | Net Cash Flow - Business Acquisitions and Disposals | A component of [NCFI] representing the net cash inflow (outflow) associated with the acquisition & disposal of businesses; joint-ventures;affiliates; and other named investments. | currency |
NCFCOMMON | Issuance (Purchase) of Equity Shares | A component of [NCFF] representing the net cash inflow (outflow) from common equity changes. Includes additional capital contributions from share issuances and exercise of stock options; and outflow from share repurchases. | currency |
NCFDEBT | Issuance (Repayment) of Debt Securities | A component of [NCFF] representing the net cash inflow (outflow) from issuance (repayment) of debt securities. | currency |
NCFDIV | Payment of Dividends & Other Cash Distributions | A component of [NCFF] representing dividends and dividend equivalents paid on common stock and restricted stock units. | currency |
NCFF | Net Cash Flow from Financing | A component of [NCF] representing the amount of cash inflow (outflow) from financing activities; from continuing and discontinued operations. Principal components of financing cash flow are: issuance (purchase) of equity shares; issuance (repayment) of debt securities; and payment of dividends & other cash distributions. | currency |
NCFI | Net Cash Flow from Investing | A component of [NCF] representing the amount of cash inflow (outflow) from investing activities; from continuing and discontinued operations. Principal components of investing cash flow are: capital (expenditure) disposal of equipment [CAPEX]; business (acquisitions) disposition [NCFBUS] and investment (acquisition) disposal [NCFINV]. | currency |
NCFINV | Net Cash Flow - Investment Acquisitions and Disposals | A component of [NCFI] representing the net cash inflow (outflow) associated with the acquisition & disposal of investments; including marketable securities and loan originations. | currency |
NCFO | Net Cash Flow from Operations | A component of [NCF] representing the amount of cash inflow (outflow) from operating activities; from continuing and discontinued operations. | currency |
NCFX | Effect of Exchange Rate Changes on Cash | A component of Net Cash Flow [NCF] representing the amount of increase (decrease) from the effect of exchange rate changes on cash and cash equivalent balances held in foreign currencies. | currency |
SBCOMP | Share Based Compensation | A component of [NCFO] representing the total amount of noncash; equity-based employee remuneration. This may include the value of stock or unit options; amortizationof restricted stock or units; and adjustment for officers' compensation. As noncash; this element is an add back when calculating net cash generated by operating activities using the indirect method. | currency |
Balance Sheet
Code | Name | Description | Unit type |
---|
ACCOCI | Accumulated Other Comprehensive Income | A component of [EQUITY] representing the accumulated change in equity from transactions and other events and circumstances from non-owner sources; net of tax effect; at period end. Includes foreign currency translation items; certain pension adjustments; unrealized gains and losses on certain investments in debt and equity securities. | currency |
ASSETS | Total Assets | Sum of the carrying amounts as of the balance sheet date of all assets that are recognized. Major components are [CASHNEQ]; [INVESTMENTS];[INTANGIBLES]; [PPNENET];[TAXASSETS] and [RECEIVABLES]. | currency |
ASSETSC | Current Assets | The current portion of [ASSETS]; reported if a company operates a classified balance sheet that segments current and non-current assets. | currency |
ASSETSNC | Assets Non-Current | Amount of non-current assets; for companies that operate a classified balance sheet. Calculated as the different between Total Assets [ASSETS] and Current Assets [ASSETSC] | currency |
CASHNEQ | Cash and Equivalents | A component of [ASSETS] representing the amount of currency on hand as well as demand deposits with banks or financial institutions. | currency |
CASHNEQUSD | Cash and Equivalents (USD) | [CASHNEQ] in USD; converted by [FXUSD]. | USD |
DEBT | Total Debt | A component of [LIABILITIES] representing the total amount of current and non-current debt owed. Includes secured and unsecured bonds issued; commercial paper; notes payable; creditfacilities; lines of credit; capital lease obligations; and convertible notes. | currency |
DEBTC | Debt Current | The current portion of [DEBT]; reported if the company operates a classified balance sheet that segments current and non-current liabilities. | currency |
DEBTNC | Debt Non-Current | The non-current portion of [DEBT] reported if the company operates a classified balance sheet that segments current and non-current liabilities. | currency |
DEBTUSD | Total Debt (USD) | [DEBT] in USD; converted by [FXUSD]. | USD |
DEFERREDREV | Deferred Revenue | A component of [LIABILITIES] representing the carrying amount of consideration received or receivable on potential earnings that were not recognized as revenue; including sales; license fees; and royalties; but excluding interest income. | currency |
DEPOSITS | Deposit Liabilities | A component of [LIABILITIES] representing the total of all deposit liabilities held; including foreign and domestic; interest and noninterest bearing. May include demand deposits; saving deposits; Negotiable Order of Withdrawal and time deposits among others. | currency |
EQUITY | Shareholders Equity | A principal component of the balance sheet; in addition to [LIABILITIES] and [ASSETS]; that represents the total of all stockholders' equity (deficit) items; net of receivables from officers; directors; owners; and affiliates of the entity which are attributable to the parent. | currency |
EQUITYUSD | Shareholders Equity (USD) | [EQUITY] in USD; converted by [FXUSD]. | USD |
INTANGIBLES | Goodwill and Intangible Assets | A component of [ASSETS] representing the carrying amounts of all intangible assets and goodwill as of the balance sheet date; net of accumulated amortization and impairment charges. | currency |
INVENTORY | Inventory | A component of [ASSETS] representing the amount after valuation and reserves of inventory expected to be sold; or consumed within one year or operating cycle; if longer. | currency |
INVESTMENTS | Investments | A component of [ASSETS] representing the total amount of marketable and non-marketable securties; loans receivable and other invested assets. | currency |
INVESTMENTSC | Investments Current | The current portion of [INVESTMENTS]; reported if the company operates a classified balance sheet that segments current and non-current assets. | currency |
INVESTMENTSNC | Investments Non-Current | The non-current portion of [INVESTMENTS]; reported if the company operates a classified balance sheet that segments current and non-current assets. | currency |
LIABILITIES | Total Liabilities | Sum of the carrying amounts as of the balance sheet date of all liabilities that are recognized. Principal components are [DEBT]; [DEFERREDREV]; [PAYABLES];[DEPOSITS];and [TAXLIABILITIES]. | currency |
LIABILITIESC | Current Liabilities | The current portion of [LIABILITIES]; reported if the company operates a classified balance sheet that segments current and non-current liabilities. | currency |
LIABILITIESNC | Liabilities Non-Current | The non-current portion of [LIABILITIES]; reported if the company operates a classified balance sheet that segments current and non-current liabilities. | currency |
PAYABLES | Trade and Non-Trade Payables | A component of [LIABILITIES] representing trade and non-trade payables. | currency |
PPNENET | Property Plant & Equipment Net | A component of [ASSETS] representing the amount after accumulated depreciation; depletion and amortization of physical assets used in the normal conduct of business to produce goods and services and not intended for resale. | currency |
RECEIVABLES | Trade and Non-Trade Receivables | A component of [ASSETS] representing trade and non-trade receivables. | currency |
RETEARN | Accumulated Retained Earnings (Deficit) | A component of [EQUITY] representing the cumulative amount of the entities undistributed earnings or deficit. May only be reported annually by certain companies; rather than quarterly. | currency |
TAXASSETS | Tax Assets | A component of [ASSETS] representing tax assets and receivables. | currency |
TAXLIABILITIES | Tax Liabilities | A component of [LIABILITIES] representing outstanding tax liabilities. | currency |
Metrics
Code | Name | Description | Unit type |
---|
ASSETSAVG | Average Assets | Average asset value for the period used in calculation of [ROE] and [ROA]; derived from [ASSETS]. | currency |
ASSETTURNOVER | Asset Turnover | Asset turnover is a measure of a firms operating efficiency; calculated by dividing [REVENUE] by [ASSETSAVG]. Often a component of [DUPONTROE] analysis. | % |
BVPS | Book Value per Share | Measures the ratio between [EQUITY] and [SHARESWA]. | currency/share |
CURRENTRATIO | Current Ratio | The ratio between [ASSETSC] and [LIABILITIESC]; for companies that operate a classified balance sheet. | ratio |
DE | Debt to Equity Ratio | Measures the ratio between [LIABILITIES] and [EQUITY]. | ratio |
DIVYIELD | Dividend Yield | Dividend Yield measures the ratio between a company's [DPS] and its [PRICE]. | % |
EBITDA | Earnings Before Interest Taxes & Depreciation Amortization (EBITDA) | EBITDA is a non-GAAP accounting metric that is widely used when assessing the performance of companies; calculated by adding [DEPAMOR] back to [EBIT]. | currency |
EBITDAMARGIN | EBITDA Margin | Measures the ratio between a company's [EBITDA] and [REVENUE]. | % |
EBITDAUSD | Earnings Before Interest Taxes & Depreciation Amortization (USD) | [EBITDA] in USD; converted by [FXUSD]. | USD |
EBT | Earnings before Tax | Earnings Before Tax is calculated by adding [TAXEXP] back to [NETINC]. | currency |
EQUITYAVG | Average Equity | Average equity value for the period used in calculation of [ROE]; derived from [EQUITY]. | currency |
EV | Enterprise Value | Enterprise value is a measure of the value of a business as a whole; calculated as [MARKETCAP] plus [DEBTUSD] minus [CASHNEQUSD]. | USD |
EVEBIT | Enterprise Value over EBIT | Measures the ratio between [EV] and [EBITUSD]. | ratio |
EVEBITDA | Enterprise Value over EBITDA | Measures the ratio between [EV] and [EBITDAUSD]. | ratio |
FCF | Free Cash Flow | Free Cash Flow is a measure of financial performance calculated as [NCFO] minus [CAPEX]. | currency |
FCFPS | Free Cash Flow per Share | Free Cash Flow per Share is a valuation metric calculated by dividing [FCF] by [SHARESWA]. | currency/share |
FXUSD | Foreign Currency to USD Exchange Rate | The exchange rate used for the conversion of foreign currency to USD for non-US companies that do not report in USD. | ratio |
GROSSMARGIN | Gross Margin | Gross Margin measures the ratio between a company's [GP] and [REVENUE]. | % |
INVCAP | Invested Capital | Invested capital is an input into the calculation of [ROIC]; and is calculated as: [DEBT] plus [ASSETS] minus [INTANGIBLES] minus [CASHNEQ] minus [LIABILITIESC]. Please notethis calculation method is subject to change. | currency |
INVCAPAVG | Invested Capital Average | Average invested capital value for the period used in the calculation of [ROIC]; and derived from [INVCAP]. Invested capital is an input into the calculation of [ROIC]; and is calculated as: [DEBT] plus [ASSETS] minus [INTANGIBLES] minus [CASHNEQ] minus [LIABILITIESC]. Please note this calculation method is subject to change. | currency |
MARKETCAP | Market Capitalization | Represents the product of [SHARESBAS]; [PRICE] and [SHAREFACTOR]. | USD |
NETMARGIN | Profit Margin | Measures the ratio between a company's [NETINCCMN] and [REVENUE]. | % |
PAYOUTRATIO | Payout Ratio | The percentage of earnings paid as dividends to common stockholders. Calculated by dividing [DPS] by [EPSUSD]. | % |
PB | Price to Book Value | Measures the ratio between [MARKETCAP] and [EQUITYUSD]. | ratio |
PE | Price Earnings (Damodaran Method) | Measures the ratio between [MARKETCAP] and [NETINCCMNUSD] | ratio |
PE1 | Price to Earnings Ratio | An alternative to [PE] representing the ratio between [PRICE] and [EPSUSD]. | ratio |
PS | Price Sales (Damodaran Method) | Measures the ratio between a companies [MARKETCAP] and [REVENUEUSD]. | ratio |
PS1 | Price to Sales Ratio | An alternative calculation method to [PS]; that measures the ratio between a company's [PRICE] and it's [SPS]. | ratio |
ROA | Return on Average Assets | Return on assets measures how profitable a company is [NETINCCMN] relative to its total assets [ASSETSAVG]. | % |
ROE | Return on Average Equity | Return on equity measures a corporation's profitability by calculating the amount of [NETINCCMN] returned as a percentage of [EQUITYAVG]. | % |
ROIC | Return on Invested Capital | Return on Invested Capital is ratio estimated by dividing [EBIT] by [INVCAPAVG]. [INVCAP] is calculated as: [DEBT] plus [ASSETS] minus [INTANGIBLES] minus [CASHNEQ] minus [LIABILITIESC]. Please note this calculation method is subject to change. | % |
ROS | Return on Sales | Return on Sales is a ratio to evaluate a company's operational efficiency; calculated by dividing [EBIT] by [REVENUE]. ROS is often a component of [DUPONTROE]. | % |
SPS | Sales per Share | Sales per Share measures the ratio between [REVENUEUSD] and [SHARESWA]. | USD/share |
TANGIBLES | Tangible Asset Value | The value of tangibles assets calculated as the difference between [ASSETS] and [INTANGIBLES]. | currency |
TBVPS | Tangible Assets Book Value per Share | Measures the ratio between [TANGIBLES] and [SHARESWA]. | currency/share |
WORKINGCAPITAL | Working Capital | Working capital measures the difference between [ASSETSC] and [LIABILITIESC]. | currency |
Entity
Code | Name | Description | Unit type |
---|
CALENDARDATE | Calendar Date | Calendar Date is a column field available in the new datatable API which represents the normalized [REPORTPERIOD]. For example; if the report period is "2015-09-26"; the calendar date will be "2015-09-30" for quarterly and trailing-twelve-month dimensions (ARQ;MRQ;ART;MRT); and "2015-12-31" for annual dimensions (ARY;MRY). This is useful when collating data across multiple companies that may have different fiscal periods. | date (YYYY-MM-DD) |
DATEKEY | Date Key | Date Key is a column field available in the new datatable API which represents the SEC filing date for AR dimensions (ARQ;ART;ARY); and the [REPORTPERIOD] for MR dimensions (MRQ;MRT;MRY). In addition; this is the observation date used for [PRICE] based data such as [MARKETCAP]; [PRICE] and [PE]. | date (YYYY-MM-DD) |
DIMENSION | Dimension | Dimension is a column field available in the new datatable API which allow you to take different dimensional views of data over time. ARQ: Quarterly; excluding restatements; MRQ: Quarterly; including restatements; ARY: annual; excluding restatements; MRY: annual; including restatements; ART: trailing-twelve-months; excluding restatements; MRT: trailing-twelve-months; including restatements. | text |
LASTUPDATED | Last Updated Date | Last Updated is a column field available in the new datatable API which represents the last date that this database entry was updated; which is useful to users when updating their local records. | date (YYYY-MM-DD) |
PRICE | Share Price (Adjusted Close) | The price per common share adjusted for stock splits but not adjusted for dividends; used in the computation of [PE1]; [PS1]; [DIVYIELD] and [SPS]. | USD/share |
REPORTPERIOD | Report Period | Report Period is a column field in the new datatable API which represents the end date of the fiscal period. It is equivalent to value in the [FILINGDATE] datasets available under the old API. | date (YYYY-MM-DD) |
SHAREFACTOR | Share Factor | Share factor is a multiplicant in the calculation of [MARKETCAP] and is used to adjust for: American Depository Receipts (ADRs) that represent more or less than 1 underlying share; and; companies which have different earnings share for different share classes (eg Berkshire Hathaway - BRKB). | ratio |
SHARESBAS | Shares (Basic) | The number of shares or other units outstanding of the entity's capital or common stock or other ownership interests; as stated on the cover of related periodic report (10-K/10-Q); after adjustment for stock splits. | units |
Sharadar insiders
This database provides insider holdings and transactions for more than 15,000 issuers and 200,000 insiders. Data are sourced from SEC form 3, 4 & 5 filings.
Collect Sharadar insiders
To collect Sharadar insiders data, specify a country (use FREE
for sample data):
$ quantrocket fundamental collect-sharadar-insiders --country 'US'
status: the fundamental data will be collected asynchronously
>>> from quantrocket.fundamental import collect_sharadar_insiders
>>> collect_sharadar_insiders(country="US")
{'status': 'the fundamental data will be collected asynchronously'}
$ curl -X POST 'http://houston/fundamental/sharadar/insiders?country=US'
{"status": "the fundamental data will be collected asynchronously"}
Collecting the full dataset takes less than 5 minutes. Monitor flightlog for completion:
quantrocket.fundamental: INFO Collecting Sharadar US insider holdings data
quantrocket.fundamental: INFO Collecting updated Sharadar US securities listings
quantrocket.fundamental: INFO Finished collecting Sharadar US insider holdings data
Query Sharadar insiders
The data can be queried by sid, universe, and date range:
$ quantrocket fundamental sharadar-insiders -i 'FIBBG000B9XRY4' -o aapl_insiders.csv
$ csvlook aapl_insiders.csv --max-columns 9 --max-rows 5
| Sid | TICKER | FILINGDATE | FORMTYPE | ISSUERNAME | OWNERNAME | OFFICERTITLE | ISDIRECTOR | ISOFFICER | ... |
| -------------- | ------ | ---------- | -------- | ---------- | ------------------- | --------------------- | ---------- | --------- | --- |
| FIBBG000B9XRY4 | AAPL | 2005-01-05 | 4 | APPLE INC | RUBINSTEIN JONATHAN | Senior Vice President | False | True | ... |
| FIBBG000B9XRY4 | AAPL | 2005-01-05 | 4 | APPLE INC | RUBINSTEIN JONATHAN | Senior Vice President | False | True | ... |
| FIBBG000B9XRY4 | AAPL | 2005-01-11 | 4 | APPLE INC | SERLET BERTRAND | Senior Vice President | False | True | ... |
>>> from quantrocket.fundamental import download_sharadar_insiders
>>> download_sharadar_insiders(filepath_or_buffer="aapl_insiders.csv", sids="FIBBG000B9XRY4")
>>> insiders = pd.read_csv("aapl_insiders.csv", parse_dates=["FILINGDATE"])
>>> insiders.tail()
Sid TICKER FILINGDATE FORMTYPE ISSUERNAME OWNERNAME OFFICERTITLE
0 FIBBG000B9XRY4 AAPL 2005-01-05 4 APPLE INC RUBINSTEIN JONATHAN Senior Vice President
1 FIBBG000B9XRY4 AAPL 2005-01-05 4 APPLE INC RUBINSTEIN JONATHAN Senior Vice President
3 FIBBG000B9XRY4 AAPL 2005-01-11 4 APPLE INC SERLET BERTRAND Senior Vice President
$ curl -X GET 'http://houston/fundamental/sharadar/insiders.csv?sids=FIBBG000B9XRY4' > aapl_insiders.csv
$ csvlook aapl_insiders.csv --max-columns 9 --max-rows 5
| Sid | TICKER | FILINGDATE | FORMTYPE | ISSUERNAME | OWNERNAME | OFFICERTITLE | ISDIRECTOR | ISOFFICER | ... |
| -------------- | ------ | ---------- | -------- | ---------- | ------------------- | --------------------- | ---------- | --------- | --- |
| FIBBG000B9XRY4 | AAPL | 2005-01-05 | 4 | APPLE INC | RUBINSTEIN JONATHAN | Senior Vice President | False | True | ... |
| FIBBG000B9XRY4 | AAPL | 2005-01-05 | 4 | APPLE INC | RUBINSTEIN JONATHAN | Senior Vice President | False | True | ... |
| FIBBG000B9XRY4 | AAPL | 2005-01-11 | 4 | APPLE INC | SERLET BERTRAND | Senior Vice President | False | True | ... |
Sharadar insiders data guide
A sample record from the dataset including field descriptions is shown below:
Sid: "FIBBG000B9XRY4"
TICKER: "AAPL"
FILINGDATE: "2005-01-05"
FORMTYPE: 4
ISSUERNAME: "APPLE INC"
OWNERNAME: "RUBINSTEIN JONATHAN"
OFFICERTITLE: "Senior Vice President"
ISDIRECTOR: "N"
ISOFFICER: "Y"
ISTENPERCENTOWNER: "N"
TRANSACTIONDATE: "2005-01-03"
SECURITYADCODE: "ND"
TRANSACTIONCODE: "M"
SHARESOWNEDBEFORETRANSACTION: 45087
TRANSACTIONSHARES: -34000
SHARESOWNEDFOLLOWINGTRANSACTION: 11087
TRANSACTIONPRICEPERSHARE: 17.313
TRANSACTIONVALUE: 588642
SECURITYTITLE: "Common Stock"
DIRECTORINDIRECT: "D"
NATUREOFOWNERSHIP: null
DATEEXERCISABLE: null
PRICEEXERCISABLE: null
EXPIRATIONDATE: null
ROWNUM: 1
Update schedule
Data is updated daily by 5 AM New York time.
Notes from the data provider
- data are sourced from SEC form 3, 4 and 5.
- The
SHARESOWNEDBEFORETRANSACTION
and SHARESOWNEDFOLLOWINGTRANSACTION
are as reported in the underlying SEC filings. There is some complexity to them which it is necessary to bear in mind. At a minimum these fields represent separate sub-totals for each of derivative and non-derivative holdings, identifiable through the SECURITYADCODE
field. Some filers segment this further to represent subtotals for DIRECTORINDIRECT
holdings and/or SECURITYTITLE
. - data are currently not adjusted for stock splits.
- where a filing has been subsequently restated the
FORMTYPE
field of the restated filing will be prepended with "RESTATED".
Sharadar institutions
This dataset provides institutional investor holdings data for 20,000+ issuers and approximately 6,000 investors, covering all types of securities reported, categorised into: common shares, funds, calls, puts, warrants, preferred stock, and debt.
Data are sourced from SEC form 13F filings, which requires that medium to large institutional investment managers report details of certain US security holdings.
Collect Sharadar institutions
To collect Sharadar institutional ownership data, specify a country (use FREE
for sample data):
$ quantrocket fundamental collect-sharadar-institutions --country 'US'
status: the fundamental data will be collected asynchronously
>>> from quantrocket.fundamental import collect_sharadar_institutions
>>> collect_sharadar_institutions(country="US")
{'status': 'the fundamental data will be collected asynchronously'}
$ curl -X POST 'http://houston/fundamental/sharadar/institutions?country=US'
{"status": "the fundamental data will be collected asynchronously"}
Monitor flightlog for completion:
quantrocket.fundamental: INFO Collecting Sharadar US institutional investor data
quantrocket.fundamental: INFO Collecting updated Sharadar US securities listings
quantrocket.fundamental: INFO Finished collecting Sharadar US institutional investor data
By default the collected data is aggregated by security; that is, there is a separate record per security per quarter. It is also possible to collect detailed, non-aggregated records; that is, a separate record per investor per security per quarter. Use the --detail/detail=True
parameter. Detailed data is stored in a separate database, allowing you to collect both the detailed and aggregated views of the data:
$ quantrocket fundamental collect-sharadar-institutions --country 'US' --detail
status: the fundamental data will be collected asynchronously
>>> from quantrocket.fundamental import collect_sharadar_institutions
>>> collect_sharadar_institutions(country="US", detail=True)
{'status': 'the fundamental data will be collected asynchronously'}
$ curl -X POST 'http://houston/fundamental/sharadar/institutions?country=US&detail=true'
{"status": "the fundamental data will be collected asynchronously"}
Query Sharadar institutions
The data can be queried by sid, universe, and date range:
$ quantrocket fundamental sharadar-institutions -i 'FIBBG000B9XRY4' -o aapl_institutions.csv
$ csvlook aapl_institutions.csv --max-columns 9 --max-rows 5
Sid | CALENDARDATE | TICKER | NAME | SHRHOLDERS | CLLHOLDERS | PUTHOLDERS | WNTHOLDERS | DBTHOLDERS | ... |
| -------------- | ------------ | ------ | --------- | ---------- | ---------- | ---------- | ---------- | ---------- | --- |
| FIBBG000B9XRY4 | 2013-06-30 | AAPL | APPLE INC | 1,855 | 89 | 61 | False | 0 | ... |
| FIBBG000B9XRY4 | 2013-09-30 | AAPL | APPLE INC | 1,881 | 107 | 63 | False | 0 | ... |
| FIBBG000B9XRY4 | 2013-12-31 | AAPL | APPLE INC | 2,066 | 86 | 57 | False | 0 | ... |
| FIBBG000B9XRY4 | 2014-03-31 | AAPL | APPLE INC | 2,040 | 81 | 67 | False | 0 | ... |
| FIBBG000B9XRY4 | 2014-06-30 | AAPL | APPLE INC | 2,110 | 98 | 66 | False | 0 | ... |
>>> from quantrocket.fundamental import download_sharadar_institutions
>>> download_sharadar_institutions(filepath_or_buffer="aapl_institutions.csv", sids="FIBBG000B9XRY4")
>>> institutions = pd.read_csv("aapl_institutions.csv", parse_dates=["CALENDARDATE"])
>>> institutions.head()
Sid CALENDARDATE TICKER NAME SHRHOLDERS CLLHOLDERS PUTHOLDERS ...
0 FIBBG000B9XRY4 2013-06-30 AAPL APPLE INC 1855 89 61
1 FIBBG000B9XRY4 2013-09-30 AAPL APPLE INC 1881 107 63
2 FIBBG000B9XRY4 2013-12-31 AAPL APPLE INC 2066 86 57
3 FIBBG000B9XRY4 2014-03-31 AAPL APPLE INC 2040 81 67
4 FIBBG000B9XRY4 2014-06-30 AAPL APPLE INC 2110 98 66
$ curl -X GET 'http://houston/fundamental/sharadar/institutions.csv?sids=FIBBG000B9XRY4' > aapl_institutions.csv
$ csvlook aapl_institutions.csv --max-columns 9 --max-rows 5
Sid | CALENDARDATE | TICKER | NAME | SHRHOLDERS | CLLHOLDERS | PUTHOLDERS | WNTHOLDERS | DBTHOLDERS | ... |
| -------------- | ------------ | ------ | --------- | ---------- | ---------- | ---------- | ---------- | ---------- | --- |
| FIBBG000B9XRY4 | 2013-06-30 | AAPL | APPLE INC | 1,855 | 89 | 61 | False | 0 | ... |
| FIBBG000B9XRY4 | 2013-09-30 | AAPL | APPLE INC | 1,881 | 107 | 63 | False | 0 | ... |
| FIBBG000B9XRY4 | 2013-12-31 | AAPL | APPLE INC | 2,066 | 86 | 57 | False | 0 | ... |
| FIBBG000B9XRY4 | 2014-03-31 | AAPL | APPLE INC | 2,040 | 81 | 67 | False | 0 | ... |
| FIBBG000B9XRY4 | 2014-06-30 | AAPL | APPLE INC | 2,110 | 98 | 66 | False | 0 | ... |
To query detailed data, use the --detail/detail=True
parameter.
$ quantrocket fundamental sharadar-institutions -i 'FIBBG000B9XRY4' --detail -o aapl_institutions.csv
$ csvlook aapl_institutions.csv --max-columns 9 --max-rows 5
| Sid | TICKER | INVESTORNAME | SECURITYTYPE | CALENDARDATE | VALUE | UNITS | PRICE |
| -------------- | ------ | --------------------------- | ------------ | ------------ | ---------- | ------- | ----- |
| FIBBG000B9XRY4 | AAPL | 1832 ASSET MANAGEMENT LP | SHR | 2013-06-30 | 16,159,000 | 40,910 | 394 |
| FIBBG000B9XRY4 | AAPL | 1919 INVESTMENT COUNSEL LLC | SHR | 2013-06-30 | 64,522,000 | 162,716 | 396 |
| FIBBG000B9XRY4 | AAPL | 1ST GLOBAL ADVISORS INC | SHR | 2013-06-30 | 250,000 | 630 | 396 |
| FIBBG000B9XRY4 | AAPL | 1ST SOURCE BANK | SHR | 2013-06-30 | 4,571,000 | 11,527 | 396 |
| FIBBG000B9XRY4 | AAPL | 300 NORTH CAPITAL LLC | SHR | 2013-06-30 | 1,496,000 | 3,776 | 396 |
>>> from quantrocket.fundamental import download_sharadar_institutions
>>> download_sharadar_institutions(filepath_or_buffer="aapl_institutions.csv", sids="FIBBG000B9XRY4", detail=True)
>>> institutions = pd.read_csv("aapl_institutions.csv", parse_dates=["CALENDARDATE"])
>>> institutions.head()
Sid TICKER INVESTORNAME SECURITYTYPE CALENDARDATE VALUE UNITS
0 FIBBG000B9XRY4 AAPL 1832 ASSET MANAGEMENT LP SHR 2013-06-30 16159000.0 40910
1 FIBBG000B9XRY4 AAPL 1919 INVESTMENT COUNSEL LLC SHR 2013-06-30 64522000.0 162716
2 FIBBG000B9XRY4 AAPL 1ST GLOBAL ADVISORS INC SHR 2013-06-30 250000.0 630
3 FIBBG000B9XRY4 AAPL 1ST SOURCE BANK SHR 2013-06-30 4571000.0 11527
4 FIBBG000B9XRY4 AAPL 300 NORTH CAPITAL LLC SHR 2013-06-30 1496000.0 3776
$ curl -X GET 'http://houston/fundamental/sharadar/institutions.csv?sids=FIBBG000B9XRY4&detail=true' > aapl_institutions.csv
$ csvlook aapl_institutions.csv --max-columns 9 --max-rows 5
| Sid | TICKER | INVESTORNAME | SECURITYTYPE | CALENDARDATE | VALUE | UNITS | PRICE |
| -------------- | ------ | --------------------------- | ------------ | ------------ | ---------- | ------- | ----- |
| FIBBG000B9XRY4 | AAPL | 1832 ASSET MANAGEMENT LP | SHR | 2013-06-30 | 16,159,000 | 40,910 | 394 |
| FIBBG000B9XRY4 | AAPL | 1919 INVESTMENT COUNSEL LLC | SHR | 2013-06-30 | 64,522,000 | 162,716 | 396 |
| FIBBG000B9XRY4 | AAPL | 1ST GLOBAL ADVISORS INC | SHR | 2013-06-30 | 250,000 | 630 | 396 |
| FIBBG000B9XRY4 | AAPL | 1ST SOURCE BANK | SHR | 2013-06-30 | 4,571,000 | 11,527 | 396 |
| FIBBG000B9XRY4 | AAPL | 300 NORTH CAPITAL LLC | SHR | 2013-06-30 | 1,496,000 | 3,776 | 396 |
In Python, you can use a DataFrame of prices (or any DataFrame with a DatetimeIndex and sids as columns) to get Sharadar institutional data (aggregated by security) that is aligned to the price data.
>>> from quantrocket import get_prices
>>> prices = get_prices("usstock-1d", start_date="2018-04-16", fields="Close")
>>> closes = prices.loc["Close"]
>>> from quantrocket.fundamental import get_sharadar_institutions_reindexed_like
>>> insti = get_sharadar_institutions_reindexed_like(closes, fields=["SHRVALUE"])
The resulting DataFrame can be thought of as several stacked DataFrames, with a MultiIndex consisting of the field and the date. The columns are sids, matching the input DataFrame. The DataFrame is forward-filled, giving each field's latest value as of the given date.
>>> insti.head()
Sid FIBBG000B9XRY4 FIBBG000BVPV84 FIBBG000CL9VN6 FIBBG000MM2P62
Field Date
SHRVALUE 2019-12-16 5.889395e+11 4.816904e+11 9.471188e+10 3.238884e+11
2019-12-17 5.889395e+11 4.816904e+11 9.471188e+10 3.238884e+11
2019-12-18 5.889395e+11 4.816904e+11 9.471188e+10 3.238884e+11
2019-12-19 5.889395e+11 4.816904e+11 9.471188e+10 3.238884e+11
2019-12-20 5.889395e+11 4.816904e+11 9.471188e+10 3.238884e+11
By default, values are shifted forward by 45 days to account for the reporting lag (see the data provider's notes below); this can be controled with the shift
parameter.
You can use .loc
to isolate a particular indicator:
>>> insti_share_values = insti.loc["SHRVALUE"]
For best performance, make two separate calls to get_sharadar_institutions_reindexed_like
to retrieve numeric (integer or float) vs non-numeric (string or date) fields. Pandas loads numeric fields in an optimized format compared to non-numeric fields, but mixing numeric and non-numeric fields prevents Pandas from using this optimized format, resulting in slower loads and higher memory consumption. See the Sharadar fundamentals docs for an example.
Sharadar institutions data guide
A sample aggregated (non-detailed) record from the dataset including field descriptions is shown below:
Sid: "FIBBG000B9XRY4"
CALENDARDATE: "2013-06-30"
TICKER: "AAPL"
NAME: "APPLE INC"
SHRHOLDERS: 1855
CLLHOLDERS: 89
PUTHOLDERS: 61
WNTHOLDERS: 0
DBTHOLDERS: 0
PRFHOLDERS: 0
FNDHOLDERS: 0
UNDHOLDERS: 0
SHRUNITS: 552964087
CLLUNITS: 46560649
PUTUNITS: 49769940
WNTUNITS: 0
DBTUNITS: 0
PRFUNITS: 0
FNDUNITS: 0
UNDUNITS: 0
SHRVALUE: 219200769570
CLLVALUE: 17952276435
PUTVALUE: 20366468206
WNTVALUE: 0
DBTVALUE: 0
PRFVALUE: 0
FNDVALUE: 0
UNDVALUE: 0
TOTALVALUE: 257519514211
PERCENTOFTOTAL: 1.46
A sample detailed record is shown below:
Sid: "FIBBG000B9XRY4"
TICKER: "AAPL"
INVESTORNAME: "WAVERTON INVESTMENT MANAGEMENT LTD"
SECURITYTYPE: "SHR"
CALENDARDATE: "2013-06-30"
VALUE: 17385000
UNITS: 43842
PRICE: 396
Update schedule
Data is updated daily by 5 AM New York time.
Notes from the data provider
- Data are sourced from SEC form 13F filings, which require that medium to large institutional investment managers report details of certain US security holdings. This means that the database may not contain: the smaller investors in a particular security; 100% of the securities that an investor holds; and the large investors in a small security if that investor is not large enough to be subject to SEC form 13F disclosure. More information on SEC form 13F reporting can be found on the SEC's website.
- Reporting by large managers is generally of high quality, however, there is a small percentage of reporting errors that are made. We identify and correct many but not all of these, and are continuously improving our efforts to do so where possible.
- Where errors are made, the reporting investment manager may restate their prior prior holdings. We will update our records accordingly and always present the most up to date record of holdings for a particular period.
- The reporting deadline is 45 days after the end of the quarter. For example by May 15th for the quarter ending March 31st. As such the most recent quarter holdings is typically incomplete until the end of this 45 day deadline as a high percentage of investors report their holdings as late as possible.
- On very limited occasions investors may have permission to delay disclosure of certain new holdings, for example Berkshire Hathaway has done so in the past. This means that from time-to-time there is a small window after the 45 day reporting deadline where newly reported data is incomplete for a particular investor, until they report the new holdings.
- Investors occasionally report securities where either the issuer or share class are unidentifiable. Generally this is the case when the investor is reporting securities which are not required to be reported to the SEC, eg for private companies or for foreign listed stocks. We assign these the UND security type, and the ticker U10D.
- Data is currently not adjusted for stock splits.
This dataset provides corporate events data as reported on SEC Form 8-K.
To collect Sharadar SEC Form 8-K data, specify the country as US
(use FREE
for sample data):
$ quantrocket fundamental collect-sharadar-sec8 --country 'US'
status: the fundamental data will be collected asynchronously
>>> from quantrocket.fundamental import collect_sharadar_sec8
>>> collect_sharadar_sec8(country="US")
{'status': 'the fundamental data will be collected asynchronously'}
$ curl -X POST 'http://houston/fundamental/sharadar/sec8?country=US'
{"status": "the fundamental data will be collected asynchronously"}
Monitor flightlog for completion:
quantrocket.fundamental: INFO Collecting Sharadar US SEC Form 8-K events
quantrocket.fundamental: INFO Collecting updated Sharadar US securities listings
quantrocket.fundamental: INFO Finished collecting Sharadar US SEC Form 8-K events
The data can be queried by sid, universe, date range, or event code:
$ quantrocket fundamental sharadar-sec8 --event-codes '13' -o bankruptcies.csv
$ csvlook bankruptcies.csv --max-rows 5
| Sid | DATE | TICKER | EVENTCODE |
| -------------- | ---------- | ------ | --------- |
| FIBBG000BXNJ07 | 1994-01-05 | CY | 13 |
| FIBBG000BCPB71 | 1994-01-06 | AVT | 13 |
| FIBBG000BRKN86 | 1994-01-20 | PPW | 13 |
| FIBBG000DM86Y7 | 1994-01-21 | CCI1 | 13 |
| FIBBG000BKFZM4 | 1994-01-24 | GLW | 13 |
>>> from quantrocket.fundamental import download_sharadar_sec8
>>> download_sharadar_sec8(filepath_or_buffer="bankruptcies.csv", event_codes=[13])
>>> bankruptcies = pd.read_csv("bankruptcies.csv", parse_dates=["DATE"])
>>> bankruptcies.head()
Sid DATE TICKER EVENTCODE
0 FIBBG000BXNJ07 1994-01-05 CY 13
1 FIBBG000BCPB71 1994-01-06 AVT 13
2 FIBBG000BRKN86 1994-01-20 PPW 13
3 FIBBG000DM86Y7 1994-01-21 CCI1 13
4 FIBBG000BKFZM4 1994-01-24 GLW 13
$ curl -X GET 'http://houston/fundamental/sharadar/sec8.csv?event_codes=13' > bankruptcies.csv
$ csvlook bankruptcies.csv --max-rows 5
| Sid | DATE | TICKER | EVENTCODE |
| -------------- | ---------- | ------ | --------- |
| FIBBG000BXNJ07 | 1994-01-05 | CY | 13 |
| FIBBG000BCPB71 | 1994-01-06 | AVT | 13 |
| FIBBG000BRKN86 | 1994-01-20 | PPW | 13 |
| FIBBG000DM86Y7 | 1994-01-21 | CCI1 | 13 |
| FIBBG000BKFZM4 | 1994-01-24 | GLW | 13 |
In Python, you can use a DataFrame of prices (or any DataFrame with a DatetimeIndex and sids as columns) to get Sharadar SEC Form 8-K data that is aligned to the price data.
>>> from quantrocket import get_prices
>>> prices = get_prices("usstock-1d", start_date="2018-04-16", fields="Close")
>>> closes = prices.loc["Close"]
>>> from quantrocket.fundamental import get_sharadar_sec8_reindexed_like
>>> filed_for_bankruptcy = get_sharadar_sec8_reindexed_like(closes, event_codes=[13])
The function returns a Boolean DataFrame indicating whether the company filed SEC Form 8-K on that date for any of the requested event_codes
. The columns and index match the input DataFrame.
>>> filed_for_bankruptcy.head()
Sid FIBBG000B9XRY4 FIBBG000PX3XC0 FIBBG009S3NB30
Date
2020-03-30 False False False
2020-03-31 False False False
2020-04-01 False True False
2020-04-02 False False False
2020-04-03 False False False
The SEC Form 8-K event codes are shown below:
11: 'Entry into a Material Definitive Agreement'
12: 'Termination of a Material Definitive Agreement'
13: 'Bankruptcy or Receivership'
14: 'Mine Safety: 'Reporting of Shutdowns and Patterns of Violations'
15: 'Receipt of an Attorney's Written Notice Pursuant to 17 CFR 205.3(d)'
21: 'Completion of Acquisition or Disposition of Assets'
22: 'Results of Operations and Financial Condition'
23: 'Creation of a Direct Financial Obligation or an Obligation under an Off-Balance Sheet Arrangement of a Registrant'
24: 'Triggering Events That Accelerate or Increase a Direct Financial Obligation or an Obligation under an Off-Balance Sheet Arrangement'
25: 'Cost Associated with Exit or Disposal Activities'
26: 'Material Impairments'
31: 'Notice of Delisting or Failure to Satisfy a Continued Listing Rule or Standard; Transfer of Listing'
32: 'Unregistered Sales of Equity Securities'
33: 'Material Modifications to Rights of Security Holders'
34: 'Schedule 13G Filing'
35: 'Schedule 13D Filing'
36: 'Notice under Rule 12b25 of inability to timely file all or part of a Form 10-K or 10-Q'
40: 'Changes in Registrant's Certifying Accountant'
41: 'Changes in Registrant's Certifying Accountant'
42: 'Non-Reliance on Previously Issued Financial Statements or a Related Audit Report or Completed Interim Review'
51: 'Changes in Control of Registrant'
52: 'Departure of Directors or Certain Officers; Election of Directors; Appointment of Certain Officers: Compensatory Arrangements of Certain Officers'
53: 'Amendments to Articles of Incorporation or Bylaws; and/or Change in Fiscal Year'
54: 'Temporary Suspension of Trading Under Registrant's Employee Benefit Plans'
55: 'Amendments to the Registrant's Code of Ethics; or Waiver of a Provision of the Code of Ethics'
56: 'Change in Shell Company Status'
57: 'Submission of Matters to a Vote of Security Holders'
58: 'Shareholder Nominations Pursuant to Exchange Act Rule 14a-11'
61: 'ABS Informational and Computational Material'
62: 'Change of Servicer or Trustee'
63: 'Change in Credit Enhancement or Other External Support'
64: 'Failure to Make a Required Distribution'
65: 'Securities Act Updating Disclosure'
71: 'Regulation FD Disclosure'
81: 'Other Events'
91: 'Financial Statements and Exhibits'
Update schedule
Data is updated daily by 5 AM New York time.
Sharadar S&P 500
This dataset provides historical and current additions to and removals from the S&P 500 index.
Collect Sharadar S&P 500
To collect Sharadar S&P 500 changes, specify the country as US
(or use FREE
for sample data):
$ quantrocket fundamental collect-sharadar-sp500 --country 'US'
status: the fundamental data will be collected asynchronously
>>> from quantrocket.fundamental import collect_sharadar_sp500
>>> collect_sharadar_sp500(country="US")
{'status': 'the fundamental data will be collected asynchronously'}
$ curl -X POST 'http://houston/fundamental/sharadar/sp500?country=US'
{"status": "the fundamental data will be collected asynchronously"}
Monitor flightlog for completion:
quantrocket.fundamental: INFO Collecting Sharadar US S&P 500 index constituents
quantrocket.fundamental: INFO Collecting updated Sharadar US securities listings
quantrocket.fundamental: INFO Finished collecting Sharadar US S&P 500 index constituents
Query Sharadar S&P 500
The data can be queried by sid, universe, or date range and shows index additions and removals:
$ quantrocket fundamental sharadar-sp500 --start-date '2019-10-01' -o sp500_changes.csv
$ csvlook sp500_changes.csv --max-rows 5
| Sid | DATE | ACTION | TICKER | NAME | ... |
| -------------- | ---------- | ------- | ------ | -------------------- | --- |
| FIBBG000BHCYJ1 | 2019-10-03 | removed | NKTR | Nektar Therapeutics | ... |
| FIBBG000JWD753 | 2019-10-03 | added | LVS | Las Vegas Sands Corp | ... |
| FIBBG000BFC8J2 | 2019-11-21 | removed | CELG | Celgene Corp | ... |
| FIBBG000M1R011 | 2019-11-21 | added | NOW | ServiceNow Inc | ... |
| FIBBG000DHSPT0 | 2019-12-05 | removed | VIAB | Viacom Inc | ... |
>>> from quantrocket.fundamental import download_sharadar_sp500
>>> download_sharadar_sp500(filepath_or_buffer="sp500_changes.csv", start_date="2019-10-01")
>>> sp500_changes = pd.read_csv("sp500_changes.csv", parse_dates=["DATE"])
>>> sp500_changes.head()
Sid DATE ACTION TICKER NAME ...
0 FIBBG000BHCYJ1 2019-10-03 removed NKTR Nektar Therapeutics
1 FIBBG000JWD753 2019-10-03 added LVS Las Vegas Sands Corp
2 FIBBG000BFC8J2 2019-11-21 removed CELG Celgene Corp
3 FIBBG000M1R011 2019-11-21 added NOW ServiceNow Inc
4 FIBBG000DHSPT0 2019-12-05 removed VIAB Viacom Inc
$ curl -X GET 'http://houston/fundamental/sharadar/sp500.csv?start_date=2019-10-01' > sp500_changes.csv
$ csvlook sp500_changes.csv --max-rows 5
| Sid | DATE | ACTION | TICKER | NAME | ... |
| -------------- | ---------- | ------- | ------ | -------------------- | --- |
| FIBBG000BHCYJ1 | 2019-10-03 | removed | NKTR | Nektar Therapeutics | ... |
| FIBBG000JWD753 | 2019-10-03 | added | LVS | Las Vegas Sands Corp | ... |
| FIBBG000BFC8J2 | 2019-11-21 | removed | CELG | Celgene Corp | ... |
| FIBBG000M1R011 | 2019-11-21 | added | NOW | ServiceNow Inc | ... |
| FIBBG000DHSPT0 | 2019-12-05 | removed | VIAB | Viacom Inc | ... |
In Python, you can use a DataFrame of prices (or any DataFrame with a DatetimeIndex and sids as columns) to get Sharadar S&P 500 constituents data that is aligned to the price data.
>>> from quantrocket import get_prices
>>> prices = get_prices("usstock-1d", start_date="2018-04-16", fields="Close")
>>> closes = prices.loc["Close"]
>>> from quantrocket.fundamental import get_sharadar_sp500_reindexed_like
>>> are_in_sp500 = get_sharadar_sp500_reindexed_like(closes)
The function returns a Boolean DataFrame indicating whether the security was in the S&P 500 as of each date. The columns and index match the input DataFrame.
>>> are_in_sp500.head()
Sid FIBBG000D6L294 FIBBG000MM2P62 FIBBG000PX3XC0 FIBBG009S3NB30
Date
2020-02-28 True True False True
2020-03-02 True True False True
2020-03-03 False True False True
2020-03-04 False True False True
2020-03-05 False True False True
Sharadar S&P 500 data guide
A sample record from the dataset including field descriptions is shown below:
Sid: "FIBBG000D6L294"
DATE: "2020-03-03"
ACTION: "removed"
TICKER: "XEC"
NAME: "Cimarex Energy Co"
CONTRATICKER: "IR"
CONTRANAME: "Ingersoll Rand Inc"
NOTE: null
Update schedule
Data is updated daily by 5 AM New York time.
Fundamentals query cache
The fundamental service utilizes a file cache to improve query performance. When you query any of the fundamentals endpoints, the data is loaded from the database and the resulting file is cached by the fundamental service. Later, if you query again using exactly the same query parameters, the cached file will be returned without hitting the database, resulting in a faster response. Whenever you collect fundamental data, the cached files are invalidated, forcing the subsequent query to hit the database in order to see the refreshed data.
Clear the cache
File caching usually requires no special action or awareness by the user, but there are a few edge cases where you might need to clear the cache manually:
- if you query fundamentals by universe, then change the constituents of the universe, then query again with the same parameters, the fundamental service won't know the universe constituents changed and will return the cached file that was generated using the original universe constituents
- if you query fundamentals, then overwrite the database by pulling another version of the database from S3, then query again with the same parameters, the fundamental service will return the cached file that was generated using the original database
If a fundamentals query is not returning expected results and you suspect caching is to blame, you can either vary the query parameters slightly (for example change the date range) to bypass the cache, or re-create the fundamental container (not just restart it) to clear all cached files.
Real-time Data
QuantRocket provides a powerful feature set for collecting, querying, and streaming real-time market data. Highlights include:
- tick or aggregate: collect tick data and optionally aggregate it into bar data of any size
- pull or push: pull tick or aggregate data into your code by querying, or push the stream of tick data to your code over WebSockets
- stream or snapshot: collect a continuous stream of market data or a single snapshot of data (supported vendors only)
- live market recording: store the data in a database for later replay
Tick data collection overview
This section describes the real-time data collection workflow that is common to all vendors. For vendor-specific guidelines, see the respective section for each vendor.
Create tick database
To get started with real-time data, first create an empty database for collecting tick data. Assign a code for the database, specify one or more universes or sids, and the fields to collect.
$ quantrocket realtime create-ibkr-tick-db 'fang-stk-tick' --universes 'fang-stk' --fields 'LastPrice' 'Volume' 'BidPrice' 'AskPrice' 'BidSize' 'AskSize'
status: successfully created tick database fang-stk-tick
>>> from quantrocket.realtime import create_ibkr_tick_db
>>> create_ibkr_tick_db("fang-stk-tick", universes="fang-stk",
fields=["LastPrice", "Volume", "BidPrice",
"AskPrice", "BidSize", "AskSize"])
{'status': 'successfully created tick database fang-stk-tick'}
$ curl -X PUT 'http://houston/realtime/databases/fang-stk-tick?universes=fang-stk&fields=LastPrice&fields=Volume&fields=BidPrice&fields=AskPrice&fields=BidSize&fields=AskSize&vendor=ibkr'
{"status": "successfully created tick database fang-stk-tick"}
You can check the configuration of your database:
$ quantrocket realtime config 'fang-stk-tick'
fields:
- LastPrice
- Volume
- BidPrice
- AskPrice
- BidSize
- AskSize
universes:
- fang-stk
vendor: ibkr
>>> from quantrocket.realtime import get_db_config
>>> get_db_config("fang-stk-tick")
{'universes': ['fang-stk'],
'vendor': 'ibkr',
'fields': ['LastPrice',
'Volume',
'BidPrice',
'AskPrice',
'BidSize',
'AskSize']}
$ curl -X GET 'http://houston/realtime/databases/fang-stk-tick'
{"universes": ["fang-stk"], "vendor": "ibkr", "fields": ["LastPrice", "Volume", "BidPrice", "AskPrice", "BidSize", "AskSize"]}
Or list the databases you've created, the output of which shows the tick databases and any aggregate databases derived from them:
$ quantrocket realtime list
etf-tick: []
fang-stk-tick: []
>>> from quantrocket.realtime import list_databases
>>> list_databases()
{'etf-tick': [], 'fang-stk-tick': []}
$ curl -X GET 'http://houston/realtime/databases'
{"etf-tick": [], "fang-stk-tick": []}
You can create any number of databases with differing configurations and collect data for more than one database at a time.
Collect data
Next you are ready to begin collecting market data:
$ quantrocket realtime collect 'fang-stk-tick'
status: the market data will be collected until canceled
>>> from quantrocket.realtime import collect_market_data
>>> collect_market_data("fang-stk-tick")
{'status': 'the market data will be collected until canceled'}
$ curl -X POST 'http://houston/realtime/collections?codes=fang-stk-tick'
{"status": "the market data will be collected until canceled"}
You can optionally override the database's configured universes and sids at collection time. This is useful if your tick database is tied to a large universe but on any given day you only need to collect ticks for a subset of securities:
$ quantrocket realtime collect 'us-stk-tick' --sids 'FIBBG000B9XRY4' 'FIBBG000BDTBL9'
status: the market data will be collected until canceled
>>> collect_market_data("us-stk-tick", sids=["FIBBG000B9XRY4", "FIBBG000BDTBL9"])
{'status': 'the market data will be collected until canceled'}
$ curl -X POST 'http://houston/realtime/collections?codes=us-stk-tick&sids=FIBBG000B9XRY4&sids=FIBBG000BDTBL9'
{"status": "the market data will be collected until canceled"}
Monitor data collection
There are numerous ways to monitor the flow of data as it's being collected.
You can view a simple summary of active collections, which will display the number of securities by database code (you can use --detail
/detail=True
if you want to see actual sids by database code instead of summary counts):
$ quantrocket realtime active
alpaca:
sample-stk-tick: 4
ibkr:
fang-stk-tick: 5
polygon:
etf-tick: 10
>>> from quantrocket.realtime import get_active_collections
>>> get_active_collections()
{'alpaca': {'sample-stk-tick': 4},
'ibkr': {'fang-stk-tick': 5},
'polygon': {'etf-tick': 10}}
$ curl -X GET 'http://houston/realtime/collections'
{"alpaca": {"sample-stk-tick": 4}, "ibkr": {"fang-stk-tick": 5}, "polygon": {"etf-tick": 10}}
You can monitor the detailed flightlog stream, which will print a summary approximately every minute of the total ticks and tickers recently received:
$ quantrocket flightlog stream -d
...
┌──────────────────────────────────────────────────┐
│ IBKR market data received: │
│ ibg1 │
│ unique_tickers total_ticks │
│ received at 20:04 UTC 11 2759 │
│ received at 20:05 UTC 11 2716 │
│ received at 20:06 UTC 11 2624 │
│ received at 20:07 UTC 11 2606 │
│ received at 20:08 UTC 11 2602 │
│ received at 20:09 UTC 11 2613 │
│ received at 20:10 UTC 11 2800 │
│ received at 20:11 UTC 11 2518 │
│ received at 20:12 UTC 11 2444 │
│ active collections 11 │
└──────────────────────────────────────────────────┘
...
You can connect directly to the data over a WebSocket to see the full, unfiltered stream, or you can query the database to see what's recently arrived.
Cancel data collection
You can cancel data collection by database code (optionally limiting by universe or sid), which returns the remaining active collections after cancellation, if any:
$ quantrocket realtime cancel 'fang-stk-tick'
alpaca:
sample-stk-tick: 4
polygon:
etf-tick: 10
>>> from quantrocket.realtime import cancel_market_data
>>> cancel_market_data("fang-stk-tick")
{'alpaca': {'sample-stk-tick': 4}, 'polygon': {'etf-tick': 10}}
$ curl -X DELETE 'http://houston/realtime/collections?codes=fang-stk-tick'
{"alpaca": {"sample-stk-tick": 4}, "polygon": {"etf-tick": 10}}
Or you can cancel everything:
$ quantrocket realtime cancel --all
>>> cancel_market_data(cancel_all=True)
{}
$ curl -X DELETE 'http://houston/realtime/collections?cancel_all=True'
{}
Another option is to indicate a cancellation time when you initiate the data collection. You can specify a specific time and timezone, for example cancel data collection after the US market close:
$ quantrocket realtime collect 'fang-stk-tick' --until '16:01:00 America/New_York'
status: the market data will be collected until 16:01:00 America/New_York
>>> from quantrocket.realtime import collect_market_data
>>> collect_market_data("fang-stk-tick", until="16:01:00 America/New_York")
{'status': 'the market data will be collected until 16:01:00 America/New_York'}
$ curl -X POST 'http://houston/realtime/collections?codes=fang-stk-tick&until=16:01:00+America/New_York'
{"status": "the market data will be collected until 16:01:00 America/New_York"}
Or you can specify a Pandas timedelta string, for example cancel data collection in 30 minutes:
$ quantrocket realtime collect 'fang-stk-tick' --until '30m'
status: the market data will be collected until 30m
>>> collect_market_data("fang-stk-tick", until="30m")
{'status': 'the market data will be collected until 30m'}
$ curl -X POST 'http://houston/realtime/collections?codes=fang-stk-tick&until=30m'
{"status": "the market data will be collected until 30m"}
Delete database
You can delete a database:
$ quantrocket realtime drop-db 'fang-stk-tick' --confirm-by-typing-db-code-again 'fang-stk-tick'
status: deleted tick database fang-stk-tick
>>> from quantrocket.realtime import drop_db
>>> drop_db("fang-stk-tick", confirm_by_typing_db_code_again="fang-stk-tick")
{"status": "deleted tick database fang-stk-tick"}
$ curl -X DELETE 'http://houston/realtime/databases/fang-stk-tick?confirm_by_typing_db_code_again=fang-stk-tick'
{"status": "deleted tick database fang-stk-tick"}
Interactive Brokers
To collect real-time market data from Interactive Brokers, you must first collect securities master listings from Interactive Brokers. It is not sufficient to have collected the listings from another vendor; specific IBKR fields must be present in the securities master database. To check if you have collected IBKR listings, query the securities master and make sure the ibkr_ConId
field is populated:
$ quantrocket master get --symbols 'AAPL' --fields 'Symbol' 'ibkr_ConId' | csvlook -I
| Sid | Symbol | ibkr_ConId |
| -------------- | ------ | ---------- |
| FIBBG000B9XRY4 | AAPL | 265598 |
>>> from quantrocket.master import get_securities
>>> securities = get_securities(symbols="AAPL", fields=["Symbol", "ibkr_ConId"])
>>> securities.head()
Symbol ibkr_ConId
Sid
FIBBG000B9XRY4 AAPL 265598
$ curl -X GET 'http://houston/master/securities.csv?symbols=AAPL&fields=Symbol&fields=ibkr_ConId' | csvlook -I
| Sid | Symbol | ibkr_ConId |
| -------------- | ------ | ---------- |
| FIBBG000B9XRY4 | AAPL | 265598 |
Once you have collected securities master listings from IBKR for the securities that interest you, assign a code for the real-time database, specify one or more universes or sids, and the fields to collect. (If not specified, "LastPrice" and "Volume" are collected.
$ quantrocket realtime create-ibkr-tick-db 'fang-stk-tick' --universes 'fang-stk' --fields 'LastPrice' 'Volume' 'BidPrice' 'AskPrice' 'BidSize' 'AskSize'
status: successfully created tick database fang-stk-tick
>>> from quantrocket.realtime import create_ibkr_tick_db
>>> create_ibkr_tick_db("fang-stk-tick", universes="fang-stk",
fields=["LastPrice", "Volume", "BidPrice",
"AskPrice", "BidSize", "AskSize"])
{'status': 'successfully created tick database fang-stk-tick'}
$ curl -X PUT 'http://houston/realtime/databases/fang-stk-tick?universes=fang-stk&fields=LastPrice&fields=Volume&fields=BidPrice&fields=AskPrice&fields=BidSize&fields=AskSize&vendor=ibkr'
{"status": "successfully created tick database fang-stk-tick"}
Make sure IB Gateway is running, then begin collecting market data:
$ quantrocket ibg start --wait
ibg1:
status: running
$ quantrocket realtime collect 'fang-stk-tick'
status: the market data will be collected until canceled
>>> from quantrocket.ibg import start_gateways
>>> start_gateways(wait=True)
{'ibg1': {'status': 'running'}}
>>> from quantrocket.realtime import collect_market_data
>>> collect_market_data("fang-stk-tick")
{'status': 'the market data will be collected until canceled'}
$ curl -X POST 'http://houston/ibgrouter/gateways?wait=True'
{"ibg1": {"status": "running"}}
$ curl -X POST 'http://houston/realtime/collections?codes=fang-stk-tick'
{"status": "the market data will be collected until canceled"}
IBKR streaming market data does not deliver every tick but is sampled and delivers ticks representing an average over the sampling interval. The sampling interval is 250 ms (4 samples per second) for stocks, futures, and non-US options, 100 ms (10 samples per second) for US options, and 5 ms (20 samples per second) for FX pairs.
Concurrent ticker limits
Ticker limits apply to streaming market data but do not apply to
snapshot data.
Interactive Brokers limits the number of securities you can stream simultaneously. By default, the limit is 100 concurrent tickers per IB Gateway. The limit can be increased in several ways:
- run multiple IB Gateways. QuantRocket will split requests between the IB Gateways, thereby increasing your ticker limit.
- purchase quote booster packs through IBKR Client Portal. Each purchased booster pack enables an additional 100 concurrent market data lines.
- accounts which are of significant size or which generate significant monthly commissions are allotted more generous ticker limits. See the "Market Data Display" section of the IBKR website to learn more about how concurrent ticker limits are calculated.
When you exceed your ticker limits, the IBKR API returns a "max tickers exceeded" error message for each security above the limit. QuantRocket automatically detects this error message and, if multiple IB Gateways are running, attempts to re-submit the rejected request to a different IB Gateway with additional capacity. Thus, you can run multiple IB Gateways with differing ticker limits and QuantRocket will split up the requests appropriately. If the ticker capacity is maxed out on all connected gateways, you will see warnings in flightlog:
quantrocket.realtime: WARNING All connected gateways have maxed out their concurrent market data collections, skipping SQM STK (sid FI12374), please cancel existing collections or increase your market data lines then re-collect this security (max tickers: ibg1:100)
Streaming vs snapshot data
By default, streaming market data is collected. An alternative option is to collect a single snapshot of data. To do so, use the snapshot
parameter. The optional wait
parameter will cause the command to block until the data collection is complete:
$ quantrocket realtime collect 'us-stk-quote' --snapshot --wait
status: completed market data snapshot for us-stk-quote
>>> from quantrocket.realtime import collect_market_data
>>> collect_market_data("us-stk-quote", snapshot=True, wait=True)
{'status': 'completed market data snapshot for us-stk-quote'}
$ curl -X POST 'http://houston/realtime/collections?codes=us-stk-quote&snapshot=True&wait=True'
{"status": "completed market data snapshot for us-stk-quote"}
Aside from the obvious difference that snapshot data captures a single point in time while streaming data captures a period of time, below are the major points of comparison between streaming and snapshot data.
Ticker limit
The primary advantage of snapshot data is that it is not subject to concurrent ticker limits. If you want the latest quote for several thousand stocks and are limited to 100 concurrent tickers, snapshot data is the best choice.
Initialization latency
When collecting market data (streaming or snapshot) for several thousand securities, it can take a few minutes to issue all of the initial market data requests to the IBKR API, after which data flows in real time. (This is because the IBKR API limits the rate of messages that the client can send to the API, but not the rate of messages that the API can send to the client). With streaming data collection, you can work around this initial latency by simply initiating data collection a few minutes before you need the data. With snapshot data, this isn't possible since you're not collecting a continuous stream.
Fields supported
Snapshot data only supports a subset of the fields supported by streaming data. See the market data field reference.
IBKR market data field reference
Due to the large number of market data fields and asset classes supported by Interactive Brokers, not all fields are applicable to all asset classes. Additionally, not all fields are available at all times of day. If a particular field is unavailable for a particular security at a particular time, often the IBKR API will not return an error message but will simply return no data. If you expect data but none is being returned, check whether you can view the data in Trader Workstation; data availability through the IBKR API mirrors availability in Trader Workstation.
For most fields, IBKR does not provide a timestamp. Therefore, QuantRocket provides one. Thus, the Date
field returned with real-time data indicates the time when the data first arrived in QuantRocket. Certain IBKR-provided timestamps are available, however, see LastTimestamp
and TimeSales
.
Trades and quotes
Field | Description | Supports snapshot? |
---|
BidSize | Number of contracts or lots offered at the bid price | ✔ |
BidPrice | Highest priced bid for the contract | ✔ |
AskPrice | Lowest price offer on the contract | ✔ |
AskSize | Number of contracts or lots offered at the ask price | ✔ |
LastPrice | Last price at which the contract traded | ✔ |
LastSize | Number of contracts or lots traded at the last price. See note below. | ✔ |
Volume | Trading volume for the day. See note below. | ✔ |
LastTimestamp | Time of the last trade (in UNIX time). This field is provided only for trades, not quotes, and as it arrives separately from LastPrice , it can be difficult to know which LastPrice it corresponds to. It can however be used to calculate latency by comparing the timestamp to the QuantRocket-generated timestamp. See Time and sales for correlating trades with IBKR-provided timestamps. | ✔ |
LastSize vs Volume
The Volume
field contains the cumulative volume for the day, while the LastSize
field contains the size of the last trade. Consider using the Volume
field for trade size calculation rather than using LastSize
. Because IBKR market data is not tick-by-tick, LastSize
may not provide a complete picture of all trades that have occurred. However, the cumulative Volume
field will. Trade size can be derived from volume by taking a diff in Pandas:
volumes = prices.loc["Volume"]
trade_sizes = volumes.diff()
Time and sales
TimeSales
and TimeSalesFiltered
provide an alternative method of collecting trades (but not quotes). These fields are the API equivalent of the Time and Sales window in Trader Workstation.
The primary advantage of these fields is that they provide the trade price, trade size, and trade timestamp (plus other fields) as a unified whole, unlike LastPrice
, LastSize
, and LastTimestamp
which arrive independently and thus can be difficult to associate with one another in fast-moving markets.
Field | Description | Supports snapshot? |
---|
TimeSales | Last trade details corresponding to Time & Sales window in TWS. Includes additional trade types such as combos, odd lots, derivates, etc. that are not reported by the LastPrice field. (In the IBKR API documentation the TimeSales field is called RtVolume.) | - |
TimeSalesFiltered | Identical to TimeSales but excludes combos, odd lots, derivates, etc. (In the IBKR API documentation the TimeSalesFiltered field is called RtTradeVolume.) | - |
When you request TimeSales
or TimeSalesFiltered
, several nested fields are returned.
LastPrice
- trade priceLastSize
- trade sizeLastTimestamp
- UTC datetime of tradeVolume
- total traded volume for the dayVwap
- volume-weighted average price for the dayOneFill
- whether or not the trade was filled by a single market maker
When streaming over WebSockets, these fields will arrive in a nested data structure:
{
"v": "ibkr",
"i": "FIBBG000B9XRY4",
"t": "2020-04-08T18:16:36.718948",
"f": "TimeSales",
"d": {
"LastPrice":356.31,
"LastSize": 100,
"LastTimestamp": "2019-06-05T18:23:16.409000",
"Volume": 3043700,
"Vwap": 353.30651072,
"OneFill": 1
}
}
CSV output queried from the database will flatten the nested structure using the following naming convention: TimeSalesLastPrice
, TimeSalesLastSize
, etc.
Option Greeks
Field | Description | Supports snapshot? |
---|
ModelOptionComputation | Computed Greeks and implied volatility based on the underlying stock price and the option model price. Corresponds to Greeks shown in TWS | ✔ |
BidOptionComputation | Computed Greeks and implied volatility based on the underlying stock price and the option bid price | ✔ |
AskOptionComputation | Computed Greeks and implied volatility based on the underlying stock price and the option ask price | ✔ |
LastOptionComputation | Computed Greeks and implied volatility based on the underlying stock price and the option last traded price | ✔ |
When you request an option computation field, several nested fields will be returned representing the different Greeks. When streaming over WebSockets, these fields will arrive in a nested data structure:
{
"v": "ibkr",
"i": "FIBBG000B9XRY4",
"t": "2019-06-05T16:10:16.162728",
"f": "ModelOptionComputation",
"d": {
"ImpliedVolatility": 0.27965811846647004,
"Delta": 0.01105129271665234,
"OptionPrice": 0.028713083045907993,
"PvDividend": 0.09943775573849334,
"Gamma": 0.0036857174753818366,
"Vega": 0.0103567465788384,
"Theta": -0.0011149809872252135,
"UnderlyingPrice": 52.37
}
}
CSV output queried from the database will flatten the nested structure using the following naming convention: ModelOptionComputationImpliedVolatility
, ModelOptionComputationDelta
, etc.
See Miscellaneous fields for other options-related fields.
Auction imbalance
Field | Description | Supports snapshot? |
---|
AuctionVolume | The number of shares that would trade if no new orders were received and the auction were held now. | - |
AuctionPrice | The price at which the auction would occur if no new orders were received and the auction were held now - the indicative price for the auction. Typically received after AuctionImbalance | - |
AuctionImbalance | The number of unmatched shares for the next auction; returns how many more shares are on one side of the auction than the other. Typically received after AuctionVolume | - |
RegulatoryImbalance | The imbalance that is used to determine which at-the-open or at-the-close orders can be entered following the publishing of the regulatory imbalance. | ✔ |
Miscellaneous fields
Field | Description | Supports snapshot? |
---|
High | High price for the day | ✔ |
Low | Low price for the day | ✔ |
Open | Current session's opening price. Before open will refer to previous day. The official opening price requires a market data subscription to the native exchange of the instrument | ✔ |
Close | Last available closing price for the previous day. | ✔ |
OptionHistoricalVolatility | The 30-day historical volatility (currently for stocks). | - |
OptionImpliedVolatility | A prediction of how volatile an underlying will be in the future. The IBKR 30-day volatility is the at-market volatility estimated for a maturity thirty calendar days forward of the current trading day, and is based on option prices from two consecutive expiration months. | - |
OptionCallOpenInterest | Call option open interest. | - |
OptionPutOpenInterest | Put option open interest. | - |
OptionCallVolume | Call option volume for the trading day. | - |
OptionPutVolume | Put option volume for the trading day. | - |
IndexFuturePremium | The number of points that the index is over the cash index. | - |
MarkPrice | The mark price is the current theoretical calculated value of an instrument. Since it is a calculated value, it will typically have many digits of precision. | - |
Halted | Indicates if a contract is halted. 1 = General halt imposed for regulatory reasons. 2 = Volatility halt imposed by the exchange to protect against extreme volatility. | - |
LastRthTrade | Last Regular Trading Hours traded price. | - |
RtHistoricalVolatility | 30-day real time historical volatility. | - |
CreditmanSlowMarkPrice | Mark price update used in system calculations | - |
FuturesOpenInterest | Total number of outstanding futures contracts | - |
AverageOptVolume | Average volume of the corresponding option contracts | - |
TradeCount | Trade count for the day. | - |
TradeRate | Trade count per minute. | - |
VolumeRate | Volume per minute. | - |
ShortTermVolume3min | The past three minutes volume. Interpolation may be applied. For stocks only. | - |
ShortTermVolume5min | The past five minutes volume. Interpolation may be applied. For stocks only. | - |
ShortTermVolume10min | The past ten minutes volume. Interpolation may be applied. For stocks only. | - |
Low13Weeks | Lowest price for the last 13 weeks. For stocks only. | - |
High13Weeks | Highest price for the last 13 weeks. For stocks only. | - |
Low26Weeks | Lowest price for the last 26 weeks. For stocks only. | - |
High26Weeks | Highest price for the last 26 weeks. For stocks only. | - |
Low52Weeks | Lowest price for the last 52 weeks. For stocks only. | - |
High52Weeks | Highest price for the last 52 weeks. For stocks only. | - |
AverageVolume | The average daily trading volume over 90 days. For stocks only. | - |
Alpaca
To collect real-time market data from Alpaca, assign a code for the database, specify one or more universes or sids, and the fields to collect:
$ quantrocket realtime create-alpaca-tick-db 'fang-stk-tick' --universes 'fang-stk' --fields 'LastPrice' 'LastSize' 'BidPrice' 'AskPrice' 'BidSize' 'AskSize'
status: successfully created tick database fang-stk-tick
>>> from quantrocket.realtime import create_alpaca_tick_db
>>> create_alpaca_tick_db("fang-stk-tick", universes="fang-stk",
fields=["LastPrice", "LastSize", "BidPrice",
"AskPrice", "BidSize", "AskSize"])
{'status': 'successfully created tick database fang-stk-tick'}
$ curl -X PUT 'http://houston/realtime/databases/fang-stk-tick?universes=fang-stk&fields=LastPrice&fields=LastSize&fields=BidPrice&fields=AskPrice&fields=BidSize&fields=AskSize&vendor=alpaca'
{"status": "successfully created tick database fang-stk-tick"}
Then collect market data:
$ quantrocket realtime collect 'fang-stk-tick'
status: the market data will be collected until canceled
>>> from quantrocket.realtime import collect_market_data
>>> collect_market_data("fang-stk-tick")
{'status': 'the market data will be collected until canceled'}
$ curl -X POST 'http://houston/realtime/collections?codes=fang-stk-tick'
{"status": "the market data will be collected until canceled"}
The Alpaca real-time data API relies on ticker symbols (which can change) rather than persistent IDs. To ensure accurate results, make sure to
keep your securities master database up-to-date so that QuantRocket has the latest ticker symbols for issuing requests to the Alpaca API. Note that this warning does not apply to Alpaca's trades and orders API, which uses persistent IDs.
Alpaca data feeds
Alpaca offers two different data feeds, depending on your Alpaca data subscription. The default feed is limited to data from IEX, while the premium feed provides access to the full SIP. You can specify which feed each of your API keys has access to when you set your Alpaca API key.
If you subscribe to Alpaca's premium feed, both the live API key and the corresponding paper API key will have access to the premium feed.
Each time you collect real-time data from Alpaca, QuantRocket will check if you indicated SIP permission for any of your Alpaca API keys. If so, QuantRocket will use that API key to connect to the SIP feed. Otherwise, QuantRocket will connect to the IEX feed.
Alpaca field reference
Trades and Quotes
These fields provide unfiltered, streaming tick data for trades and quotes.
AskPrice
AskSize
BidPrice
BidSize
LastPrice
LastSize
AskExchangeId
BidExchangeId
ExchangeId
TradeTape
QuoteTape
TradeId
Minute Aggregates
These fields provide streaming data aggregated into minute. See the fuller discussion on aggregates below.
MinuteClose
MinuteHigh
MinuteLow
MinuteOpen
MinuteVolume
Alpaca aggregates
Alpaca's Trades and Quotes feed is not sampled or filtered. It provides every tick. This can result in a very large amount of data being sent, which can impact performance. If you wish to monitor a large number of securities and don't require every tick, an alternative approach is to request Alpaca minute aggregates (MinuteOpen
, MinuteClose
, ...). This is the recommended approach for Zipline users.
Alpaca aggregates vs aggregate databases
To avoid confusion, note that Alpaca aggregates are not a replacement for QuantRocket's aggregate database feature but rather should be used in conjunction with that feature.
With Alpaca's aggregate data feed, tick data is aggregated by Alpaca into minute bars and then delivered to your QuantRocket database. Although the minute bars are already aggregated, they are stored in what QuantRocket calls a "tick" database. Therefore, Alpaca aggregates are best understood within QuantRocket's architecture as compressed tick data, rather than as what QuantRocket calls aggregate data.
To use the Alpaca aggregate data, you should create an aggregate database (that is, an aggregate database of the aggregates). This allows you to query the data using get_prices
or other QuantRocket APIs for aggregate data. The aggregate database could have a bar size that is either the same as or larger than the underlying Alpaca aggregates.
For example, if you created a "tick" database of Alpaca minute aggregates, like this:
$ quantrocket realtime create-alpaca-tick-db 'us-stk-realtime' --universes 'us-stk' --fields 'MinuteOpen' 'MinuteHigh' 'MinuteLow' 'MinuteClose' 'MinuteVolume'
status: successfully created tick database us-stk-realtime
>>> from quantrocket.realtime import create_alpaca_tick_db
>>> create_alpaca_tick_db("us-stk-realtime",
universes="us-stk",
fields=["MinuteOpen",
"MinuteHigh",
"MinuteLow",
"MinuteClose",
"MinuteVolume"])
{'status': 'successfully created tick database us-stk-realtime'}
$ curl -X PUT 'http://houston/realtime/databases/us-stk-realtime?universes=us-stk&fields=MinuteOpen&fields=MinuteHigh&fields=MinuteLow&fields=MinuteClose&fields=MinuteVolume&vendor=alpaca'
{"status": "successfully created tick database us-stk-realtime"}
You could create an aggregate database that would "aggregate" (in essence, simply copy) the minute bars into minute bars like this:
$ quantrocket realtime create-agg-db 'us-stk-realtime-1min' --tick-db 'us-stk-realtime' --bar-size '1m' --fields 'MinuteOpen:Open' 'MinuteHigh:High' 'MinuteLow:Low' 'MinuteClose:Close' 'MinuteVolume:Sum'
status: successfully created aggregate database us-stk-realtime-1min from tick database
us-stk-realtime
>>> from quantrocket.realtime import create_agg_db
>>> create_agg_db("us-stk-realtime-1min",
tick_db_code="us-stk-realtime",
bar_size="1m",
fields={"MinuteOpen":["Open"],
"MinuteHigh": ["High"],
"MinuteLow": ["Low"],
"MinuteClose": ["Close"],
"MinuteVolume": ["Sum"]})
{'status': 'successfully created aggregate database us-stk-realtime-1min from tick database us-stk-realtime'}
$ curl -X PUT 'http://houston/realtime/databases/us-stk-realtime/aggregates/us-stk-realtime-1min?bar_size=1m&fields=MinuteOpen%3AOpen&fields=MinuteHigh%3AHigh&fields=MinuteLow%3ALow&fields=MinuteClose%3AClose&fields=MinuteVolume%3ASum'
{"status": "successfully created aggregate database us-stk-realtime-1min from tick database us-stk-realtime"}
Learn more about aggregate databases.
Time delay of Alpaca aggregates
The Alpaca API delivers minute bars at the conclusion of the bar. Thus, for example, you will receive the 10:30 minute bar just after 10:31:00, since that is when the 10:30:00-10:30:59 trading activity is complete. If monitoring a small number of securities, the minute bars arrive almost immediately at the conclusion of the period. If monitoring a large number of securities such as the entire US stock market, it will take 5-10 seconds for all of the bars to arrive.
Because minute bars arrive once a minute, all at once, users should be aware of a potential race condition in which queries may return no data if the query is issued during the period after the minute has ended but before the minute bars have arrived from Alpaca. If you are using Alpaca minute aggregates for Zipline live trading (which is recommended), you do not need to worry about this race condition as Zipline will query the real-time database repeatedly until all of the minute data has arrived. (Zipline monitors for two successive queries to return the same number of records as an indication that all minute data has arrived.)
Polygon.io
To collect real-time market data from Polygon.io, assign a code for the database, specify one or more universes or sids, and the fields to collect:
$ quantrocket realtime create-polygon-tick-db 'fang-stk-tick' --universes 'fang-stk' --fields 'LastPrice' 'LastSize' 'BidPrice' 'AskPrice' 'BidSize' 'AskSize'
status: successfully created tick database fang-stk-tick
>>> from quantrocket.realtime import create_polygon_tick_db
>>> create_polygon_tick_db("fang-stk-tick", universes="fang-stk",
fields=["LastPrice", "LastSize", "BidPrice",
"AskPrice", "BidSize", "AskSize"])
{'status': 'successfully created tick database fang-stk-tick'}
$ curl -X PUT 'http://houston/realtime/databases/fang-stk-tick?universes=fang-stk&fields=LastPrice&fields=LastSize&fields=BidPrice&fields=AskPrice&fields=BidSize&fields=AskSize&vendor=polygon'
{"status": "successfully created tick database fang-stk-tick"}
Then collect market data:
$ quantrocket realtime collect 'fang-stk-tick'
status: the market data will be collected until canceled
>>> from quantrocket.realtime import collect_market_data
>>> collect_market_data("fang-stk-tick")
{'status': 'the market data will be collected until canceled'}
$ curl -X POST 'http://houston/realtime/collections?codes=fang-stk-tick'
{"status": "the market data will be collected until canceled"}
The Polygon.io API relies on ticker symbols (which can change) rather than persistent IDs. To ensure accurate results, make sure to
keep your securities master database up-to-date so that QuantRocket has the latest ticker symbols for issuing requests to the Polygon.io API.
Polygon.io field reference
Trades and Quotes
These fields provide unfiltered, streaming tick data for trades and quotes.
AskPrice
AskSize
BidPrice
BidSize
LastPrice
LastSize
AskExchangeId
BidExchangeId
ExchangeId
QuoteCondition
Tape
TradeConditions
TradeId
Second and Minute Aggregates
These fields provide streaming data aggregated into minute or second bars. See the fuller discussion on aggregates below.
MinuteClose
MinuteHigh
MinuteLow
MinuteOpen
MinuteVolume
MinuteVwap
SecondClose
SecondHigh
SecondLow
SecondOpen
SecondVolume
SecondVwap
Auction Imbalance
These fields, which are only available with certain Polygon subscriptions, provide access to the opening and closing auction imbalance feed.
AuctionExchangeId
AuctionImbalanceQuantity
AuctionPairedQuantity
AuctionPrice
AuctionSymbolSequence
AuctionTime
Polygon.io aggregates
Collecting Polygon.io aggregrates requires a Polygon subscription with websockets access but does not require a plan with access to trades and quotes.
Polygon.io's Trades and Quotes feed is not sampled or filtered. It provides every tick. This can result in a very large amount of data being sent, which can impact performance. If you wish to monitor a large number of securities and don't require every tick, an alternative and often more suitable approach is to request Polygon.io minute or second aggregates (MinuteOpen
, MinuteClose
, ..., SecondOpen
, SecondClose
, ...).
For use cases that require minute data (such as Zipline), we recommend collecting second aggregates from Polygon.io and using QuantRocket to aggregate them to minute data, for reasons outlined below.
Polygon.io aggregates vs aggregate databases
To avoid confusion, note that Polygon.io aggregates are not a replacement for QuantRocket's aggregate database feature but rather should be used in conjunction with that feature.
With Polygon.io's aggregate data feed, tick data is aggregated by Polygon.io into minute or second bars and then delivered to your QuantRocket database. Although the minute or second bars are already aggregated, they are stored in what QuantRocket calls a "tick" database. Therefore, Polygon.io aggregates are best understood within QuantRocket's architecture as compressed tick data, rather than as what QuantRocket calls aggregate data.
To use the Polygon.io aggregate data, you should create an aggregate database (that is, an aggregate database of the aggregates). This allows you to query the data using get_prices
or other QuantRocket APIs for aggregate data. The aggregate database could have a bar size that is either the same as or larger than the underlying Polygon.io aggregates.
For example, if you created a "tick" database of Polygon.io second aggregates, like this:
$ quantrocket realtime create-polygon-tick-db 'us-stk-realtime' --universes 'us-stk' --fields 'SecondOpen' 'SecondHigh' 'SecondLow' 'SecondClose' 'SecondVolume'
status: successfully created tick database us-stk-realtime
>>> from quantrocket.realtime import create_polygon_tick_db
>>> create_polygon_tick_db("us-stk-realtime",
universes="us-stk",
fields=["SecondOpen",
"SecondHigh",
"SecondLow",
"SecondClose",
"SecondVolume"])
{'status': 'successfully created tick database us-stk-realtime'}
$ curl -X PUT 'http://houston/realtime/databases/us-stk-realtime?universes=us-stk&fields=SecondOpen&fields=SecondHigh&fields=SecondLow&fields=SecondClose&fields=SecondVolume&vendor=polygon'
{"status": "successfully created tick database us-stk-realtime"}
You could create an aggregate database that would aggregate the second bars into minute bars like this:
$ quantrocket realtime create-agg-db 'us-stk-realtime-1min' --tick-db 'us-stk-realtime' --bar-size '1m' --fields 'SecondOpen:Open' 'SecondHigh:High' 'SecondLow:Low' 'SecondClose:Close' 'SecondVolume:Sum'
status: successfully created aggregate database us-stk-realtime-1min from tick database
us-stk-realtime
>>> from quantrocket.realtime import create_agg_db
>>> create_agg_db("us-stk-realtime-1min",
tick_db_code="us-stk-realtime",
bar_size="1m",
fields={"SecondOpen":["Open"],
"SecondHigh": ["High"],
"SecondLow": ["Low"],
"SecondClose": ["Close"],
"SecondVolume": ["Sum"]})
{'status': 'successfully created aggregate database us-stk-realtime-1min from tick database us-stk-realtime'}
$ curl -X PUT 'http://houston/realtime/databases/us-stk-realtime/aggregates/us-stk-realtime-1min?bar_size=1m&fields=SecondOpen%3AOpen&fields=SecondHigh%3AHigh&fields=SecondLow%3ALow&fields=SecondClose%3AClose&fields=SecondVolume%3ASum'
{"status": "successfully created aggregate database us-stk-realtime-1min from tick database us-stk-realtime"}
Learn more about aggregate databases.
Time delay of Polygon.io aggregates
The Polygon.io API delivers minute or second bars at the conclusion of the bar. Thus, for example, if receiving minute data you will receive the 10:30 bar at 10:31, since that is when the 10:30:00-10:30:59 trading activity is complete. For both minute and second bars, there is typically a small additional delay of about 2 seconds before the bar is delivered. Thus, for example, if receiving second aggregates, the 10:30:05 bar will be received at approximately 10:30:08 (2 seconds after the 10:30:06 completion of trading activity for the 10:30:05 second).
In benchmark tests, we find the performance of second aggregates to be more favorable than that of minute aggregates when collecting a large universe such as the entire US stock market. This is because, on adequate hardware, the second aggregates continue to arrive with a consistent, approximately two second delay regardless of the universe size. In contrast, the delay for minute aggregates worsens with a large universe, with minute bars arriving over a 15-20 second window at the conclusion of the bar. (This could change in the future, so be prepared to run your own benchmarks.)
For users who need minute data for a large universe, this delay can be avoided by collecting Polygon.io second aggregates and creating an aggregate database to build one-minute bars from the second data.
Database size for Polygon.io aggregates
If you are utilizing Polygon.io aggregates in order to collect real-time data for large universes of stocks, such as the entire US stock market, you will need to pay careful attention to database size. This is especially true since we recommend collecting second aggregates instead of minute aggregates. Fortunately, because many stocks don't trade every second, second aggregates do not require 60 times more storage space than minute aggregates, but more like 5 to 10 times more. However, the data volume will still be very considerable, on the order of several GB per trading day. Also note that limiting data collection to, say, the most liquid 50% of the market won't actually reduce your data volume very much, since you are mostly excluding illiquid securities that don't trade much.
Learn more about monitoring and managing database size.
WebSockets streaming
With data collection in progress, you can connect to the incoming data stream over WebSockets. This allows you to push the data stream to your code; meanwhile the realtime service also saves the incoming data to the database in the background for future use.
Streaming market data to a JupyterLab terminal provides a simple technique to monitor the incoming data. To start the stream:
$ quantrocket realtime stream
Received ping
{"v": "ibkr", "i": "FIBBG000B9XRY4", "t": "2019-06-06T14:07:48.750025", "f": "LastPrice", "d": 182.87}
{"v": "ibkr", "i": "FIBBG000B9XRY4", "t": "2019-06-06T14:07:48.750321", "f": "LastSize", "d": 100}
...
Data arrives as a JSON array, the structure of which varies by vendor:
Interactive Brokers
{
"v": "ib",
"i": "FIBBG000B9XRY4",
"t": "2020-04-08T14:07:48.732735",
"f": "LastPrice",
"d": 182.87
}
Alpaca
{
"v": "alpaca",
"i": "FIBBG000B9XRY4",
"t": "2020-04-08T19:59:00.050000",
"LastSize": 100,
"LastPrice": 265.88
}
Polygon.io
{
"v": "polygon",
"i": "FIBBG000B9XRY4",
"t": "2020-04-08T19:59:00.050000",
"LastSize": 100,
"LastPrice": 265.88
}
By default all incoming data is streamed, that is, all collected tickers and all fields, even fields that you have not configured to save to the database. You can optionally limit the fields and sids:
$ quantrocket realtime stream --sids 'FIBBG000B9XRY4' --fields 'LastPrice' 'BidPrice' 'AskPrice'
Remember, filtering the WebSocket stream doesn't control what data is being collected from the vendor, it only controls how much of the collected data is included in the stream.
WebSocket Python integration
Streaming data is not currently integrated into any of QuantRocket's Python libraries or APIs. We plan to add this integration in the future. For now, users can stream data to their own custom scripts by installing and using the WebSockets library.
The wscat
utility is a useful tool to help you understand the WebSocket API for the purpose of Python development.
wscat
The command quantrocket realtime stream
is a lightweight wrapper around wscat
, a command-line utility written in Node.js for making WebSocket connections. You can use wscat
directly if you prefer, which is useful for experimenting with the WebSocket API. To start the stream:
$ wscat -c 'http://houston/realtime/stream'
connected (press CTRL+C to quit)
< Received ping
< {"v": "ibkr", "i": "FIBBG000B9XRY4", "t": "2020-06-06T14:07:48.750025", "f": "LastPrice", "d": 182.87}
< {"v": "ibkr", "i": "FIBBG000B9XRY4", "t": "2020-06-06T14:07:48.750321", "f": "LastSize", "d": 100}
...
You can send a JSON message to limit the fields:
> {"fields": ["LastPrice", "BidPrice", "AskPrice"]}
To limit the securities being returned, send JSON messages with the keys "sids" or "exclude_sids" to indicate which tickers you want to add to, or subtract from, the current stream. For example, this sequence of messages would exclude all tickers from the stream then re-enable only AAPL:
> {"exclude_sids":"*"}
> {"sids":["FIBBG000B9XRY4"]}
You can also provide the filters as query string parameters at the time you initiate the WebSocket connection:
$ wscat -c 'http://houston/realtime/stream?sids=FIBBG000B9XRY4&sids=FIBBG000BVPV84&fields=LastPrice&fields=BidPrice'
Tick data file
You can download a file of the ticks stored in your tick database:
$ quantrocket realtime get 'fang-stk-tick' --start-date '2020-04-08' --sids 'FIBBG000B9XRY4' --fields 'LastPrice' 'BidPrice' 'AskPrice' | csvlook
| Sid | Date | LastPrice | BidPrice | AskPrice |
| -------------- | ----------------------------- | --------- | -------- | -------- |
| FIBBG000B9XRY4 | 2020-04-08 17:58:37.393111+00 | 263.49 | | |
| FIBBG000B9XRY4 | 2020-04-08 17:58:37.433426+00 | | 263.49 | |
| FIBBG000B9XRY4 | 2020-04-08 17:58:37.433912+00 | | | 263.53 |
| FIBBG000B9XRY4 | 2020-04-08 17:58:37.436259+00 | | 263.47 | |
| FIBBG000B9XRY4 | 2020-04-08 17:58:37.436441+00 | | | 263.51 |
| FIBBG000B9XRY4 | 2020-04-08 17:58:37.957495+00 | | | 263.50 |
| ... | ... | ... | ... | ... |
>>> import pandas as pd
>>> from quantrocket.realtime import download_market_data_file
>>> download_market_data_file("fang-stk-tick",
start_date="2020-04-08",
sids=["FIBBG000B9XRY4"],
fields=["LastPrice","BidPrice","AskPrice"],
filepath_or_buffer="fang_stk_tick.csv")
>>> ticks = pd.read_csv("fang_stk_tick.csv", parse_dates=["Date"])
>>> ticks.head()
Sid Date LastPrice BidPrice AskPrice
0 FIBBG000B9XRY4 2020-04-08 17:58:37.393111+00:00 263.49 NaN NaN
1 FIBBG000B9XRY4 2020-04-08 17:58:37.433426+00:00 NaN 263.49 NaN
2 FIBBG000B9XRY4 2020-04-08 17:58:37.433912+00:00 NaN NaN 263.53
3 FIBBG000B9XRY4 2020-04-08 17:58:37.436259+00:00 NaN 263.47 NaN
4 FIBBG000B9XRY4 2020-04-08 17:58:37.436441+00:00 NaN NaN 263.51
5 FIBBG000B9XRY4 2020-04-08 17:58:37.957495+00:00 NaN NaN 263.50
6 FIBBG000B9XRY4 2020-04-08 17:58:38.216396+00:00 NaN 263.46 NaN
7 FIBBG000B9XRY4 2020-04-08 17:58:38.216586+00:00 NaN NaN 263.48
8 FIBBG000B9XRY4 2020-04-08 17:58:38.720103+00:00 263.47 NaN NaN
9 FIBBG000B9XRY4 2020-04-08 17:58:38.960057+00:00 NaN 263.42 NaN
$ curl -X GET 'http://houston/realtime/fang-stk-tick.csv?start_date=2020-04-08&sids=FIBBG000B9XRY4&fields=LastPrice&fields=BidPrice&fields=AskPrice' | head
Sid,Date,LastPrice,BidPrice,AskPrice
FIBBG000B9XRY4,2020-04-08 17:58:37.393111+00,263.49,,
FIBBG000B9XRY4,2020-04-08 17:58:37.433426+00,,263.49,
FIBBG000B9XRY4,2020-04-08 17:58:37.433912+00,,,263.53
FIBBG000B9XRY4,2020-04-08 17:58:37.436259+00,,263.47,
FIBBG000B9XRY4,2020-04-08 17:58:37.436441+00,,,263.51
FIBBG000B9XRY4,2020-04-08 17:58:37.957495+00,,,263.5
FIBBG000B9XRY4,2020-04-08 17:58:38.216396+00,,263.46,
FIBBG000B9XRY4,2020-04-08 17:58:38.216586+00,,,263.48
FIBBG000B9XRY4,2020-04-08 17:58:38.720103+00,263.47,,
Timestamps in the file are UTC.
Aggregate databases
Aggregate databases provide rolled-up views of tick databases. Tick data can be rolled up to any bar size, for example 1 second, 1 minute, 15 minutes, 2 hours, or 1 day. One of the major benefits of aggregate databases is that they provide a consistent API with history databases, using the get_prices
function.
Create aggregate database
Create an aggregate database by providing a database code, the tick database to aggregate, the bar size (using a Pandas timedelta string such as '1s', '1m', '1h' or '1d'), and how to aggregate the tick fields. For example, the following command creates a 1-minute aggregate database with OHLCV bars, that is, with bars containing the open, high, low, and close of the LastPrice
field, plus the close of the Volume
field:
$ quantrocket realtime create-agg-db 'fang-stk-tick-1min' --tick-db 'fang-stk-tick' --bar-size '1m' --fields 'LastPrice:Open,High,Low,Close' 'Volume:Close'
status: successfully created aggregate database fang-stk-tick-1min from tick database fang-stk-tick
>>> from quantrocket.realtime import create_agg_db
>>> create_agg_db("fang-stk-tick-1min",
tick_db_code="fang-stk-tick",
bar_size="1m",
fields={"LastPrice":["Open","High","Low","Close"],
"Volume": ["Close"]})
{'status': 'successfully created aggregate database fang-stk-tick-1min from tick database fang-stk-tick'}
$ curl -X PUT 'http://houston/realtime/databases/fang-stk-tick/aggregates/fang-stk-tick-1min?bar_size=1m&fields=LastPrice%3AOpen%2CHigh%2CLow%2CClose&fields=Volume%3AClose'
{"status": "successfully created aggregate database fang-stk-tick-1min from tick database fang-stk-tick"}
Checking the database config reveals the fieldnames in the resulting aggregate database:
$ quantrocket realtime config 'fang-stk-tick-1min'
bar_size: 1m
fields:
- LastPriceClose
- LastPriceHigh
- LastPriceLow
- LastPriceOpen
- VolumeClose
tick_db_code: fang-stk-tick
>>> from quantrocket.realtime import get_db_config
>>> get_db_config("fang-stk-tick-1min")
{'tick_db_code': 'fang-stk-tick',
'bar_size': '1m',
'fields': ['LastPriceClose',
'LastPriceHigh',
'LastPriceLow',
'LastPriceOpen',
'VolumeClose']}
$ curl -X GET 'http://houston/realtime/databases/fang-stk-tick/aggregates/fang-stk-tick-1min'
{"tick_db_code": "fang-stk-tick", "bar_size": "1m", "fields": ["LastPriceClose", "LastPriceHigh", "LastPriceLow", "LastPriceOpen", "VolumeClose"]}
You can create multiple aggregate databases from a single tick database.
When listing databases, aggregate databases are nested beneath their tick database:
$ quantrocket realtime list
etf-tick: []
fang-stk-tick:
- fang-stk-tick-1min
>>> from quantrocket.realtime import list_databases
>>> list_databases()
{'etf-tick': [], 'fang-stk-tick': ['fang-stk-tick-1min']}
$ curl -X GET 'http://houston/realtime/databases'
{"etf-tick": [], "fang-stk-tick": ["fang-stk-tick-1min"]}
To delete an aggregate database but keep the underlying tick database, use the aggregate database code in the drop database API call:
$ quantrocket realtime drop-db 'fang-stk-tick-1min' --confirm-by-typing-db-code-again 'fang-stk-tick-1min'
status: deleted aggregate database fang-stk-tick-1min
>>> from quantrocket.realtime import drop_db
>>> drop_db("fang-stk-tick-1min", confirm_by_typing_db_code_again="fang-stk-tick-1min")
{"status": "deleted aggregate database fang-stk-tick-1min"}
$ curl -X DELETE 'http://houston/realtime/databases/fang-stk-tick/aggregates/fang-stk-tick-1min?confirm_by_typing_db_code_again=fang-stk-tick-1min'
{"status": "deleted aggregate database fang-stk-tick-1min"}
Alternatively, to delete a tick database with one or more aggregate databases associated with it, you must use the --cascade/cascade=True
parameter which causes both the tick database and all its aggregate databases to be deleted:
$ quantrocket realtime drop-db 'fang-stk-tick' --confirm-by-typing-db-code-again 'fang-stk-tick' --cascade
status: deleted tick database fang-stk-tick
>>> drop_db("fang-stk-tick", confirm_by_typing_db_code_again="fang-stk-tick", cascade=True)
{"status": "deleted tick database fang-stk-tick"}
$ curl -X DELETE 'http://houston/realtime/databases/fang-stk-tick?confirm_by_typing_db_code_again=fang-stk-tick&cascade=true'
{"status": "deleted tick database fang-stk-tick"}
Materialization of aggregate databases
An aggregate database is populated by aggregating the tick data and storing the aggregated results as a separate database table which can then be queried directly. In database terminology, this process is called materialization.
No user action is required to materialize the aggregate database.
QuantRocket uses TimescaleDB to store tick data as well as to build aggregate databases from tick data. After you create an aggregate database, background workers will materialize the aggregate database from the tick data and will periodically run again to keep the aggregate database up-to-date. In case any tick data that has recently arrived has not yet been materialized to the aggregate database, TimescaleDB aggregates this tick data on-the-fly at query time and includes it in the aggregate results, ensuring a fully up-to-date result.
Query aggregate data
You can download a file of aggregate data using the same API used to download tick data. Instead of ticks, bars are returned. As with tick data, all timestamps are UTC:
$ quantrocket realtime get 'fang-stk-tick-1min' --start-date '2020-04-08' --sids 'FIBBG000B9XRY4' | csvlook --max-rows 5
| Sid | Date | LastPriceOpen | LastPriceClose | LastPriceLow | LastPriceHigh | VolumeClose |
| -------------- | ---------------------- | ------------- | -------------- | ------------ | ------------- | ----------- |
| FIBBG000B9XRY4 | 2020-04-08 17:58:00+00 | 263.49 | 263.33 | 263.30 | 263.53 | 22,169,600 |
| FIBBG000B9XRY4 | 2020-04-08 17:59:00+00 | 263.31 | 263.24 | 263.02 | 263.31 | 22,235,700 |
| FIBBG000B9XRY4 | 2020-04-08 18:00:00+00 | 263.32 | 263.25 | 263.07 | 263.41 | 22,302,000 |
| FIBBG000B9XRY4 | 2020-04-08 18:01:00+00 | 263.30 | 263.72 | 263.21 | 263.78 | 22,383,500 |
| FIBBG000B9XRY4 | 2020-04-08 18:02:00+00 | 263.82 | 263.57 | 263.50 | 263.82 | 22,422,100 |
| ... | ... | ... | ... | ... | ... | ... |
>>> import pandas as pd
>>> from quantrocket.realtime import download_market_data_file
>>> download_market_data_file("fang-stk-tick-1min",
start_date="2020-04-08",
sids=["FIBBG000B9XRY4"],
filepath_or_buffer="fang_stk_tick_1min.csv")
>>> prices = pd.read_csv("fang_stk_tick_1min.csv", parse_dates=["Date"])
>>> prices.head()
Sid Date LastPriceOpen LastPriceClose LastPriceLow LastPriceHigh VolumeClose
0 FIBBG000B9XRY4 2020-04-08 17:58:00+00:00 263.49 263.33 263.30 263.53 22169600
1 FIBBG000B9XRY4 2020-04-08 17:59:00+00:00 263.31 263.24 263.02 263.31 22235700
2 FIBBG000B9XRY4 2020-04-08 18:00:00+00:00 263.32 263.25 263.07 263.41 22302000
3 FIBBG000B9XRY4 2020-04-08 18:01:00+00:00 263.30 263.72 263.21 263.78 22383500
4 FIBBG000B9XRY4 2020-04-08 18:02:00+00:00 263.82 263.57 263.50 263.82 22422100
$ curl -X GET 'http://houston/realtime/fang-stk-tick-1min.csv?start_date=2020-04-08&sids=FIBBG000B9XRY4' | head
Sid,Date,LastPriceOpen,LastPriceClose,LastPriceLow,LastPriceHigh,VolumeClose
FIBBG000B9XRY4,2020-04-08 17:58:00+00,263.49,263.33,263.3,263.53,22169600
FIBBG000B9XRY4,2020-04-08 17:59:00+00,263.31,263.24,263.02,263.31,22235700
FIBBG000B9XRY4,2020-04-08 18:00:00+00,263.32,263.25,263.07,263.41,22302000
FIBBG000B9XRY4,2020-04-08 18:01:00+00,263.3,263.72,263.21,263.78,22383500
FIBBG000B9XRY4,2020-04-08 18:02:00+00,263.82,263.57,263.5,263.82,22422100
For a higher-level API, you can load real-time aggregate data with the get_prices function which is also used for loading historical data.
How many securities can you collect real-time data for at one time? It depends on the data provider and type of real-time data.
Interactive Brokers tick data
Interactive Brokers enforces concurrent ticker limits that will typically determine the cap on concurrent data collection, as these limits will typically be lower than the threshold at which database performance becomes an issue. However, see the longer discussion about database performance under Polygon.io tick data to understand the role that database performance may play.
Alpaca or Polygon.io aggregates
Polygon.io does not impose concurrent ticker limits, and Alpaca does not impose concurrent ticker limits for aggregates. If you are collecting Alpaca aggregates or Polygon.io aggregates, you should be able to collect data for large universes of thousands of stocks, such as the entire US stock market. While you shouldn't suffer database lag as described below for tick data, you will still need to worry about database size.
Although it is possible to collect large amounts of data with Alpaca or Polygon.io aggregates, try to be smart and only collect the data your trading strategies actually require, as there is always likely to be some amount of performance cost associated with large volumes of data.
Alpaca or Polygon.io tick data
If you are collecting full tick data from Alpaca or Polygon.io, there is a soft, practical limit on concurrent data collection which is determined by database performance. This limit will vary by use case and depends on a variety of factors:
- how actively the securities trade (liquid securities produce more data than illiquid securities)
- the time of day (trading is typically more active near the open and close of the trading session)
- whether you collect trades only (= less data) or trades and quotes (= more data)
- the speed of your hardware, particularly disk I/O
In most cases, collecting tick data for 500-1000 tickers concurrently should not cause database performance problems on most systems. Collecting more than that may work but users should expect to have to test their particular system and use case. Ultimately, performance will be determined not by the number of unique tickers but by the total number of ticks. Both metrics can be viewed in the detailed log output:
$ quantrocket flightlog stream -d
...
quantrocket_realtime_1|┌──────────────────────────────────────────────────┐
quantrocket_realtime_1|│ Polygon market data received: │
quantrocket_realtime_1|│ total_ticks unique_tickers │
quantrocket_realtime_1|│ received at 15:23 UTC 173430 2871 │
quantrocket_realtime_1|│ received at 15:24 UTC 166559 2766 │
quantrocket_realtime_1|│ received at 15:25 UTC 165228 2703 │
quantrocket_realtime_1|│ active collections 3460 │
quantrocket_realtime_1|└──────────────────────────────────────────────────┘
...
The typical bottleneck will occur in writing the incoming data to disk. The detailed logs will show current data arriving, but querying the database will reveal a lag. If this happens, try running on hardware optimized for I/O performance. Increasing system memory may also improve performance as TimescaleDB tries to retain recent data in memory in order to field queries for recent data without hitting the disk.
Connecting to the incoming data stream over websockets bypasses the database and is subject to different limits. While you would expect the limit to be higher since there is no disk I/O involved, websocket bottlenecks will typically occur earlier than the database bottlenecks. This counterintuitive result is explained by the underlying technologies. Database writing and reading is handled by TimescaleDB, which is optimized for that purpose and thus makes the best of the inherently slow I/O process. Connecting to the incoming data stream is handled by PostgreSQL's LISTEN/NOTIFY message queue, which is a convenient tool but not as highly optimized for the use case of financial data streaming. We think LISTEN/NOTIFY is the right technology choice for QuantRocket at this time (since most use cases center on querying the database) but might revisit this in the future.
In summary, streaming data over websockets is best suited for smaller numbers of securities.
Database size
Although real-time databases utilize compression, collecting tick data can quickly consume a considerable amount of disk space. TimescaleDB is designed and optimized for its speed of writing and reading data, not for its compression capabalities. Creating an aggregate database from the tick database uses additional space. Therefore you should keep an eye on your disk space.
Below are some strategies for managing database size.
Delete ticks
Sometimes you may collect ticks solely for the purpose of generating aggregates such as 1-minute bars. The stored tick data uses considerably more space than the derived aggregate database. You can delete older ticks to free up space, while still preserving all of the aggregate data and the recent ticks. Use a Pandas timedelta string to specify the cutoff for dropping old ticks. This examples deletes ticks more than 7 days old:
$ quantrocket realtime drop-ticks 'fang-stk-tick' --older-than '7d'
status: dropped ticks older than 7d from database fang-stk-tick
>>> from quantrocket.realtime import drop_ticks
>>> drop_ticks("fang-stk-tick", older_than="7d")
{'status': 'dropped ticks older than 7d from database fang-stk-tick'}
$ curl -X DELETE 'http://houston/realtime/ticks/fang-stk-tick?older_than=7d'
{"status": "dropped ticks older than 7d from database fang-stk-tick"}
See the API reference for additional information and caveats.
Tick data collection strategy
Here is an example strategy for collecting more tick data than will fit on your local disk, if you don't want to delete old ticks.
Suppose you have the following constraints:
- you have only enough local disk space for 3 months of tick data
- you want data that won't fit on your local disk to be preserved in the cloud indefinitely
- your trading strategies require at minimum that the past 2 weeks of tick data are available on the local disk
First, create the tick database and append a date or version number:
$ quantrocket realtime create-tick-ibkr-db 'cme-fut-taq-1' --universes 'cme-fut' --fields 'LastPrice' 'BidPrice' 'AskPrice'
status: successfully created tick database cme-fut-taq-1
>>> from quantrocket.realtime import create_ibkr_tick_db
>>> create_ibkr_tick_db("cme-fut-taq-1", universes="cme-fut", fields=["LastPrice","BidPrice","AskPrice"])
{'status': 'successfully created tick database cme-fut-taq-1'}
$ curl -X PUT 'http://houston/realtime/databases/cme-fut-taq-1?universes=cme-fut&fields=LastPrice&fields=BidPrice&fields=AskPrice&vendor=ibkr'
{"status": "successfully created tick database cme-fut-taq-1"}
Collect data and use this database for your trading. After two and a half months, create a second, identical database:
$ quantrocket realtime create-ibkr-tick-db 'cme-fut-taq-2' --universes 'cme-fut' --fields 'LastPrice' 'BidPrice' 'AskPrice'
status: successfully created tick database cme-fut-taq-2
>>> create_ibkr_tick_db("cme-fut-taq-2", universes="cme-fut", fields=["LastPrice","BidPrice","AskPrice"])
{'status': 'successfully created tick database cme-fut-taq-2'}
$ curl -X PUT 'http://houston/realtime/databases/cme-fut-taq-2?universes=cme-fut&fields=LastPrice&fields=BidPrice&fields=AskPrice&vendor=ibkr'
{"status": "successfully created tick database cme-fut-taq-2"}
Begin collecting data into both databases, but continue to point your trading strategies at the first database (since the second database does not yet have two weeks of data). Once you have collected two weeks of data into the new database, push the first database to S3:
$ quantrocket db s3push --services 'realtime' --codes 'cme-fut-taq-1'
status: the databases will be pushed to S3 asynchronously
>>> from quantrocket.db import s3_push_databases
>>> s3_push_databases(services="realtime", codes="cme-fut-taq-1")
{'status': 'the databases will be pushed to S3 asynchronously'}
$ curl -X PUT 'http://houston/db/s3?services=realtime&codes=cme-fut-taq-1'
{"status": "the databases will be pushed to S3 asynchronously"}
With the first database safely in the cloud, point your trading strategies to the second database, and delete the first database:
$ quantrocket realtime drop-db 'cme-fut-taq-1' --confirm-by-typing-db-code-again 'cme-fut-taq-1'
status: deleted tick database cme-fut-taq-1
>>> from quantrocket.realtime import drop_db
>>> drop_db("cme-fut-taq-1", confirm_by_typing_db_code_again="cme-fut-taq-1")
{'status': 'deleted tick database cme-fut-taq-1'}
$ curl -X DELETE 'http://houston/realtime/databases/cme-fut-taq-1?confirm_by_typing_db_code_again=cme-fut-taq-1'
{"status": "deleted tick database cme-fut-taq-1"}
Repeat this database rotation strategy every 3 months.
Later, if you need to perform analysis of an archived tick database, you can restore it from the cloud.
History database as real-time feed
Each time you update an intraday history database from Interactive Brokers, the data is brought current as of the moment you collect it. Thus, for some use cases it may be suitable to use an IBKR history database as a real-time data source. One advantage of this approach, compared to using the realtime service, is simplicity: you only have to worry about a single database.
The primary limitation of this approach is that it takes longer to collect data using the history service than using the realtime service. This difference isn't significant for a small number of symbols, but it can be quite significant if you need up-to-date quotes for thousands of securities.
Wait for historical data collection
When using a history database as a real-time data source, you may need to coordinate data collection with other tasks that depend on the data. For example, if trading an intraday strategy using a history database, you will typically want to run your strategy shortly after collecting data, but you want to ensure that the strategy doesn't run while data collection is still in progress. You can use the command quantrocket history wait
for this purpose. This command simply blocks until the specified database is no longer being collected:
$
$ quantrocket history collect 'arca-15min'
status: the historical data will be collected asynchronously
$
$ quantrocket history wait 'arca-15min'
status: data collection finished for arca-15min
An optional timeout can be provided using a Pandas timedelta string; if the data collection doesn't finish within the allotted timeout, the wait command will return an error message and exit nonzero:
$ quantrocket history wait 'arca-15min' --timeout '10sec'
msg: data collection for arca-15min not finished after 10sec
status: error
To use the wait command on your countdown service crontab, you can run it before your trade command. In the example below, we collect data at 9:45 and want to place orders at 10:00. In case data collection is too slow, we will wait up to 5 minutes to place orders (that is, until 10:05). If data collection is still not finished, the wait command will exit nonzero and the strategy will not run. (If data collection is finished before 10:00, the wait command will return immediately and our strategy will run immediately.)
45 9 * * mon-fri quantrocket master isopen 'ARCA' && quantrocket history collect 'arca-15min'
0 10 * * mon-fri quantrocket master isopen 'ARCA' && quantrocket history wait 'arca-15min' --timeout '5min' && quantrocket moonshot trade 'intraday-strategy' | quantrocket blotter order -f '-'
Alternatively, if you want to run your strategy as soon as data collection finishes, you can place everything on one line:
45 9 * * mon-fri quantrocket master isopen 'ARCA' && quantrocket history collect 'arca-15min' && quantrocket history wait 'arca-15min' --timeout '15min' && quantrocket moonshot trade 'intraday-strategy' | quantrocket blotter order -f '-'
Custom Data
QuantRocket supports loading custom data into a history database. Once loaded, the data can be queried using QuantRocket's standard APIs, like any other history database. Custom data can consist of many different kinds of data, including price data, fundamental data, alternative data, etc.
Supported datasets
Custom databases can be used for any dataset containing records keyed by date and security. Put differently, each custom database has two required columns: Sid
and Date
. Dates can be any frequency: for example, quarterly, daily, minute, etc.
The security identifiers in your data (for example, ticker symbols) must be mapped to sids before loading the data into the database. This means that the sids must already exist in your securities master database (so that it's possible for you to map to them). Consequently, custom databases can only be used for loading data that relate to securities that are already natively supported by QuantRocket. Custom databases cannot be used for loading data for securities that are unknown by QuantRocket.
If your dataset is not keyed by security at all (for example, country-level economic data or broad market sentiment data), there are two options. One option is to assign the data to a placeholder sid such as SPY (FIBBG000BDTBL9
) so that the data can be loaded into a custom database. Alternatively, you can skip the custom database and load the dataset directly from flat files, perhaps using a custom script.
Dataset size
Custom data is stored in SQLite databases. SQLite is easy to use and offers great performance for reasonably-sized datasets. However, you should not expect to be able to load a large intraday dataset (such as minute data for US stocks) into a SQLite database (or any other non-specialized database) and get adequate performance. If your dataset is very large, you will need to split it up and store it in multiple, smaller SQLite databases. Generally, for best performance, try to limit each SQLite database to a few GB of data.
Create custom database
To get started with custom data, first create an empty database into which the data can be loaded. Specify a database code, the bar size (that is, data frequency) of your data, and define the name and types of your data fields (other than Sid
and Date
, which are created automatically). Creating a database for custom fundamental data might look like this:
$ quantrocket history create-custom-db 'custom-fundamentals' --bar-size '1 day' --columns 'Revenue:int' 'EPS:float' 'Currency:str' 'TotalAssets:int'
status: successfully created quantrocket.v2.history.custom-fundamentals.sqlite
>>> from quantrocket.history import create_custom_db
>>> create_custom_db(
"custom-fundamentals",
bar_size="1 day",
columns={
"Revenue":"int",
"EPS":"float",
"Currency":"str",
"TotalAssets":"int"})
{'status': 'successfully created quantrocket.v2.history.custom-fundamentals.sqlite'}
$ curl -X PUT 'http://houston/history/databases/custom-fundamentals?bar_size=1+day&columns=Revenue%3Aint&columns=EPS%3Afloat&columns=Currency%3Astr&columns=TotalAssets%3Aint&vendor=custom'
{"status": "successfully created quantrocket.v2.history.custom-fundamentals.sqlite"}
The --bar-size
/bar_size
parameter is not enforced but determines how the Date
column is indexed and thus facilitates efficient querying. It also provides a hint to other parts of the API. Use a Pandas timedelta string, for example, '1 day' or '1 min' or '1 sec'.
The --columns
/columns
parameter should specify pairs of <name>:<type>
for each column in the database other than Sid
and Date
. The possible column types are 'int', 'float', 'text', 'date', or 'datetime'. Column names must begin with a letter and consist of letters, numbers, and underscores only.
Databases are created in the /var/lib/quantrocket
directory. You can view the full database path by listing the database:
$ quantrocket db list --services 'history' --codes 'custom-fundamentals' --detail
postgres: []
sqlite:
- last_modified: '2021-02-09T20:40:17'
name: quantrocket.v2.history.custom-fundamentals.sqlite
path: /var/lib/quantrocket/quantrocket.v2.history.custom-fundamentals.sqlite
size_in_mb: 0.02
>>> from quantrocket.db import list_databases
>>> list_databases(services="history", codes="custom-fundamentals", detail=True)
{'sqlite': [{'name': 'quantrocket.v2.history.custom-fundamentals.sqlite',
'path': '/var/lib/quantrocket/quantrocket.v2.history.custom-fundamentals.sqlite',
'size_in_mb': 0.02,
'last_modified': '2021-02-09T20:40:17'}],
'postgres': []}
$ curl -X GET 'http://houston/db/databases?services=history&codes=custom-fundamentals&detail=True'
{"sqlite": [{"name": "quantrocket.v2.history.custom-fundamentals.sqlite", "path": "/var/lib/quantrocket/quantrocket.v2.history.custom-fundamentals.sqlite", "size_in_mb": 0.02, "last_modified": "2021-02-09T20:40:17"}], "postgres": []}
Though not necessary, it may be orienting to look in the database that was created and show the schema so that you understand its structure.
$ sqlite3 /var/lib/quantrocket/quantrocket.v2.history.custom-fundamentals.sqlite
sqlite> .schema
CREATE TABLE ConfigBlob (
Id INT PRIMARY KEY NOT NULL,
JsonConfig BLOB NOT NULL
);
CREATE TABLE Price (
Sid VARCHAR(20) NOT NULL,
Date DATETIME NOT NULL,
Revenue INT DEFAULT NULL,
EPS DOUBLE DEFAULT NULL,
Currency TEXT DEFAULT NULL,
TotalAssets INT DEFAULT NULL,
PRIMARY KEY (Sid, Date)
);
You will see two tables. The ConfigBlob
table stores the database configuration and should not be modified. The Price
table contains a Sid
and Date
column, plus the columns you specified. This is the table into which you will import your custom data. Note that the Price
table's primary key is (Sid, Date)
. This means that each record in the table must have a unique combination of sid and date.
Because custom data utilizes the history service, you will typically be accessing custom data using APIs that use the terms "price" or "prices". However, this doesn't mean that a custom database needs to contain price data. It can contain any kind of data.
Load custom data
Once you have created your custom database, the next step is to load your custom data. Conceptually, this is a 3-part process:
- Collect the data from your data provider;
- Prepare the data for import by mapping to sids and parsing dates;
- Import the data into the database.
Loading data requires access to the /var/lib/quantrocket
directory and thus should be run from either the jupyter
container (for manual or one-off imports) or from the satellite
container (for scripted imports).
Collect custom data
Collecting custom data is specific to the dataset and data provider, but most scenarios fall into two broad categories: querying APIs or downloading bulk files.
If you are collecting the data from an API, a good approach is to write a custom script and run it from the satellite
service.
If you have one or more bulk files on your local computer that you want to import, the first step is to upload them to your QuantRocket deployment. For small numbers of files, this can be done through the JupyterLab GUI. Alternatively, you can copy files from your local computer to the filesystem of either the jupyter
or satellite
container (it doesn't matter which as they are shared) using docker cp
:
$
$ docker cp path/to/local/files/. quantrocket_satellite_1:/codeload/custom_data/
Carefully note the syntax of the command to avoid unexpected results such as inserting an extra subdirectory in destination path. There is a dot (.
) at the end of source directory path (path/to/local/files/.
), indicating that the directory contents should be copied but not the directory itself. There is a slash at the end of the destination path (quantrocket_satellite_1:/codeload/custom_data/
), indicating that the files should be placed directly under that directory.
Prepare custom data
Preparing custom data for import consists of 3 main steps (in no particular order):
- Ensure dates are in the proper format;
- Map records to sids;
- Rename or drop columns to ensure that the DataFrame columns exactly match the database columns.
These steps are documented below using Python and pandas.
You need not, and often should not, load your entire dataset into pandas at once. If your dataset is large, you can load a subset of data, prepare and import the data into the database, then repeat.
Dates should be inserted into the database in ISO 8601 format:
- for non-intraday datasets, the format should be
2021-02-10
- for intraday datasets, the format should be
2021-02-10T09:30:00-05:00
The easiest way to ensure the proper format is to parse your dates using pandas. When the pandas dates are inserted into the database, they will be coerced to strings and will automatically be in the correct format. For example, for a daily dataset:
>>> custom_data["Date"] = pd.to_datetime(custom_data["my_date_col"])
For intraday datasets, make sure you indicate the timezone so that the dates are stored in the database with the proper timezone offsets (-05:00
in the example above):
>>> custom_data["Date"] = pd.to_datetime(custom_data["my_datetime_col"], tz="America/New_York")
Map to sids
The records in your dataset may be identified by ticker symbols or some other security identifiers, and you must map those identifiers to QuantRocket sids before importing the data. The general way to do this is to query QuantRocket securities and join them to your DataFrame based on your dataset's security identifiers.
Suppose your dataset covers US stocks and contains a Symbol
column which contains the ticker symbol. At the simplest level, you could append sids like this:
>>>
>>> from quantrocket.master import get_securities
>>> securities = get_securities(vendors="usstock", fields=["Sid","Symbol"])
>>>
>>> securities = securities.reset_index()
>>>
>>> custom_data = pd.merge(custom_data, securities, on="Symbol", how="left")
Now your custom data has a Sid
column as required for import.
While this process is conceptually simple, and may be simple for simple datasets, ensuring good matching requires considerable care when you are importing a large and complex dataset. In particular, large equities datasets such as US stocks are complex and messy due to ticker symbol changes and other issues. If your dataset includes delisted stocks, this greatly adds to the complexity. You should focus carefully on this step and iteratively inspect and improve your matching logic to ensure a good result. Reviewing the problems and tips below will help you.
Common problems
See also the section on
understanding sids, which provides additional details about some of the challenges of mapping securities to sids.
- Ticker changes: Ticker symbols can change over time. This creates a risk of mapping your data to the wrong security. For example, you might map data for Randgold Resources (which had the ticker 'GOLD' before it was delisted) to the sid for Barrick Gold (which now has the ticker 'GOLD').
- Ticker symbol conventions: Ticker symbols that include the share class are represented differently by different data providers. For example, Berkshire Hathaway Class B shares are variously referred to by the ticker symbol "BRK-B", "BRK.B", or "BRK B", depending on the data provider. This also applies to preferred shares. Compare your dataset conventions to the conventions of the data you are matching to, and modify the symbols as needed to ensure a good match. Pandas' string methods can help, for example:
custom_data.Symbol.str.replace(".", "-")
- Duplicate joins: When joining using
pd.merge
, it is possible to end up with more rows than you started with, if the join key in one DataFrame matches multiple join keys in the other DataFrame. For example, if your custom data contains the ticker 'GOLD' and the securities master returns two securities with the ticker 'GOLD' (because the ticker was recycled), the 'GOLD' row in your custom data will be duplicated and matched to both securities. You will need to improve your matching strategy to remedy this. If you can devise a way of sorting better matches before worse matches, you can then drop the duplicates: custom_data.drop_duplicates(subset=["Sid", "Date"], keep="first")
Tips
- Limit the data you query from the securities master based on the characteristics of your dataset. This will reduce false matches. If the dataset contains US stocks only, limit to the
usstock
vendor (vendors='usstock'
) so that you don't match tickers from other countries or asset classes. If your dataset doesn't include delisted stocks, exclude delisted stocks from your securities master query (exclude_delisted=True
). If your dataset is limited to one exchange, only match to securities from that exchange. - Use left joins with
pd.merge
: pd.merge(custom_data, securities, how="left", ...)
. This will result in NaN sids for rows that didn't match, which you can then inspect to determine your next step: custom_data[custom_data.Sid.isnull()]
- Map your dataset using point-in-time ticker symbols, if possible. See the explanation below.
- If your dataset contains ISINs or CUSIPs or another type of identifier supported by the OpenFIGI API, consider using the OpenFIGI API to determine the country-level FIGI, which is the basis of most QuantRocket sids.
- For best results, consider using a cascade of multiple mapping strategies and combining the results.
Point-in-time ticker symbols
Some QuantRocket datasets (specifically the US Stock dataset and EDI datasets) include point-in-time ticker symbols. That is, whereas the Symbol
column in the securities master file reflects the latest ticker symbol for each security, the Symbol
column in the history database reflects the ticker symbol as of each historical date. If your dataset also has point-in-time ticker symbols (rather than just the latest ticker symbol), you can greatly improve your results by matching on ticker symbol and date, instead of just symbol. For example:
>>> from quantrocket.history import download_history_file
>>> import io
>>> import pandas as pd
>>>
>>> f = io.StringIO()
>>> download_history_file(
"usstock-1d", f,
fields=["Sid", "Date", "Symbol"],
start_date="2014-01-01",
end_date="2014-12-30")
>>> usstock_symbols = pd.read_csv(f, parse_dates=["Date"])
>>>
>>> custom_data = pd.merge(custom_data, usstock_symbols, on=["Symbol", "Date"], how="left")
Ensure matching columns
The last step before inserting custom data is to ensure that the DataFrame columns exactly match the columns in the database. This might involve renaming and/or dropping columns:
>>> custom_data = custom_data.rename(columns={"eps": "EPS", "revenue":"Revenue"})
>>> custom_data = custom_data.drop(["ticker"], axis=1)
Your DataFrame's index will not be inserted into the database. Therefore, if one of your data fields is contained in the DataFrame index, you should reset the index, which moves the index to a column:
>>> custom_data = custom_data.reset_index()
Import custom data
Once you have loaded your dataset into pandas, parsed the dates, mapped to sids, and ensured the DataFrame columns match your database columns, you are ready to insert the data. The quantrocket-client
package contains several utilities to assist with this. First, get the full database path if you don't already know it:
>>> from quantrocket.db import list_databases
>>> db_path = list_databases(
services="history",
codes="custom-fundamentals",
detail=True)["sqlite"][0]["path"]
Then, get a connection to the database:
>>> from quantrocket.db import connect_sqlite
>>> conn = connect_sqlite(db_path)
Finally, insert the data into the database by using the insert_or_replace
function (or one of the alternative functions described below) and passing 3 positional arguments: the DataFrame, the database table name (always 'Price'), and the database connection:
>>> from quantrocket.db import insert_or_replace
>>> insert_or_replace(custom_data, 'Price', conn)
Recall that the Price
table's unique primary key is (Sid, Date)
. The insert_or_replace
function will insert your DataFrame records into the Price
table. If a particular combination of sid and date already exists in the table, the record from the DataFrame will overwrite the existing record. Use insert_or_replace
if you want your database to always reflect the latest available data.
Alternatively, you can use the insert_or_ignore
function (which accepts the same 3 positional arguments):
>>> from quantrocket.db import insert_or_ignore
>>> insert_or_ignore(custom_data, 'Price', conn)
With this function, any duplicate records that you try to insert are ignored, thus preserving what is already in the database. Use insert_or_ignore
if you never want to change a record once it has been inserted.
A final option is to use the insert_or_fail
function, which will fail if there are any duplicate records. This function might be useful if you don't expect duplicates and want to be alerted in the event that there are any.
Query custom data
Once you have loaded data into your custom database, you can query the data in all the same ways you can query a standard history database. Examples include:
- Load your data into pandas with get_prices.
- Use get_prices_reindexed_like to load your data into the same shape as another DataFrame. This is useful when you have custom fundamental data and want to use it alongside price data.
- Specify the custom database code as the
DB
parameter in your Moonshot strategy (if your data contains price data). - Load your data as a custom database in Zipline's Pipeline API.
Research
The workflow of many quants includes a research stage prior to backtesting. The purpose of a separate research stage is to rapidly test ideas in a preliminary manner to see if they're worth the effort of a full-scale backtest. The research stage typically ignores transaction costs, liquidity constraints, and other real-world challenges that traders face and that backtests try to simulate. Thus, the research stage constitutes a "first cut": promising ideas advance to the more stringent simulations of backtesting, while unpromising ideas are discarded.
Jupyter notebooks provide Python quants with an excellent tool for ad-hoc research. Jupyter notebooks let you write code to crunch your data, run visualizations, and make sense of the results with narrative commentary.
The get_prices function
The get_prices
function is a flexible and convenient way to load price data into a pandas DataFrame. It can load data from a history database, a real-time aggregate database, or a Zipline bundle.
End-of-day data
Using the Python client, you can load data into a Pandas DataFrame using the database code:
>>> from quantrocket import get_prices
>>> prices = get_prices("usstock-1d", start_date="2017-01-01", fields=["Open","High","Low","Close", "Volume"])
The DataFrame will have a column for each security (represented by sids). For daily bar sizes and larger, the DataFrame will have a two-level index: an outer level for each field (Open, Close, Volume, etc.) and an inner level containing a DatetimeIndex:
>>> prices.head()
Sid FI13857203 FI13905344 FI13905462 FI13905522 FI13905624 \
Field Date
Close 2017-01-04 11150.0 3853.0 4889.0 4321.0 2712.0
2017-01-05 11065.0 3910.0 4927.0 4299.0 2681.0
2017-01-06 11105.0 3918.0 4965.0 4266.0 2672.5
2017-01-10 11210.0 3886.0 4965.0 4227.0 2640.0
2017-01-11 11115.0 3860.0 4970.0 4208.0 2652.0
...
Volume 2018-01-29 685800.0 2996700.0 1000600.0 1339000.0 6499600.0
2018-01-30 641700.0 2686100.0 1421900.0 1709900.0 7039800.0
2018-01-31 603400.0 3179000.0 1517100.0 1471000.0 5855500.0
2018-02-01 447300.0 3300900.0 1295800.0 1329600.0 5540600.0
2018-02-02 510200.0 4739800.0 2060500.0 1145200.0 5585300.0
The DataFrame can be thought of as several stacked DataFrames, one for each field. You can use .loc
to isolate a DataFrame for each field:
>>> closes = prices.loc["Close"]
>>> closes.head()
Sid FI13857203 FI13905344 FI13905462 FI13905522 FI13905624 FI13905665
Date
2017-01-04 11150.0 3853.0 4889.0 4321.0 2712.0 655.9
2017-01-05 11065.0 3910.0 4927.0 4299.0 2681.0 658.4
2017-01-06 11105.0 3918.0 4965.0 4266.0 2672.5 656.2
2017-01-10 11210.0 3886.0 4965.0 4227.0 2640.0 652.8
2017-01-11 11115.0 3860.0 4970.0 4208.0 2652.0 665.1
Each field's DataFrame has the same columns and index, which makes it easy to perform matrix operations. For example, calculate dollar volume (or Euro volume, Yen volume, etc. depending on the universe):
>>> volumes = prices.loc["Volume"]
>>> dollar_volumes = closes * volumes
Or calculate overnight (close-to-open) returns:
>>> opens = prices.loc["Open"]
>>> prior_closes = closes.shift()
>>> overnight_returns = (opens - prior_closes) / prior_closes
>>> overnight_returns.head()
Sid FI13857203 FI13905344 FI13905462 FI13905522 FI13905624 FI13905665 \
Date
2017-01-04 NaN NaN NaN NaN NaN NaN
2017-01-05 0.001345 0.004412 0.003477 -0.002083 0.002765 0.021497
2017-01-06 -0.000904 -0.005115 -0.000812 -0.011165 -0.016039 -0.012606
2017-01-10 -0.003152 -0.006891 0.009869 -0.008204 -0.011038 -0.002591
2017-01-11 0.000446 -0.000257 0.007049 0.004968 0.001894 0.009498
Daily bars can be retrieved from a Zipline bundle containing minute data by specifying data_frequency='daily'
(this parameter is ignored for history databases and real-time databases):
>>> prices = get_prices("usstock-1min", data_frequency="daily", start_date="2017-01-01", fields="Close")
Intraday data
In contrast to daily bars, the stacked DataFrame for intraday bars is a three-level index, consisting of the field, the date, and the time as a string (for example, 09:30:00
):
>>> prices = get_prices("etf-1h", start_date="2017-01-01", fields=["Open","High","Low","Close", "Volume"])
>>> prices.head()
Sid FI756733 FI721954 FI731285
Field Date Time
Close 2017-07-20 09:30:00 247.28 324.30 216.27
10:00:00 247.08 323.94 216.25
11:00:00 246.97 323.63 215.90
12:00:00 247.25 324.11 216.22
13:00:00 247.29 324.32 216.22
...
Volume 2017-08-04 11:00:00 5896400.0 168700.0 170900.0
12:00:00 2243700.0 237300.0 114100.0
13:00:00 2228000.0 113900.0 107600.0
14:00:00 2841400.0 84500.0 116700.0
15:00:00 11351600.0 334000.0 357000.0
As with daily bars, use .loc
to isolate a particular field.
>>> closes = prices.loc["Close"]
>>> closes.head()
Sid FI756733 FI721954 FI731285
Date Time
2017-07-20 09:30:00 247.28 324.30 216.27
10:00:00 247.08 323.94 216.25
11:00:00 246.97 323.63 215.90
12:00:00 247.25 324.11 216.22
13:00:00 247.29 324.32 216.22
To isolate a particular time, use Pandas' .xs
method (short for "cross-section"):
>>> session_closes = closes.xs("15:45:00", level="Time")
>>> session_closes.head()
Sid FI756733 FI721954 FI731285
Date
2017-07-20 247.07 323.84 216.16
2017-07-21 246.89 322.93 215.53
2017-07-24 246.81 323.50 215.09
2017-07-25 247.39 326.37 215.88
2017-07-26 247.45 323.36 216.81
A bar's time represents the start of the bar. Thus, to get the 4:00 PM closing price using 1-minute bars, you would look at the close of the "15:59:00" bar. To get the 3:59 PM price using 1-minute bars, you could look at the open of the "15:59:00" bar or the close of the "15:58:00" bar.
After taking a cross-section of an intraday DataFrame, you can perform matrix operations with bars from different times of day:
>>> opens = prices.loc["Open"]
>>> session_opens = opens.xs("09:30:00", level="Time")
>>> session_closes = closes.xs("15:59:00", level="Time")
>>> prior_session_closes = session_closes.shift()
>>> overnight_returns = (session_opens - prior_session_closes) / prior_session_closes
>>> overnight_returns.head()
Sid FI756733 FI721954 FI731285
Date
2017-07-20 NaN NaN NaN
2017-07-21 -0.002509 -0.001637 -0.004441
2017-07-24 -0.000405 -0.000929 -0.000139
2017-07-25 0.003525 0.005286 0.006555
2017-07-26 0.001455 0.000123 0.004308
Timezone of intraday data
Intraday historical data is stored in the database in ISO-8601 format, which consists of the date followed by the time in the local timezone of the exchange, followed by a UTC offset. For example, a 9:30 AM bar for a stock trading on the NYSE might have a timestamp of 2017-07-25T09:30:00-04:00
, where -04:00
indicates that New York is 4 hours behind Greenwich Mean Time/UTC. This storage format allows QuantRocket to properly align data that may originate from different timezones.
If you don't specify the timezone
parameter when loading prices into Pandas using get_prices
, the function will infer the timezone from the data itself. (This is accomplished by querying the securities master database to determine the timezone of the securities in your dataset.) This approach works fine as long as your data originates from a single timezone. If multiple timezones are represented, an error will be raised.
>>> prices = get_prices("aapl-arb-5min")
ParameterError: cannot infer timezone because multiple timezones are present in data, please specify timezone explicitly (timezones: America/New_York, America/Mexico_City)
In this case, you should manually specify the timezone to which you want the data to be aligned:
>>> prices = get_prices("aapl-arb-5min", timezone="America/New_York")
Historical data with a bar size of 1 day or higher is stored and returned in YYYY-MM-DD format. Specifying a timezone for such a database has no effect.
Securities master fields aligned to prices
Sometimes it is useful to have securities master fields such as the primary exchange in your data analysis. To do so, first use .loc
(or .loc
and .xs
for intraday data) to isolate a particular price field:
>>> prices = get_prices("usstock-1d", fields=["Close","Open"], start_date="2020-03-01")
>>> closes = prices.loc["Close"]
Then use the DataFrame of prices to get a DataFrame of securities master fields shaped like the prices:
>>> from quantrocket.master import get_securities_reindexed_like
>>> securities = get_securities_reindexed_like(closes, fields=["Exchange", "Symbol"])
You can isolate the securities master fields using .loc
:
>>> exchanges = securities.loc["Exchange"]
>>> exchanges.head()
Sid FIBBG000B9XRY4 FIBBG000BKZB36 FIBBG000BMHYD1 FIBBG000BPH459
Date
2020-03-02 XNAS XNYS XNYS XNAS
2020-03-03 XNAS XNYS XNYS XNAS
2020-03-04 XNAS XNYS XNYS XNAS
2020-03-05 XNAS XNYS XNYS XNAS
2020-03-06 XNAS XNYS XNYS XNAS
And perform matrix operations using your securities master data and price data:
>>> closes.where(exchanges=="XNYS").head()
Sid FIBBG000B9XRY4 FIBBG000BKZB36 FIBBG000BMHYD1 FIBBG000BPH459
Date
2020-03-02 NaN 228.4118 140.02 NaN
2020-03-03 NaN 226.4251 135.59 NaN
2020-03-04 NaN 239.4778 143.48 NaN
2020-03-05 NaN 233.2495 142.01 NaN
2020-03-06 NaN 226.9913 142.03 NaN
Load only what you need
The more data you load into Pandas, the slower the performance will be. Therefore, it's a good idea to filter the dataset before loading it, particularly when working with large universes and intraday bars. Use the sids
, universes
, fields
, times
, start_date
, and end_date
parameters to load only the data you need:
>>> prices = get_prices("usstock-1min", start_date="2020-01-01", end_date="2020-01-15", fields=["Open","Close"], times=["09:30:00", "15:59:00"])
QuantRocket doesn't prevent you from trying to load more data than you can fit in memory. If you load too much data and the query is taking too long,
restart the container servicing the query to kill the query.
Cumulative daily prices for intraday data
This feature is available for intraday history databases only, not for real-time aggregate databases or Zipline bundles.
For history databases with bar sizes smaller than 1 day, QuantRocket will calculate and store the day's high, low, and volume as of each intraday bar. When querying intraday data, the additional fields DayHigh
, DayLow
, and DayVolume
are available. Other fields represent only the trading activity that occurred within the duration of a particular bar: for example, the Volume
field for a 15:00:00
bar in a database with 1-hour bars represents the trading volume from 15:00:00 to 16:00:00. In contrast, DayHigh
, DayLow
, and DayVolume
represent the trading activity for the entire day up to and including the particular bar.
>>> prices = get_prices(
"spy-1h",
fields=["Open","High","Low","Close","Volume","DayHigh","DayLow","DayVolume"])
>>>
>>>
>>>
>>> prices.xs("2018-03-08", level="Date").xs("15:00:00", level="Time")
Sid FIBBG000BDTBL9
Field
Close 274.09
DayHigh 274.24
DayLow 272.42
DayVolume 48126000.00
High 274.24
Low 272.97
Open 273.66
Volume 16897100.00
A common use case for cumulative daily totals is if your research idea or trading strategy needs a selection of intraday prices but also needs access to daily price fields (e.g. to calculate average daily volume). Instead of requesting and aggregating all intraday bars (which for large universes might require loading too much data), you can use the times
parameter to load only the intraday bars you need, including the final bar of the trading session to give you access to the daily totals. For example, here is how you might screen for stocks with heavy volume in the opening 30 minutes relative to their average volume:
>>>
>>> prices = get_prices("usa-stk-15min", start_date="2018-01-01", times=["09:45:00","15:45:00"], fields=["DayVolume"])
>>>
>>> early_session_volumes = prices.loc["DayVolume"].xs("09:45:00", level="Time")
>>>
>>> daily_volumes = prices.loc["DayVolume"].xs("15:45:00", level="Time")
>>> avg_daily_volumes = daily_volumes.rolling(window=30).mean()
>>>
>>> volume_surges = early_session_volumes > (avg_daily_volumes.shift() * 2)
Cumulative daily totals are calculated directly from the intraday data in your database and thus will reflect any times
or between-times
filters used when creating the database.
Multi-database queries
Using get_prices
, it is possible to load data from multiple history databases, real-time aggregate databases, and/or Zipline bundles into the same DataFrame (provided the databases have the same bar size). This allows you (for example) to combine historical data with today's real-time updates:
>>>
>>> prices = get_prices(["fang-stk-1min",
"fang-stk-tick-1min"],
start_date="2019-06-01",
fields=["Close", "LastPriceClose"])
>>>
>>>
>>> history_closes = prices.loc["Close"]
>>> realtime_closes = prices.loc["LastPriceClose"]
>>>
>>>
>>> combined_closes = realtime_closes.fillna(history_closes)
Prices aligned to other prices
Sometimes it is useful to get a DataFrame of prices shaped like another DataFrame of prices. Although this can sometimes be achieved using multi-database queries, another approach which offers additional flexibility is to use the function get_prices_reindexed_like
. Unlike multi-database queries, this function can be used even when the bar sizes of the two databases differ. This function is analogous to get_securities_reindexed_like
for securities master data and the various get_*_reindexed_like
functions provided for fundamental data. It uses get_prices
under the hood and thus can be used with any data source queryable with get_prices
(that is, history databases, real-time aggregate databases, or Zipline bundles).
For example, suppose you created a custom database with fundamental data. Given a DataFrame of prices:
>>> from quantrocket import get_prices
>>> prices = get_prices("usstock-1d", fields=["Close"], start_date="2020-03-01")
>>> closes = prices.loc["Close"]
You could load the fundamental data and perform matrix operations:
>>> from quantrocket import get_prices_reindexed_like
>>> fundamentals = get_prices_reindexed_like(
closes, "custom-fundamentals", fields=["Revenue"],
lookback_window=180)
>>> revenues = fundamentals.loc["Revenue"]
>>>
>>> have_high_revenue = revenues > 100e6
>>> returns = closes.pct_change().where(have_high_revenue)
This function can be used to query daily or intraday databases. With intraday databases, the results are aggregated into daily results using a customizable aggregation method. Other parameters control how the queried data is aligned with the source DataFrame. See the API Reference for more details.
Alphalens
Alphalens is an open source library for analyzing alpha factors. You can use Alphalens early in your research process to determine if your ideas look promising.
For example, suppose you wanted to analyze the momentum factor, which says that recent winners tend to outperform recent losers. First, load your historical data and extract the closing prices:
>>> prices = get_prices("demo-stocks-1d", start_date="2010-01-01", fields=["Close"])
>>> closes = prices.loc["Close"]
Next, calculate the 12-month returns, skipping the most recent month (as commonly prescribed in academic papers about the momentum factor):
>>> MOMENTUM_WINDOW = 252
>>> RANKING_PERIOD_GAP = 22
>>> earlier_closes = closes.shift(MOMENTUM_WINDOW)
>>> later_closes = closes.shift(RANKING_PERIOD_GAP)
>>> returns = (later_closes - earlier_closes) / earlier_closes
The 12-month returns are the predictive factor we will pass to Alphalens, along with pricing data so Alphalens can see whether the factor was in fact predictive. To avoid lookahead bias, in this example we should shift()
our factor forward one period to align it with the subsequent prices, since the subsequent prices would represent our entry prices after calculating the factor. Alphalens expects the predictive factor to be stacked into a MultiIndex Series, while pricing data should be a DataFrame:
>>>
>>> returns = returns.shift()
>>>
>>> returns = returns.stack()
>>> factor_data = alphalens.utils.get_clean_factor_and_forward_returns(returns, closes)
>>> alphalens.tears.create_returns_tear_sheet(factor_data)
You'll see tabular statistics as well as graphs that look something like this:

For a detailed walk-through of an Alphalens tear sheet, see Lecture 38 in the Quant Finance Lectures in the Code Library.
Code reuse in Jupyter
If you find yourself writing the same code again and again, you can factor it out into a .py
file in Jupyter and import it into your notebooks and algo files. Any .py
files in or under the /codeload
directory inside Jupyter (that is, in or under the top-level directory visible in the Jupyter file browser) can be imported using standard Python import syntax. For example, suppose you've implemented a function in /codeload/research/utils.py
called analyze_fundamentals
. You can import and use the function in another file or notebook:
from codeload.research.utils import analyze_fundamentals
The .py
files can live wherever you like in the directory tree; subdirectories can be reached using standard Python dot syntax.
To make your code importable as a standard Python package, the 'codeload' directory and each subdirectory must contain a __init__.py
file. QuantRocket will create these files automatically if they don't exist.
Moonshot
Moonshot is a fast, vectorized Pandas-based backtester that supports daily or intraday data, multi-strategy backtests and parameter scans, and live trading. It is well-suited for running cross-sectional strategies or screens involving hundreds or even thousands of securities.
What is Moonshot?
Key features
Pandas-based: Moonshot is based on Pandas, the centerpiece of the Python data science stack. If you love Pandas you'll love Moonshot. Moonshot can be thought of as a set of conventions for organizing Pandas code for the purpose of running backtests.
Lightweight: Moonshot is simple and lightweight because it relies on the power and flexibility of Pandas and doesn't attempt to re-create functionality that Pandas can already do. No bloated codebase full of countless indicators and models to import and learn. Most of Moonshot's code is contained in a single Moonshot
class.
Fast: Moonshot is fast because Pandas is fast. No event-driven backtester can match Moonshot's speed. Speed promotes alpha discovery by facilitating rapid experimentation and research iteration.
Multi-asset class, multi-time frame: Moonshot supports end-of-day and intraday strategies using equities, futures, and FX.
Machine learning support: Moonshot supports machine learning and deep learning strategies using scikit-learn or Keras.
Live trading: Live trading with Moonshot can be thought of as running a backtest on up-to-date historical data and generating a batch of orders based on the latest signals produced by the backtest.
No black boxes, no magic: Moonshot provides many conveniences to make backtesting easier, but it eschews hidden behaviors and complex, under-the-hood simulation rules that are hard to understand or audit. What you see is what you get.
Vectorized vs event-driven backtesters
What's the difference between event-driven backtesters like Zipline and vectorized backtesters like Moonshot? Event-driven backtests process one event at a time, where an event is usually one historical bar (or in the case of live trading, one real-time quote). Vectorized backtests process all events at once, by performing simultaneous calculations on an entire vector or matrix of data. (In pandas, a Series
is a vector and a DataFrame
is a matrix).
Imagine a simplistic strategy of buying a security whenever the price falls below $10 and selling whenever it rises above $10. We have a time series of prices and want to know which days to buy and which days to sell. In an event-driven backtester we loop through one date at a time and check the price at each iteration:
>>> data = {
>>> "2017-02-01": 10.07,
>>> "2017-02-02": 9.87,
>>> "2017-02-03": 9.91,
>>> "2017-02-04": 10.01
>>> }
>>> for date, price in data.items():
>>> if price < 10:
>>> buy_signal = True
>>> else:
>>> buy_signal = False
>>> print(date, buy_signal)
2017-02-01 False
2017-02-02 True
2017-02-03 True
2017-02-04 False
In a vectorized backtest, we check all the prices at once to calculate our buy signals:
>>> import pandas as pd
>>> data = {
>>> "2017-02-01": 10.07,
>>> "2017-02-02": 9.87,
>>> "2017-02-03": 9.91,
>>> "2017-02-04": 10.01
>>> }
>>> prices = pd.Series(data)
>>> buy_signals = prices < 10
>>> buy_signals.head()
2017-02-01 False
2017-02-02 True
2017-02-03 True
2017-02-04 False
dtype: bool
Both backtests produce the same result but use a different approach.
Vectorized backtests are faster than event-driven backtests
Speed is one of the principal benefits of vectorized backtests, thanks to running calculations on an entire time series at once. Event-driven backtests can be prohibitively slow when working with large universes of securities and large amounts of data. Because of their speed, vectorized backtesters support rapid experimentation and testing of new ideas.
Watch out for look-ahead bias with vectorized backtesters
Look-ahead bias refers to making decisions in your backtest based on information that wouldn't have been available at the time of the trade. Because event-driven backtesters only give you one bar at a time, they generally protect you from look-ahead bias. Because a vectorized backtester gives you the entire time-series, it's easier to introduce look-ahead bias by mistake, for example generating signals based on today's close but then calculating the return from today's open instead of tomorrow's.
If you achieve a phenomenal backtest result on the first try with a vectorized backtester, check for look-ahead bias.
How does live trading work?
With event-driven backtesters, switching from backtesting to live trading typically involves changing out a historical data feed for a real-time market data feed, and replacing a simulated broker with a real broker connection.
With a vectorized backtester, live trading can be achieved by running an up-to-the-moment backtest and using the final row of signals (that is, today's signals) to generate orders.
Supported types of strategies
The vectorized design of Moonshot is well-suited for cross-sectional and factor-model strategies with regular rebalancing intervals, or for any strategy that "wakes up" at a particular time, checks current and historical market conditions, and makes trading decisions accordingly.
Examples of supported strategies:
- End-of-day strategies
- Intraday strategies that trade once per day at a particular time of day
- Intraday strategies that trade throughout the day
- Cross-sectional and factor-model strategies
- Market neutral strategies
- Seasonal strategies (where "seasonal" might be time of year, day of month, day of week, or time of day)
- Strategies that use fundamental data
- Strategies that screen thousands of stocks using daily data
- Strategies that screen thousands of stocks using 15- or 30-minute intraday data
- Strategies that screen a few hundred stocks using 5-minute intraday data
- Strategies that screen a few stocks using 1-minute intraday data
Examples of unsupported strategies:
- Path-dependent strategies that don't lend themselves to Moonshot's vectorized design
Backtesting
An example Moonshot strategy template is available from the JupyterLab launcher.
Backtesting quickstart
Let's design a dual moving average strategy which buys tech stocks when their short moving average is above their long moving average. Assume we've collected US Stock data into a database called 'usstock-1d' and created a universe of several tech stocks:
$ quantrocket master get -e 'XNAS' -s 'GOOGL' 'NFLX' 'AAPL' 'AMZN' | quantrocket master universe 'tech-giants' -f -
code: tech-giants
inserted: 4
provided: 4
total_after_insert: 4
Now let's write the minimal strategy code to run a backtest:
import pandas as pd
from moonshot import Moonshot
class DualMovingAverageStrategy(Moonshot):
CODE = "dma-tech"
DB = "usstock-1d"
UNIVERSES = "tech-giants"
LMAVG_WINDOW = 300
SMAVG_WINDOW = 100
def prices_to_signals(self, prices: pd.DataFrame):
closes = prices.loc["Close"]
lmavgs = closes.rolling(self.LMAVG_WINDOW).mean()
smavgs = closes.rolling(self.SMAVG_WINDOW).mean()
signals = smavgs.shift() > lmavgs.shift()
return signals.astype(int)
A strategy is a subclass of the Moonshot
class. You implement your trading logic in the class methods and store your strategy parameters as class attributes. Class attributes include built-in Moonshot parameters which you can specify or override, as well as your own custom parameters. In the above example, CODE
and DB
are built-in parameters while LMAVG_WINDOW
and SMAVG_WINDOW
are custom parameters which we've chosen to store as class attributes, which will allow us to run parameter scans or create similar strategies with different parameters.
Place your code in a file inside the 'moonshot' directory in JupyterLab. QuantRocket recursively scans .py
files in this directory and loads your strategies.
You can run backtests via the command line or inside a Jupyter notebook, and you can get back a CSV of backtest results or a tear sheet with performance plots.
$ quantrocket moonshot backtest 'dma-tech' -s '2005-01-01' -e '2017-01-01' --pdf -o dma_tech_tearsheet.pdf --details
>>> from quantrocket.moonshot import backtest
>>> from moonchart import Tearsheet
>>> backtest("dma-tech", start_date="2005-01-01", end_date="2017-01-01",
details=True, filepath_or_buffer="dma_tech.csv")
>>> Tearsheet.from_moonshot_csv("dma_tech.csv")
$ curl -X POST 'http://houston/moonshot/backtests?strategies=dma-tech&start_date=2005-01-01&end_date=2017-01-01&pdf=true&details=true' > dma_tech_tearsheet.pdf
The performance plots will resemble the following:

Backtest visualization and analysis in Jupyter
In addition to running backtests from the CLI, you can run backtests from a Jupyter notebook and perform analysis and visualizations inside the notebook. First, run the backtest and save the results to a CSV:
>>> from quantrocket.moonshot import backtest
>>> backtest("dma-tech", start_date="2005-01-01", end_date="2017-01-01",
filepath_or_buffer="dma_tech_results.csv")
You can do four main things with the CSV results:
- generate a performance tear sheet using Moonchart, an open source companion library to Moonshot;
- generate a performance tear sheet using pyfolio, another open source backtest visualization library;
- use Moonchart to get a
DailyPerformance
object and create your own plots; and - load the results into a Pandas DataFrame for further analysis.
Moonchart tear sheet
To look at a Moonchart tear sheet:
>>> from moonchart import Tearsheet
>>> Tearsheet.from_moonshot_csv("dma_tech_results.csv")
pyfolio tear sheet
To look at a pyfolio tear sheet:
>>> import pyfolio as pf
>>> pf.from_moonshot_csv("dma_tech_results.csv")
Moonchart and pyfolio offer somewhat different visualizations so it's nice to look at both.
For a detailed walk-through of a pyfolio tear sheet, see Lecture 33 in the Quant Finance Lectures in the Code Library.
Custom plots with Moonchart
For finer-grained control with Moonchart or for times when you don't want a full tear sheet, you can instantiate a DailyPerformance
object and create your own individual plots:
>>> from moonchart import DailyPerformance
>>> perf = DailyPerformance.from_moonshot_csv("dma_tech_results.csv")
>>> perf.cum_returns.tail()
AAPL(FIBBG000B9XRY4) AMZN(FIBBG000BVPV84) NFLX(FIBBG000CL9VN6) GOOGL(FIBBG009S39JX6)
Date
2020-03-31 1.958090 3.453483 2.479267 0.986340
2020-04-01 1.932332 3.434876 2.460417 0.973639
2020-04-02 1.940393 3.439886 2.470554 0.976936
2020-04-03 1.933422 3.434400 2.456668 0.971617
2020-04-06 1.975589 3.475380 2.487567 0.991732
>>> perf.cum_returns.plot()
You can use the DailyPerformance
object to construct an AggregateDailyPerformance
object representing aggregated backtest results:
>>> from moonchart import AggregateDailyPerformance
>>> agg_perf = AggregateDailyPerformance(perf)
>>> agg_perf.cum_returns.tail()
Date
2020-03-31 13.708673
2020-04-01 13.173726
2020-04-02 13.346788
2020-04-03 13.129860
2020-04-06 14.009854
>>> agg_perf.cum_returns.plot()
See Moonchart reference for available performance attributes.
Raw backtest results analysis
You can also load the backtest results into a DataFrame:
>>> from quantrocket.moonshot import read_moonshot_csv
>>> results = read_moonshot_csv("dma_tech_results.csv")
>>> results.tail()
AAPL(FIBBG000B9XRY4) AMZN(FIBBG000BVPV84) NFLX(FIBBG000CL9VN6) GOOGL(FIBBG009S39JX6)
Field Date
Weight 2020-03-31 0.25 0.25 0.25 0.25
2020-04-01 0.25 0.25 0.25 0.25
2020-04-02 0.25 0.25 0.25 0.25
2020-04-03 0.25 0.25 0.25 0.25
2020-04-06 0.25 0.25 0.25 0.25
The DataFrame consists of several stacked DataFrames, one DataFrame per field (see backtest field reference). Use .loc
to isolate a particular field:
>>> returns = results.loc["Return"]
>>> returns.tail()
AAPL(FIBBG000B9XRY4) AMZN(FIBBG000BVPV84) NFLX(FIBBG000CL9VN6) GOOGL(FIBBG009S39JX6)
Date
2020-03-31 -0.000510 -0.001811 0.003060 0.003411
2020-04-01 -0.013154 -0.005388 -0.007603 -0.012877
2020-04-02 0.004172 0.001459 0.004120 0.003387
2020-04-03 -0.003593 -0.001595 -0.005620 -0.005445
2020-04-06 0.021809 0.011932 0.012577 0.020703
Since we specified details=True
when running the backtest, there is a column per security. Had we omitted details=True
, or if we were running a multi-strategy backtest, there would be a column per strategy.
How a Moonshot backtest works
Moonshot is all about DataFrames. In a Moonshot backtest, we start with a DataFrame of historical prices and derive a variety of equivalently-indexed DataFrames, including DataFrames of signals, trade allocations, positions, and returns. These DataFrames consist of a time-series index (vertical axis) with one or more securities as columns (horizontal axis). A simple example of a DataFrame of signals is shown below for a strategy with a 2-security universe (securities are identified by sid):
Sid FIBBG12345 FIBBG67890
Date
2017-09-19 0 -1
2017-09-20 1 -1
2017-09-21 1 0
A Moonshot strategy consists of strategy parameters (stored as class attributes) and strategy logic (implemented in class methods). The strategy logic required to run a backtest is spread across four main methods, mirroring the stages of a trade:
| method name | input/output |
---|
what direction to trade? | prices_to_signals | from a DataFrame of prices, return a DataFrame of integer signals, where 1=long, -1=short, and 0=cash |
how much capital to allocate to the trades? | signals_to_target_weights | from a DataFrame of integer signals (-1, 0, 1), return a DataFrame indicating how much capital to allocate to the signals, expressed as a percentage of the total capital allocated to the strategy (for example, -0.25, 0, 0.1 to indicate 25% short, cash, 10% long) |
enter the positions when? | target_weights_to_positions | from a DataFrame of target weights, return a DataFrame of positions (here we model the delay between when the signal occurs and when the position is entered, and possibly model non-fills) |
what's our return? | positions_to_gross_returns | from a DataFrame of positions and a DataFrame of prices, return a DataFrame of percentage returns before commissions and slippage (our return is the security's percent change over the period, multiplied by the size of the position) |
Since Moonshot is a vectorized backtester, each of these methods is called only once per backtest.
Our demo strategy above relies on the default implementations of several of these methods, but since it's better to be explicit than implicit, you should always implement these methods even if you copy the default behavior. Let's explicitly implement the default behavior in our demo strategy:
import pandas as pd
from moonshot import Moonshot
class DualMovingAverageStrategy(Moonshot):
CODE = "dma-tech"
DB = "usstock-1d"
UNIVERSES = "tech-giants"
LMAVG_WINDOW = 300
SMAVG_WINDOW = 100
def prices_to_signals(self, prices: pd.DataFrame):
closes = prices.loc["Close"]
lmavgs = closes.rolling(self.LMAVG_WINDOW).mean()
smavgs = closes.rolling(self.SMAVG_WINDOW).mean()
signals = smavgs.shift() > lmavgs.shift()
return signals.astype(int)
def signals_to_target_weights(self, signals: pd.DataFrame, prices: pd.DataFrame):
weights = self.allocate_equal_weights(signals)
return weights
def target_weights_to_positions(self, weights: pd.DataFrame, prices: pd.DataFrame):
positions = weights.shift()
return positions
def positions_to_gross_returns(self, positions: pd.DataFrame, prices: pd.DataFrame):
closes = prices.loc["Close"]
gross_returns = closes.pct_change() * positions.shift()
return gross_returns
To summarize the above code, we generate signals based on moving average crossovers, we divide our capital equally among the securities with signals, we enter the positions the next day, and compute our (gross) returns using the securities' close-to-close returns.
Several weight allocation algorithms are provided out of the box via moonshot.mixins.WeightAllocationMixin
.
Benchmarks
Optionally, we can identify a benchmark security and get a plot of the strategy's performance against the benchmark. The benchmark can exist within the same database used by the strategy, or a different database. Let's make SPY
our benchmark. First, look up the sid, since that's how we specify the benchmark:
$ quantrocket master get --exchanges 'ARCX' --symbols 'SPY' --sec-types 'ETF' --fields 'Sid'
Sid
FIBBG000BDTBL9
Now set this sid as the benchmark:
class DualMovingAverageStrategy(Moonshot):
CODE = "dma-tech"
DB = "usstock-1d"
UNIVERSES = "tech-giants"
BENCHMARK = "FIBBG000BDTBL9"
Run the backtest again, and we'll see an additional chart in our tear sheet:

To use a benchmark security from a different database, specify a BENCHMARK_DB
:
class DualMovingAverageStrategy(Moonshot):
CODE = "dma-tech"
DB = "usstock-1d"
UNIVERSES = "tech-giants"
BENCHMARK = "IB416904"
BENCHMARK_DB = "ibkr-indexes-1d"
Specifying a benchmark means it will be included in the prices DataFrame that is passed to prices_to_signals
and other methods. Depending on your trading logic, this might result in your strategy generating signals for the benchmark security. If that is not what you want, you can zero out signals for your benchmark security:
def prices_to_signals(self, prices: pd.DataFrame):
....
signals[self.BENCHMARK] = 0
Multi-strategy backtests
We can easily backtest multiple strategies at once to simulate running complex portfolios of strategies. Simply specify all of the strategies:
$ quantrocket moonshot backtest 'dma-tech' 'dma-etf' -s '2005-01-01' -e '2017-01-01' --pdf -o dma_multistrat.pdf
>>> from quantrocket.moonshot import backtest
>>> from moonchart import Tearsheet
>>> backtest(["dma-tech", "dma-etf"], start_date="2005-01-01", end_date="2017-01-01",
filepath_or_buffer="dma_multistrat.csv")
>>> Tearsheet.from_moonshot_csv("dma_multistrat.csv")
$ curl -X POST 'http://houston/moonshot/backtests?strategies=dma-etf&strategies=dma-tech&start_date=2005-01-01&end_date=2017-01-01&pdf=true' > dma_multistrat.pdf
Our tear sheet will show the aggregate portfolio performance as well as the individual strategy performance:

By default, when backtesting multiple strategies, capital is divided equally among the strategies; that is, each strategy's allocation is 1.0 / number of strategies
. If this isn't what you want, you can specify custom allocations for each strategy (which need not add up to 1):
$
$ quantrocket moonshot backtest 'dma-tech' 'dma-etf' --allocations 'dma-tech:1.25' 'dma-etf:0.25' -s '2005-01-01' -e '2017-01-01' --pdf -o dma_multistrat.pdf
>>> from quantrocket.moonshot import backtest
>>>
>>> backtest(["dma-tech", "dma-etf"],
allocations={"dma-tech": 1.25, "dma-etf": 0.25},
start_date="2005-01-01", end_date="2017-01-01",
filepath_or_buffer="dma_multistrat.csv")
$
$ curl -X POST 'http://houston/moonshot/backtests?strategies=dma-etf&strategies=dma-tech&start_date=2005-01-01&end_date=2017-01-01&allocations=dma-tech%3A1.25&allocations=dma-etf%3A0.25&pdf=true' > dma_multistrat.pdf
Set parameters on-the-fly
You can change Moonshot parameters on-the-fly from the Python client or CLI when running backtests, without having to edit your .py
algo files. Pass parameters as KEY:VALUE
pairs:
$
$ quantrocket moonshot backtest 'dma-tech' -o dma_tech_no_commissions.csv --params 'COMMISSION_CLASS:None'
>>>
>>> backtest("dma-tech", filepath_or_buffer="dma_tech_no_commissions.csv",
params={"COMMISSION_CLASS":None})
$
$ curl -X POST 'http://houston/moonshot/backtests?strategies=dma-tech¶ms=COMMISSION_CLASS%3ANone' > dma_tech_no_commissions.csv
This capability is provided as a convenience and helps protect you from temporarily editing your algo file and forgetting to change it back. It also makes your notebooks more self-documenting when you are testing different values for a parameter. The feature is also available for parameter scans:
$
$ quantrocket moonshot paramscan 'dma-tech' -p 'SMAVG_WINDOW' -v 5 20 100 --params 'SLIPPAGE_BPS:2' -o dma_tech_1d_with_slippage.csv
>>>
>>> from quantrocket.moonshot import scan_parameters
>>> scan_parameters("dma-tech",
param1="SMAVG_WINDOW", vals1=[5,20,100],
params={"SLIPPAGE_BPS":2},
filepath_or_buffer="dma_tech_1d_with_slippage.csv")
$
$ curl -X POST 'http://houston/moonshot/paramscans?strategies=dma-tech¶m1=SMAVG_WINDOW&vals1=5&vals1=20&vals1=100&SLIPPAGE_BPS%3A2' > dma_tech_1d_with_slippage.csv
Lookback windows
Commonly, your strategy may need an initial cushion of data to perform rolling calculations (such as moving averages) before it can begin generating signals. By default, Moonshot will infer the required cushion size by using the largest integer value of any strategy attribute whose name ends with _WINDOW
. In the following example, the lookback window will be set to 200 days:
class DualMovingAverage(Moonshot):
...
SMAVG_WINDOW = 50
LMAVG_WINDOW = 200
This means Moonshot will load 200 trading days of historical data (plus a small additional buffer) prior to your backtest start date so that your signals can actually begin on the start date. If there are no _WINDOW
attributes, the cushion defaults to 252 (approx. 1 year).
Additionally, any attributes ending with _INTERVAL
which contain pandas offset aliases will be used to further pad the lookback window. In the following example, the calculated lookback window will be 100 trading days to cover the moving average window plus an additional month to cover the rebalancing interval:
class MonthlyRebalancingStrategy(Moonshot):
...
MAVG_WINDOW = 100
REBALANCE_INTERVAL = "M"
You can override the default behavior by explicitly setting the LOOKBACK_WINDOW
attribute (set to 0 to disable):
class StrategyWithQuarterlyLookback(Moonshot):
...
LOOKBACK_WINDOW = 63
If you make a habit of storing rolling window lengths as class attributes ending with _WINDOW
and storing rebalancing intervals as class attributes ending with _INTERVAL
, the lookback window will usually take care of itself and you shouldn't need to worry about it.
Adequate lookback windows are especially important for live trading. In case you don't name your rolling window attributes with _WINDOW
, make sure to define a LOOKBACK_WINDOW
that is adequate for your strategy's rolling calculations, as an inadequate lookback window will mean your strategy doesn't load enough data in live trading and therefore never generates any trades.
Segmented backtests
When running a backtest on a large universe and sizable date range, you might run out of memory. You'll see an error like this:
$ quantrocket moonshot backtest 'big-boy' --start-date '2000-01-01'
msg: 'HTTPError(''502 Server Error: Bad Gateway for url: http://houston/moonshot/backtests?strategies=big-boy&start_date=2000-01-01'',
''please check the logs for more details'')'
status: error
And in the logs you'll find this:
$ quantrocket flightlog stream --hist 1
quantrocket.moonshot: ERROR the system killed the worker handling the request, likely an Out Of Memory error; \if you were backtesting, try a segmented backtest to reduce memory usage (for example `segment="A"`), or add more memory
When this happens, you can try a segmented backtest. In a segmented backtest, QuantRocket breaks the backtest date range into smaller segments (for example, 1-year segments), runs each segment of the backtest in succession, and concatenates the partial results into a single backtest result. The output is identical to a non-segmented backtest, but the memory footprint is smaller. The segment
option takes a Pandas frequency string specifying the desired size of the segments, for example "Y" for yearly segments, "Q" for quarterly segments, or "2Y" for 2-year segments:
$ quantrocket moonshot backtest 'big-boy' -s '2000-01-01' -e '2018-01-01' --segment 'Y' -o backtest_result.csv
>>> from quantrocket.moonshot import backtest
>>> backtest("big-boy", start_date="2001-01-01", end_date="2018-01-01", segment="Y", filepath_or_buffer="backtest_result.csv")
$ curl -X POST 'http://houston/moonshot/backtests.csv?strategies=big-boy&start_date=2001-01-01&end_date=2018-01-01&segment=Y'
Providing a start and end date is optional for a non-segmented backtest but required for a segmented backtest.
In the detailed logs, you'll see Moonshot running through each backtest segment:
$ quantrocket flightlog stream -d
quantrocket_moonshot_1|[big-boy] Backtesting strategy from 2001-01-01 to 2001-12-30
quantrocket_moonshot_1|[big-boy] Backtesting strategy from 2001-12-31 to 2002-12-30
quantrocket_moonshot_1|[big-boy] Backtesting strategy from 2002-12-31 to 2003-12-30
quantrocket_moonshot_1|[big-boy] Backtesting strategy from 2003-12-31 to 2004-12-30
quantrocket_moonshot_1|[big-boy] Backtesting strategy from 2004-12-31 to 2005-12-30
...
When running a segmented backtest to reduce memory usage, you might want to avoid specifying details=True
. Moonshot concatentates the partial backtest results at the end of a segmented backtest, and if you specify details=True
, the partial results will contain a column for each security. Concatenating this much data may negate the memory benefit of running the backtest in segments.
Backtest field reference
Backtest result CSVs contain the following fields in a stacked format. Each field is a DataFrame from the backtest. For detailed backtests, there is a column per security. For non-detailed or multi-strategy backtests, there is a column per strategy, with each column containing the aggregated (summed) results of all securities in the strategy.
Signal
: the signals returned by prices_to_signals
.NetExposure
: the net long or short positions returned by target_weights_to_positions
. Expressed as a proportion of capital base.AbsExposure
: the absolute value of positions, irrespective of their side (long or short). Expressed as a proportion of capital base. This represents the total market exposure of the strategy.Weight
: the target weights allocated to the strategy, after multiplying by strategy allocation and applying any weight constraints. Expressed as a proportion of capital base.AbsWeight
: the absolute value of the target weights.Turnover
: the strategy's day-to-day turnover. Expressed as a proportion of capital base.TotalHoldings
: the total number of holdings for the period.Return
: the returns, after commissions and slippage. Expressed as a proportion of capital base.Commission
: the commissions deducted from gross returns. Expressed as a proportion of capital base.Slippage
: the slippage deducted from gross returns. Expressed as a proportion of capital base.Benchmark
: the prices of the benchmark security, if any.
Moonchart reference
Moonchart DailyPerformance
and AggregateDailyPerformance
objects provide the following attributes.
Attributes copied directly from backtest results:
returns
: the returns, after commissions and slippage. Expressed as a proportion of capital base.net_exposures
: the net long or short positions. Expressed as a proportion of capital base.abs_exposures
: the absolute value of positions, irrespective of their side (long or short). Expressed as a proportion of capital base. This represents the total market exposure of the strategy.total_holdings
: the total number of holdings for the period.turnover
- the strategy's day-to-day turnover. Expressed as a proportion of capital base.commissions
- the commissions deducted from gross returns. Expressed as a proportion of capital base.slippages
- the slippage deducted from gross returns. Expressed as a proportion of capital base.benchmark_prices
: the prices of the benchmark security, if any.
Calculated attributes:
cum_returns
- cumulative returnscum_commissions
- cumulative commissionscum_slippage
- cumulative slippagecagr
- compound annual growth rate. DailyPerformance.cagr
returns a Series while AggregateDailyPerformance.cagr
returns a scalar.sharpe
- Sharpe ratio. DailyPerformance.sharpe
returns a Series while AggregateDailyPerformance.sharpe
returns a scalar.rolling_sharpe
- rolling Sharpe ratiodrawdowns
- drawdownsmax_drawdown
- maximum drawdowns. DailyPerformance.max_drawdown
returns a Series while AggregateDailyPerformance.max_drawdown
returns a scalar.benchmark_returns
- benchmark returns calculated from benchmark pricesbenchmark_cum_returns
- cumulative returns for benchmark
Parameter scans
You can run 1-dimensional or 2-dimensional parameter scans to see how your strategy performs for a variety of parameter values. You can run parameter scans against any parameter which is stored as a class attribute on your strategy (or as a class attribute on a parent class of your strategy).
For example, returning to the moving average crossover example, recall that the long and short moving average windows are stored as class attributes:
class DualMovingAverageStrategy(Moonshot):
CODE = "dma-tech"
DB = "usstock-1d"
UNIVERSES = "tech-giants"
LMAVG_WINDOW = 300
SMAVG_WINDOW = 100
Let's try varying the short moving average window on our dual moving average strategy:
$ quantrocket moonshot paramscan 'dma-tech' -p 'SMAVG_WINDOW' -v 5 20 100 -s '2005-01-01' -e '2017-01-01' --pdf -o dma_1d.pdf
>>> from quantrocket.moonshot import scan_parameters
>>> from moonchart import ParamscanTearsheet
>>> scan_parameters("dma-tech", start_date="2005-01-01", end_date="2017-01-01",
param1="SMAVG_WINDOW", vals1=[5,20,100],
filepath_or_buffer="dma_tech_1d.csv")
>>>
>>> ParamscanTearsheet.from_csv("dma_tech_1d.csv")
$ curl -X POST 'http://houston/moonshot/paramscans?strategies=dma-tech&start_date=2005-01-01&end_date=2017-01-01¶m1=SMAVG_WINDOW&vals1=5&vals1=20&vals1=100&pdf=true' > dma_tech_1d.pdf
The resulting tear sheet will show how the strategy performs for each parameter value:

Results are also logged to flightlog for each tested parameter:
quantrocket.moonshot: INFO CAGR Sharpe MaxDrawdown AbsExposure NormalizedCagr DailyHoldings
quantrocket.moonshot: INFO SMAVG_WINDOW = 5 0.36 1.21 -0.37 0.94 0.38 2.87
quantrocket.moonshot: INFO SMAVG_WINDOW = 20 0.31 1.05 -0.53 0.94 0.33 2.86
quantrocket.moonshot: INFO SMAVG_WINDOW = 100 0.24 0.86 -0.52 0.94 0.26 2.79
Let's try a 2-dimensional parameter scan, varying both our short and long moving averages:
$ quantrocket moonshot paramscan 'dma-tech' --param1 'SMAVG_WINDOW' --vals1 5 20 100 --param2 'LMAVG_WINDOW' --vals2 150 200 300 -s '2005-01-01' -e '2017-01-01' --pdf -o dma_2d.pdf
>>> from quantrocket.moonshot import scan_parameters
>>> from moonchart import ParamscanTearsheet
>>> scan_parameters("dma-tech", start_date="2005-01-01", end_date="2017-01-01",
param1="SMAVG_WINDOW", vals1=[5,20,100],
param2="LMAVG_WINDOW", vals2=[150,200,300],
filepath_or_buffer="dma_tech_2d.csv")
>>> ParamscanTearsheet.from_csv("dma_tech_2d.csv")
$ curl -X POST 'http://houston/moonshot/paramscans?strategies=dma-tech&start_date=2005-01-01&end_date=2017-01-01¶m1=SMAVG_WINDOW&vals1=5&vals1=20&vals1=100¶m2=LMAVG_WINDOW&vals2=150&vals2=200&vals2=300&pdf=true' > dma_tech_2d.pdf
This time our tear sheet uses a heat map to visualize the 2-D results:

We can even run a 1-D or 2-D parameter scan on multiple strategies at once:
$ quantrocket moonshot paramscan 'dma-tech' 'dma-etf' -p 'SMAVG_WINDOW' -v 5 20 100 -s '2005-01-01' -e '2017-01-01' --pdf -o dma_multistrat_1d.pdf
>>> from quantrocket.moonshot import scan_parameters
>>> from moonchart import ParamscanTearsheet
>>> scan_parameters(["dma-tech","dma-etf"], start_date="2005-01-01", end_date="2017-01-01",
param1="SMAVG_WINDOW", vals1=[5,20,100],
filepath_or_buffer="dma_multistrat_1d.csv")
>>> ParamscanTearsheet.from_csv("dma_multistrat_1d.csv")
$ curl -X POST 'http://houston/moonshot/paramscans?strategies=dma-tech&strategies=dma-etf&start_date=2005-01-01&end_date=2017-01-01¶m1=SMAVG_WINDOW&vals1=5&vals1=20&vals1=100&pdf=true' > dma_multistrat_1d.pdf
The tear sheet shows the scan results for the individual strategies and the aggregate portfolio:

Often when first coding a strategy your parameter values will be hardcoded in the body of your methods:
class TrendDay(Moonshot):
...
def prices_to_signals(self, prices: pd.DataFrame):
...
afternoon_prices = closes.xs("14:00:00", level="Time")
...
When you're ready to run parameter scans, simply factor out the hardcoded values into class attributes, naming the attribute whatever you like:
class TrendDay(Moonshot):
...
DECISION_TIME = "14:00:00"
def prices_to_signals(self, prices: pd.DataFrame):
...
afternoon_prices = closes.xs(self.DECISION_TIME, level="Time")
...
Now run your parameter scan:
$ quantrocket moonshot paramscan 'trend-day' -p 'DECISION_TIME' -v '14:00:00' '14:15:00' '14:30:00' --pdf -o trend_day_afternoon_time_scan.pdf
>>> from quantrocket.moonshot import scan_parameters
>>> from moonchart import ParamscanTearsheet
>>> scan_parameters("trend-day",
param1="DECISION_TIME", vals1=["14:00:00", "14:15:00", "14:30:00"],
filepath_or_buffer="trend_day_afternoon_time_scan.csv")
>>> ParamscanTearsheet.from_csv("trend_day_afternoon_time_scan.csv")
$ curl -X POST 'http://houston/moonshot/paramscans?strategies=trend-day¶m1=DECISION_TIME&vals1=14%3A00%3A00&vals1=14%3A15%3A00&vals1=14%3A30%3A00&pdf=true' > trend_day_afternoon_time_scan.pdf
You can scan parameter values other than just strings or numbers, including True
, False
, None
, and lists of values. You can pass the special value "default" to run an iteration that preserves the parameter value already defined on your strategy.
$ quantrocket moonshot paramscan 'dma-tech' --param1 'SLIPPAGE_BPS' --vals1 'default' 'None' '2' '5' --param2 'EXCLUDE_SIDS' --vals2 'FIBBG756733' 'FIBBG6604766' 'FIBBG756733,FIBBG6604766' --pdf -o paramscan_results.pdf
>>> from quantrocket.moonshot import scan_parameters
>>> from moonchart import ParamscanTearsheet
>>> scan_parameters("dma-tech",
param1="SLIPPAGE_BPS", vals1=["default",None,2,100],
param2="EXCLUDE_SIDS", vals2=["FIBBG756733","FIBBG6604766",["FIBBG756733","FIBBG6604766"]],
filepath_or_buffer="paramscan_results.csv")
>>> ParamscanTearsheet.from_csv("paramscan_results.csv")
$ curl -X POST 'http://houston/moonshot/paramscans.csv?strategies=dma-tech¶m1=SLIPPAGE_BPS&vals1=default&vals1=None&vals1=2&vals1=100¶m2=EXCLUDE_SIDS&vals2=FIBBG756733&vals2=FIBBG6604766&vals2=%5BFIBBG756733%2C+FIBBG6604766%5D' > paramscan_results.pdf
Parameter values are converted to strings, sent over HTTP to the moonshot service, then converted back to the appropriate types by the moonshot service using Python's built-in eval()
function.
Segmented parameter scans
As with backtests, you can run segmented parameter scans to reduce memory usage:
$ quantrocket moonshot paramscan 'big-boy' -s '2000-01-01' -e '2018-01-01' --segment 'Y' -p 'MAVG_WINDOW' -v 20 40 60 -o paramscan_result.csv
>>> from quantrocket.moonshot import scan_parameters
>>> scan_parameters("big-boy", start_date="2001-01-01", end_date="2018-01-01", segment="Y", param1="MAVG_WINDOW", vals1=[20,40,60], filepath_or_buffer="paramscan_result.csv")
$ curl -X POST 'http://houston/moonshot/paramscans.csv?strategies=big-boy&start_date=2000-01-01&end_date=2018-01-01&segment=Y¶m1=MAVG_WINDOW&vals1=20&vals1=40&vals1=60'
Learn more about segmented backtests in the section on backtesting.
Parameter scan concurrency
By default, parameter scans run in sequence: the first parameter value is backtested, then the second value, etc. If your system has adequate resources, you can speed up parameter scans by using the --num-workers
/num_workers
argument to run multiple workers in parallel. Each worker will be assigned to backtest a specific parameter value, until all the parameter values have been tested. Depending on your system resources, you should set the number of workers to an integer that is less than or equal to the total number of parameter values you're testing (3 in the following example):
$ quantrocket moonshot paramscan 'dma' -s '2000-01-01' -e '2018-01-01' -p 'MAVG_WINDOW' -v 20 40 60 --num-workers 3 -o paramscan_result.csv
>>> from quantrocket.moonshot import scan_parameters
>>> scan_parameters("dma", start_date="2001-01-01", end_date="2018-01-01", param1="MAVG_WINDOW", vals1=[20,40,60], num_workers=3, filepath_or_buffer="paramscan_result.csv")
$ curl -X POST 'http://houston/moonshot/paramscans.csv?strategies=dma&start_date=2000-01-01&end_date=2018-01-01¶m1=MAVG_WINDOW&vals1=20&vals1=40&vals1=60&num_workers=3'
The maximum number of workers you can specify is determined by the moonshot service's environment variable BACKTEST_WORKERS
, which is set to 6 by default. This variable defines the total number of workers that are created by the moonshot container for running backtests and parameter scans. To run extra workers so that you can increase the concurrency of your parameter scans, set the BACKTEST_WORKERS
environment variable to a higher number in docker-compose.override.yml
:
version: '2.4'
services:
moonshot:
environment:
BACKTEST_WORKERS: 10
Learn more about docker-compose.override.yml
.
It is possible, and often advisable, to run a parameter scan that utilizes both concurrency and
segmentation. This might seem counter-intuitive, since concurrency requires additional memory, while segmented backtesting is a way to reduce memory usage. Nevertheless, when running parameter scans on a large universe of securities, the fastest performance will often result from using
segment
to break each backtest into smaller chunks while also using
num_workers
to run multiple backtests in parallel.
Moonshot development workflow
Interactive strategy development in Jupyter
Working with DataFrames is much easier when done interactively. You can follow and validate the transformations at each step, rather than having to write lots of code and run a complete backtest only to wonder why the results don't match what you expected.
Luckily, Moonshot is a simple, fairly "raw" framework that doesn't perform lots of invisible, black-box magic, making it straightforward to step through your DataFrame transformations in a notebook and later transfer your working code to a .py
file.
To interactively develop our moving average crossover strategy, define a simple Moonshot class that points to your history database:
from moonshot import Moonshot
class DualMovingAverageStrategy(Moonshot):
DB = "usstock-1d"
UNIVERSES = "tech-giants"
To see other built-in parameters you might define besides DB
, check the Moonshot docstring by typing: Moonshot?
Instantiate the strategy and get a DataFrame of prices:
self = DualMovingAverageStrategy()
prices = self.get_prices(start_date="2016-01-01")
This is the same prices DataFrame that will be passed to your prices_to_signals
method in a backtest, so you can now interactively implement your logic to produce a DataFrame of signals from the DataFrame of prices (peeking at the intermediate DataFrames as you go):
closes = prices.loc["Close"]
lmavgs = closes.rolling(300).mean()
smavgs = closes.rolling(100).mean()
signals = smavgs.shift() > lmavgs.shift()
signals = signals.astype(int)
In a backtest your signals DataFrame will be passed to your signals_to_target_weights
method, so now work on the logic for that method. In this case it's easy:
weights = self.allocate_equal_weights(signals)
Next, transform the target weights into a positions DataFrame; this will become the logic of your strategy's target_weights_to_positions
method:
positions = weights.shift()
Finally, compute gross returns from your positions; this will become positions_to_gross_returns
:
closes = prices.loc["Close"]
gross_returns = closes.pct_change() * positions.shift()
Once you've stepped through this process and your code appears to be doing what you expect, you can create a .py
file for your strategy and copy your code into it, then run a full backtest.
Don't forget to add a CODE
attribute to your strategy class at this point to identify it (e.g. "dma-tech"). The class name of your strategy and the name of the file in which you store it don't matter; only the CODE
is used to identify the strategy throughout QuantRocket.
Save custom DataFrames to backtest results
You can add custom DataFrames to your backtest results, in addition to the DataFrames that are included by default. For example, you might save the computed moving averages:
def prices_to_signals(self, prices: pd.DataFrame):
closes = prices.loc["Close"]
mavgs = closes.rolling(50).mean()
self.save_to_results("MAvg", mavgs)
...
After running a backtest with details=True
, the resulting CSV will contain the custom DataFrame:
>>> from quantrocket.moonshot import read_moonshot_csv
>>> results = read_moonshot_csv("dma_tech_results.csv")
>>> mavgs = results.loc["MAvg"]
>>> mavgs.tail()
AAPL(FIBBG000B9XRY4) AMZN(FIBBG000BVPV84) NFLX(FIBBG000CL9VN6) GOOGL(FIBBG009S39JX6)
Date
2020-03-31 227.234433 1826.798467 334.330250 1230.522150
2020-04-01 227.533192 1827.690733 334.470550 1230.581117
2020-04-02 227.849347 1828.570400 334.615250 1230.691217
2020-04-03 228.137191 1829.357133 334.694283 1230.661850
2020-04-06 228.500019 1830.556133 334.841950 1231.006283
Custom DataFrames are only returned when running single-strategy backtests using the --details
/details=True
option.
Debugging Moonshot strategies
There are several options for debugging your strategies.
First, you can interactively develop the strategy in a notebook. This is particularly helpful in the early stages of development.
Second, if your strategy is already in a .py
file, you can save custom DataFrames to your backtest output and try to see what's going on.
Third, you can add print statements to your .py
file, which will show up in flightlog's detailed logs. Open a terminal and start streaming the logs:
$ quantrocket flightlog stream -d
Then run your backtest from a notebook or another terminal.
If you want to inspect or debug the Moonshot library itself (we hope it's so solid you never need to!), a good tactic is to find the relevant method from the base Moonshot class and copy and paste it into your own strategy:
class MyStrategy(Moonshot):
...
def backtest(self, start_date=None, end_date=None):
self.is_backtest = True
...
This will override the corresponding method on the base Moonshot class, so you can now add print statements to your copy of the method and they'll show up in flightlog.
Code reuse for strategy variants
Often, you may want to re-use a strategy's logic while changing some of the parameters. For example, perhaps you'd like to run an existing strategy on a different market. To do so, simply subclass your existing strategy and modify the parameters as needed. Let's try our dual moving average strategy on a group of ETFs. First, define a universe of the ETFs:
$ quantrocket master get -e 'ARCX' -s 'SPY' 'XLF' 'EEM' 'VNQ' 'XOP' 'GDX' | quantrocket master universe 'etf-sampler' -f -
code: etf-sampler
inserted: 6
provided: 6
total_after_insert: 6
Since we're inheriting from an existing strategy, implementing our strategy is easy, simply adjust the parameters to point to the new universe:
class DualMovingAverageStrategyETF(DualMovingAverageStrategy):
CODE = "dma-etf"
DB = "usstock-1d"
UNIVERSES = "etf-sampler"
LMAVG_WINDOW = 300
SMAVG_WINDOW = 100
Now we can run our backtest:
$ quantrocket moonshot backtest 'dma-etf' -s '2005-01-01' -e '2017-01-01' --pdf -o dma_etf_tearsheet.pdf --details
>>> from quantrocket.moonshot import backtest
>>> backtest("dma-etf", start_date="2005-01-01", end_date="2017-01-01",
filepath_or_buffer="dma_etf.csv", details=True)
$ curl -X POST 'http://houston/moonshot/backtests?strategies=dma-etf&start_date=2005-01-01&end_date=2017-01-01&pdf=true' > dma_etf_tearsheet.pdf
Code organization
Your Moonshot code should be placed in the /codeload/moonshot
subdirectory inside JupyterLab. QuantRocket recursively scans .py
files in this directory and loads your strategies (a strategy is defined as a subclass of moonshot.Moonshot
). You can place as many strategies as you like within a single .py
file, or you can place them in separate files. If you like, you can organize your .py
files into subdirectories as you see fit.
If you want to re-use code across multiple files, you can do so using standard Python import syntax. Any .py
files in or under the /codeload
directory inside Jupyter (that is, any .py
files you can see in the Jupyter file browser) can be imported from codeload
. For example, consider a simple directory structure containing two files for your strategies and one file with helper functions used by multiple strategies:
/codeload/moonshot/helpers.py
/codeload/moonshot/meanreversion_strategies.py
/codeload/moonshot/momentum_strategies.py
Suppose you've implemented a function in helpers.py
called rebalance_positions
. You can import and use the function in another file like so:
from codeload.moonshot.helpers import rebalance_positions
Importing also works if you're using subdirectories:
/codeload/moonshot/helpers/rebalance.py
/codeload/moonshot/meanreversion/buythedip.py
/codeload/moonshot/momentum/hml.py
Just use standard Python dot syntax to reach your modules wherever they are in the directory tree:
from codeload.moonshot.helpers.rebalance import rebalance_positions
To make your code importable as a standard Python package, the 'codeload' directory and each subdirectory must contain a __init__.py
file. QuantRocket will create these files automatically if they don't exist.
Interactive order creation in Jupyter
This section might make more sense after reading about
live trading.
Just as you can interactively develop your Moonshot backtest code in Jupyter, you can use a similar approach to develop your order_stubs_to_orders
method.
First, import and instantiate your strategy:
from codeload.moonshot.dual_moving_average import DualMovingAverageTechGiantsStrategy
self = DualMovingAverageTechGiantsStrategy()
Next, run the trade method, which returns a DataFrame of orders. You'll need to pass at least one account allocation (normally this would be pulled from quantrocket.moonshot.allocations.yml
).
allocations = {"DU12345": 1.0}
orders = self.trade(allocations)
The account must be a valid account as Moonshot will try to pull the account balance from the account service. You can run quantrocket account balance --latest
to make sure account history is available for the account.
If
self.trade()
returns no orders, you can pass a
review_date
to
generate orders for an earlier date, and/or modify
prices_to_signals
to create some trades for the purpose of testing.
If your strategy hasn't overridden order_stubs_to_orders
, you'll receive the orders DataFrame as processed by the default implementation of order_stubs_to_orders
on the Moonshot base class. (Note that the trade
method returns None
if your strategy produces no orders.) You can return the orders DataFrame to the state in which it was passed to order_stubs_to_orders
by dropping a few columns:
orders = orders.drop(["OrderType", "Tif"], axis=1)
You can now experiment with modifying your orders DataFrame. For example, re-add the required fields:
orders["OrderType"] = "MKT"
orders["Tif"] = "DAY"
orders["Exchange"] = "SMART"
Or attach exit orders:
child_orders = self.orders_to_child_orders(orders)
child_orders.loc[:, "OrderType"] = "MOC"
orders = pd.concat([orders, child_orders])
To use the prices DataFrame for order creation (for example, to set limit prices), query recent historical prices. (To learn more about the historical data start date used in live trading, see the section on lookback windows.)
prices = self.get_prices("2018-04-01")
Now create limit prices set to the prior close:
closes = prices.loc["Close"]
prior_closes = closes.shift()
prior_closes = self.reindex_like_orders(prior_closes, orders)
orders["OrderType"] = "LMT"
orders["LmtPrice"] = prior_closes
Intraday strategies
When your strategy points to an intraday history database, the strategy receives a DataFrame of intraday prices, that is, a DataFrame containing the time in the index, not just the date.
Moonshot supports two different conventions for intraday strategies, depending on how frequently the strategy trades.
Trade frequency | Example strategy |
---|
throughout the day | using 1 minute bars, enter long (short) position whenever price moves above (below) its N-period moving average |
once per day | if intraday return is greater than X% as of 2:00 PM, enter long position at 2:15 PM and close position at 4:00 PM |
Throughout-the-day strategies
Intraday strategies that trade throughout the day are very similar to end-of-day strategies, the only difference being that the prices DataFrame and the derived DataFrames (signals, target weights, etc.) have a "Time" level in the index. (See the structure of intraday prices.)
Given the similarity with end-of-day strategies, we can demonstrate an intraday strategy by using the end-of-day dual moving average strategy from an earlier example. We can create a subclass of the end-of-day strategy which points to the intraday database or bundle:
class DualMovingAverageIntradayStrategy(DualMovingAverageStrategy):
CODE = "dma-tech-intraday"
DB = "usstock-1min"
LMAVG_WINDOW = 300
SMAVG_WINDOW = 100
LOOKBACK_WINDOW = 1
Now we can run the backtest and view the performance:
$ quantrocket moonshot backtest 'dma-tech-intraday' --start-date '2016-06-01' --end-date '2016-12-31' --pdf -o dma_tech_intraday.pdf --details
>>> from quantrocket.moonshot import backtest
>>> from moonchart import Tearsheet
>>> backtest("dma-tech-intraday", start_date="2016-06-01", end_date="2016-12-31", details=True, filepath_or_buffer="dma_tech_intraday.csv")
>>> Tearsheet.from_moonshot_csv("dma_tech_intraday.csv")
$ curl -X POST 'http://houston/moonshot/backtests.pdf?strategies=dma-tech-intraday&start_date=2016-06-01&end_date=2016-12-31&pdf=true' -o dma_tech_intraday.pdf
If you load the backtest results CSV into a DataFrame, it has the same fields as an end-of-day CSV, but the index includes a "Time" level:
>>> from quantrocket.moonshot import read_moonshot_csv
>>> results = read_moonshot_csv("dma_tech_intraday.csv")
>>> results.tail()
AAPL(FIBBG000B9XRY4) AMZN(FIBBG000BVPV84) GOOGL(FIBBG009S39JX6) NFLX(FIBBG000CL9VN6)
Field Date Time
Weight 2016-12-29 15:45:00 0.000000 0.000000 0.0 1.000000
15:46:00 0.500000 0.000000 0.0 0.500000
15:47:00 0.500000 0.000000 0.0 0.500000
15:48:00 0.333333 0.333333 0.0 0.333333
15:49:00 0.333333 0.333333 0.0 0.333333
When you create a Moonchart or pyfolio tear sheet from an intraday Moonshot CSV, the respective libraries first aggregate the intraday results DataFrame to a daily results DataFrame, then plot the daily results.
Once-a-day strategies
Some intraday strategies only trade at most once per day, at a particular time of day. These strategies can be thought of as "seasonal": that is, instead of treating the intraday prices as a continuous series, the time of day is highly relevant to the trading logic. Once-a-day strategies need to select relevant times of day from the intraday prices DataFrame and perform calculations with those slices of data, rather than using the entirety of intraday prices.
For these once-a-day intraday strategies, the recommended convention is to "reduce" the DataFrame of intraday prices to a DataFrame of daily signals in prices_to_signals
. Since there can only be one signal per day, the signals DataFrame need not have the time in the index. An example will illustrate.
Consider a simple "trend day" strategy using several ETFs: if the ETF is up (down) more than 2% from yesterday's close as of 2:00 PM, buy (sell) the ETF and exit the position at the market close.
Define a Moonshot strategy and point it to an intraday database or bundle:
class TrendDayStrategy(Moonshot):
CODE = 'trend-day'
DB = 'usstock-1min'
DB_TIMES = ['14:00:00', '15:59:00']
DB_FIELDS = ['Open','Close']
UNIVERSES = 'etf-sampler'
Note the use of
DB_TIMES
and
DB_FIELDS
to limit the amount of data loaded into the backtest.
Loading only the data you need is an important performance optimization for intraday strategies with large universes (albeit less important in this particular example since the universe is small).
Working with intraday prices in Moonshot is identical to working with intraday prices in historical research. We use .xs
to select particular times of day from the prices DataFrame, thereby reducing the DataFrame from intraday to daily. In this way our prices_to_signals
method calculates the return from yesterday's close to 2:00 PM and uses it to make trading decisions:
def prices_to_signals(self, prices: pd.DataFrame):
closes = prices.loc["Close"]
opens = prices.loc["Open"]
session_closes = closes.xs("15:59:00", level="Time")
afternoon_prices = opens.xs("14:00:00", level="Time")
prior_closes = session_closes.shift()
returns = (afternoon_prices - prior_closes) / prior_closes
long_signals = returns > 0.02
short_signals = returns < -0.02
signals = long_signals.astype(int).where(long_signals, -short_signals.astype(int))
return signals
If you step through this code interactively, you'll see that after the use of .xs
to select particular times of day from the prices DataFrame, all subsequent DataFrames have dates in the index but not times, just like with an end-of-day strategy.
Because our prices_to_signals
method has reduced intraday prices to daily signals, our signals_to_target_weights
and target_weights_to_positions
methods don't need to do any special "intraday handling" and therefore look similar to how they might look for a daily strategy:
def signals_to_target_weights(self, signals: pd.DataFrame, prices: pd.DataFrame):
target_weights = self.allocate_fixed_weights_capped(signals, 0.20, cap=1.0)
return target_weights
def target_weights_to_positions(self, target_weights: pd.DataFrame, prices: pd.DataFrame):
positions = target_weights.copy()
return positions
To calculate gross returns, we select the intraday prices that correspond to our entry and exit times and multiply the security's return by our position size:
def positions_to_gross_returns(self, positions: pd.DataFrame, prices: pd.DataFrame):
closes = prices.loc["Close"]
entry_prices = closes.xs("14:00:00", level="Time")
session_closes = closes.xs("15:59:00", level="Time")
pct_changes = (session_closes - entry_prices) / entry_prices
gross_returns = pct_changes * positions
return gross_returns
Now we can run the backtest and view the performance:
$ quantrocket moonshot backtest 'trend-day' --pdf -o trend_day.pdf --details
>>> from quantrocket.moonshot import backtest
>>> from moonchart import Tearsheet
>>> backtest("trend-day", details=True, filepath_or_buffer="trend_day.csv")
>>> Tearsheet.from_moonshot_csv("trend_day.csv")
$ curl -X POST 'http://houston/moonshot/backtests.pdf?strategies=trend-day&pdf=true' -o trend_day.pdf
Lookback windows in intraday strategies
It is usually a good idea to specify an explicit LOOKBACK_WINDOW
for intraday strategies. Moonshot measures and calculates lookback windows in days. This can inadvertently lead to loading too much data in intraday strategies. Consider the following intraday strategy using a 1-minute database:
class DualMovingAverageIntradayStrategy(DualMovingAverageStrategy):
CODE = "dma-tech-intraday"
DB = "usstock-1min"
LMAVG_WINDOW = 300
SMAVG_WINDOW = 100
Based on the LMAVG_WINDOW
parameter, Moonshot will load a 300-day lookback window. But this is too much data. Since we are using 1-minute bars, the moving average windows represent minutes, not days, so we only need a 300-minute lookback window. The solution is to set the LOOKBACK_WINDOW
explicitly to a small number like 1 or 0:
class DualMovingAverageIntradayStrategy(DualMovingAverageStrategy):
CODE = "dma-tech-intraday"
DB = "usstock-1min"
LMAVG_WINDOW = 300
SMAVG_WINDOW = 100
LOOKBACK_WINDOW = 1
Commissions and slippage
Commissions
Moonshot supports realistic modeling of commissions. To model commissions, subclass the appropriate commission class, set the commission costs as per your broker's website, then add the commission class to your strategy:
from moonshot import Moonshot
from moonshot.commission import PercentageCommission
class JapanStockFixedCommission(PercentageCommission):
BROKER_COMMISSION_RATE = 0.0008
MIN_COMMISSION = 80.00
class MyJapanStrategy(Moonshot):
COMMISSION_CLASS = JapanStockFixedCommission
Because commission costs change from time to time, and because some cost components depend on account specifics such as your monthly trade volume or the degree to which you add or remove liquidity, Moonshot provides the commission logic but expects you to fill in the specific cost constants.
Percentage commissions
Use moonshot.commission.PercentageCommission
where the broker's commission is calculated as a percentage of the trade value. If your broker uses a tiered commission structure, you can also set an exchange fee (as a percentage of trade value). A variety of examples are shown below:
from moonshot.commission import PercentageCommission
class MexicoStockCommission(PercentageCommission):
BROKER_COMMISSION_RATE = 0.0010
MIN_COMMISSION = 60.00
class SingaporeStockTieredCommission(PercentageCommission):
BROKER_COMMISSION_RATE = 0.0008
EXCHANGE_FEE_RATE = 0.00034775 + 0.00008025
MIN_COMMISSION = 2.50
class UKStockTieredCommission(PercentageCommission):
BROKER_COMMISSION_RATE = 0.0008
EXCHANGE_FEE_RATE = 0.000045 + 0.0025
MIN_COMMISSION = 1.00
class HongKongStockTieredCommission(PercentageCommission):
BROKER_COMMISSION_RATE = 0.0008
EXCHANGE_FEE_RATE = (
0.00005
+ 0.00002
+ 0.001
+ 0.000027
)
MIN_COMMISSION = 18.00
class JapanStockTieredCommission(PercentageCommission):
BROKER_COMMISSION_RATE = 0.0005
EXCHANGE_FEE_RATE = 0.00002 + 0.000004
MIN_COMMISSION = 80.00
Per Share commissions
Use moonshot.commission.PerShareCommission
to model commissions which are assessed per share. Here is an example of a fixed commission for US stocks:
from moonshot.commission import PerShareCommission
class USStockFixedCommission(PerShareCommission):
BROKER_COMMISSION_PER_SHARE = 0.005
MIN_COMMISSION = 1.00
Some commission structures can be complex; in addition to the broker commission, the commission may include exchange fees which are assessed per share (and which may differ depending on whether you add or remove liqudity), fees which are based on the trade value, and fees which are assessed as a percentage of the broker comission itself. These can also be modeled:
class CostPlusUSStockCommission(PerShareCommission):
BROKER_COMMISSION_PER_SHARE = 0.0035
EXCHANGE_FEE_PER_SHARE = (0.0002
+ (0.000119/2))
MAKER_FEE_PER_SHARE = -0.002
TAKER_FEE_PER_SHARE = 0.00118
MAKER_RATIO = 0.25
COMMISSION_PERCENTAGE_FEE_RATE = (0.000175
+ 0.00056)
PERCENTAGE_FEE_RATE = 0.0000231
MIN_COMMISSION = 0.35
class CanadaStockCommission(PerShareCommission):
BROKER_COMMISSION_PER_SHARE = 0.008
EXCHANGE_FEE_PER_SHARE = (
0.00017
+ 0.00011
)
MAKER_FEE_PER_SHARE = -0.0019
TAKER_FEE_PER_SHARE = 0.003
MAKER_RATIO = 0
MIN_COMMISSION = 1.00
Futures commissions
moonshot.commission.FuturesCommission
lets you define a commission, exchange fee, and carrying fee per contract:
from moonshot.commission import FuturesCommission
class CMEEquityEMiniFixedCommission(FuturesCommission):
BROKER_COMMISSION_PER_CONTRACT = 0.85
EXCHANGE_FEE_PER_CONTRACT = 1.18
CARRYING_FEE_PER_CONTRACT = 0
FX commissions
Spot FX commissions are percentage-based, so moonshot.commission.SpotFXCommission
can be used directly without subclassing:
from moonshot import Moonshot
from moonshot.commission import SpotFXCommission
class MyFXStrategy(Moonshot):
COMMISSION_CLASS = SpotFXCommission
Note that at present, SpotFXCommission
does not model minimum commissions (this has to do with the fact that the minimum commission for FX for currently supported brokers is always expressed in USD, rather than the currency of the traded security). This limitation means that if your trades are small, SpotFXCommission
may underestimate the commission.
Minimum commissions
During backtests, Moonshot calculates and assesses commissions in percentage terms (relative to the capital allocated to the strategy) rather than in dollar terms. However, since minimum commissions are expressed in dollar terms, Moonshot must know your NLV (Net Liquidation Value, i.e. account balance) in order to accurately model minimum commissions in backtests. You can specify your NLV in your strategy definition or at the time you run a backtest.
If you trade in size and are unlikely ever to trigger minimum commissions, you don't need to model them.
NLV should be provided as key-value pairs of CURRENCY:NLV
. You must provide the NLV in each currency you wish to model. For example, if your account balance is $100K USD, and your strategy trades instruments denominated in JPY and AUD, you could specify this on the strategy:
class MyAsiaStrategy(Moonshot):
CODE = "my-asia-strategy"
NLV = {
"JPY": 100000 * 110,
"AUD": 100000 * 1.25
}
Or pass the NLV at the time you run the backtest:
$ quantrocket moonshot backtest 'my-asia-strategy' --nlv 'JPY:11000000' 'AUD:125000' -o asia.csv
>>> backtest("my-asia-strategy", nlv={"JPY":11000000, "AUD":125000},
filepath_or_buffer="asia.csv")
$ curl -X POST 'http://houston/moonshot/backtests.csv?strategies=my-asia-strategy&nlv=JPY%3A11000000&nlv=AUD%3A125000' > asia.csv
If you don't specify NLV on the strategy or via the nlv
option, the backtest will still run, it just won't take into account minimum commissions.
Multiple commission structures on the same strategy
You might run a strategy that trades multiple securities with different commission structures. Instead of specifying a single commission class, you can specify a Python dictionary associating each commission class with the respective security type, exchange, and currency it applies to:
class USStockFixedCommission(PerShareCommission):
BROKER_COMMISSION_PER_SHARE = 0.005
MIN_COMMISSION = 1.00
class CMEEquityEMiniFixedCommission(FuturesCommission):
BROKER_COMMISSION_PER_CONTRACT = 0.85
EXCHANGE_FEE_PER_CONTRACT = 1.18
class MultiSecTypeStrategy(Moonshot):
COMMISSION_CLASS = {
("STK", "XNYS", "USD"): USStockFixedCommission,
("STK", "XNAS", "USD"): USStockFixedCommission,
("FUT", "XCME", "USD"): CMEEquityEMiniFixedCommission
}
Slippage
Fixed slippage
You can apply a fixed amount of slippage (in basis points) to the trades in your backtest by setting SLIPPAGE_BPS
on your strategy:
class MyStrategy(Moonshot):
...
SLIPPAGE_BPS = 5
The above will apply 5 basis point of one-way slippage to each trade. If you expect different slippage for entry vs exit, take the average.
Parameter scans are a handy way to check your strategy's sensitivity to slippage:
$ quantrocket moonshot paramscan 'my-strategy' -p 'SLIPPAGE_BPS' -v 0 2.5 5 10 --pdf -o my_strategy_slippage.pdf
>>> from quantrocket.moonshot import scan_parameters
>>> scan_parameters("my-strategy",
param1="SLIPPAGE_BPS", vals1=[0,2.5,5,10],
filepath_or_buffer="my_strategy_slippage.csv")
$ curl -X POST 'http://houston/moonshot/paramscans.pdf?strategies=my-strategy¶m1=SLIPPAGE_BPS&vals1=0&vals1=2.5&vals1=5&vals1=10' > my_strategy_slippage.pdf
You can research bid-ask spreads for the purpose of estimating slippage by collecting intraday historical data from Interactive Brokers using the BID
, ASK
, or BID_ASK
bar types.
Commissions and slippage for intraday positions
If you run an intraday strategy that closes its positions the same day it opens them, you should set a parameter (POSITIONS_CLOSED_DAILY
, see below) to tell Moonshot you're doing this so that it can more accurately assess commissions and slippage. Here's why:
Moonshot calculates commissions and slippage by first diff()
ing the positions DataFrame in your backtest to calculate the day-to-day turnover. For example, suppose we entered a position in AAPL, then reduced the position the next day, then maintained the position for a day, then closed the position. Our holdings look like this:
>>> positions.head()
AAPL(FIBBG000B9XRY4)
Date
2012-01-06 0.000
2012-01-06 0.500
2012-01-09 0.333
2012-01-12 0.333
2012-01-12 0.000
The corresponding DataFrame of trades, representing our turnover due to opening and closing the position, would look like this:
>>> trades = positions.diff()
>>> trades.head()
AAPL(FIBBG000B9XRY4)
Date
2012-01-06 NaN
2012-01-06 0.500
2012-01-09 -0.167
2012-01-12 0.000
2012-01-12 -0.333
Commissions and slippage are applied against this DataFrame of trades.
The default use of diff()
to calculate trades from positions involves an assumption: that adjacent, same-side positions in the positions DataFrame represent continuous holdings. For strategies that close out their positions each day, this assumption isn't correct. For example, the positions DataFrame from above might actually indicate 3 positions opened and closed on 3 consecutive days, rather than 1 continuously held position:
>>> positions.head()
AAPL(FIBBG000B9XRY4)
Date
2012-01-06 0.000
2012-01-06 0.500
2012-01-09 0.333
2012-01-12 0.333
2012-01-12 0.000
If so, diff()
will underestimate turnover and thus underestimate commissions and slippage. The correct calculation of turnover is to multiply the positions by 2:
>>> trades = positions * 2
>>> trades.head()
AAPL(FIBBG000B9XRY4)
Date
2012-01-06 0.000
2012-01-06 1.000
2012-01-09 0.667
2012-01-12 0.667
2012-01-12 0.000
As there is no reliable way for Moonshot to infer automatically whether adjacent, same-side positions are continuously held or closed out daily, you must set POSITIONS_CLOSED_DAILY = True
on the strategy if you want Moonshot to assume they are closed out daily:
class TrendDay(Moonshot):
...
POSITIONS_CLOSED_DAILY = True
Otherwise, Moonshot will assume that adjacent, same-side positions are continuously held.
Position size constraints
Liquidity constraints
Instead of or in addition to limiting position sizes as described below, also consider using
VWAP or other algorithmic orders to trade in size if you have a large account and/or wish to trade illiquid securities. VWAP orders can be modeled in backtests as well as used in live trading.
A backtest that assumes it is possible to buy or sell any security you want in any size you want is likely to be unrealistic. In the real world, a security's liquidity constrains the number of shares it is practical to buy or sell.
Maximum position sizes for long and short positions can be defined in your strategy's limit_position_sizes
method. If defined, this method should return two DataFrames, one defining the maximum quantities (i.e. shares or contracts) allowed for longs and a second defining the maximum quantities allowed for shorts. The following example limits quantities to 1% of 15-day average daily volume:
def limit_position_sizes(self, prices: pd.DataFrame):
volumes = prices.loc["Volume"]
mean_volumes = volumes.rolling(15).mean()
max_shares = (mean_volumes * 0.01).round()
max_quantities_for_longs = max_quantities_for_shorts = max_shares.shift()
return max_quantities_for_longs, max_quantities_for_shorts
The returned DataFrames might resemble the following:
>>> max_quantities_for_longs.head()
Sid FI1234 FI2345
Date
2018-05-18 100 200
2018-05-19 100 200
>>> max_quantities_for_shorts.head()
Sid FI1234 FI2345
Date
2018-05-18 100 200
2018-05-19 100 200
In the above example, our strategy will be allowed to long or short at most 100 shares of Sid FI1234 and 200 shares of Sid FI2345.
Note that max_quantities_for_shorts
can equivalently be represented with positive or negative numbers. Values of 100 and -100 are both interpreted to mean: short no more than 100 shares. (The same applies to max_quantities_for_longs
— only the absolute value matters).
The shape and alignment of the returned DataFrames should match that of the target_weights
returned by signals_to_target_weights
. Target weights will be reduced, if necessary, so as not to exceed max_quantities_for_longs
and max_quantities_for_shorts
. Position size limits are applied in backtesting and in live trading.
You can return None
for one or both DataFrames to indicate "no limits" (this is the default implementation in the Moonshot base class). For example to limit shorts but not longs:
def limit_position_sizes(self, prices: pd.DataFrame):
...
return None, max_quantities_for_shorts
Within a DataFrame, any None
or NaN
will be treated as "no limit" for that particular security and date.
If you define position size limits for longs or shorts or both, you must specify the NLV to use for the backtest. This is because the target_weights
returned by signals_to_target_weights
are expressed as percentages of capital, and NLV is required for Moonshot to convert the percentage weights to the corresponding number of shares/contracts so that the position size limits can be enforced. NLV should be provided as key-value pairs of CURRENCY:NLV
, and should be provided for each currency represented in the strategy. For example, if your account balance is $100K USD, and your strategy trades instruments denominated in JPY and USD, you could specify NLV on the strategy:
class MyStrategy(Moonshot):
CODE = "my-strategy"
NLV = {
"USD": 100000,
"JPY": 100000 * 110,
}
Or pass the NLV at the time you run the backtest:
$ quantrocket moonshot backtest 'my-strategy' --nlv 'JPY:11000000' 'USD:100000' -o backtest_results.csv
>>> backtest("my-strategy", nlv={"JPY":11000000, "USD":100000},
filepath_or_buffer="backtest_results.csv")
$ curl -X POST 'http://houston/moonshot/backtests.csv?strategies=my-strategy&nlv=JPY%3A11000000&nlv=USD%3A100000' > backtest_results.csv
Fixed order quantities
Moonshot expects you to define your target weights as a percentage of capital. Moonshot then converts these percentage weights to the corresponding quantities of shares or contracts at the time of live trading.
For some trading strategies, you may wish to set the exact order quantities yourself, rather than using percentage weights. To accomplish this, set your weights very high (in absolute terms) in signals_to_target_weights
, then use limit_position_sizes
to reduce these percentage weights to the exact desired quantity of shares or contracts. See the examples above for the expected conventions to use in limit_position_sizes
.
Short sale constraints
You can model short sale constraints in your backtests with short sale availability data from your broker.
Interactive Brokers shortable shares
One way to use shortable shares data from Interactive Brokers is to enforce position limits based on share availability:
def limit_position_sizes(self, prices: pd.DataFrame):
max_shares_for_shorts = get_ibkr_shortable_shares_reindexed_like(prices.loc["Close"])
return None, max_shares_for_shorts
Shortable shares data is available back to April 16, 2018. Prior to that date, get_ibkr_shortable_shares_reindexed_like
will return NaNs, which are interpreted by Moonshot as "no limit on position size".
Due to the limited historical depth of shortable shares data, a useful approach is to develop your strategy without modeling short sale constraints, then run a parameter scan starting at April 16, 2018 to compare the performance with and without short sale constraints. Add a parameter to make your short sale constraint code conditional:
class ShortSaleStrategy(Moonshot):
CODE = "shortseller"
CONSTRAIN_SHORTABLE = False
...
def limit_position_sizes(self, prices: pd.DataFrame):
if self.CONSTRAIN_SHORTABLE:
max_shares_for_shorts = get_ibkr_shortable_shares_reindexed_like(prices.loc["Close"])
else:
max_shares_for_shorts = None
return None, max_shares_for_shorts
Then run the parameter scan:
$ quantrocket moonshot paramscan 'shortseller' -p 'CONSTRAIN_SHORTABLE' -v True False -s '2018-04-16' --nlv 'USD:1000000' --pdf -o shortseller_CONSTRAIN_SHORTABLE.pdf
>>> from quantrocket.moonshot import scan_parameters
>>> from moonchart import ParamscanTearsheet
>>> scan_parameters("shortseller", start_date="2018-04-16",
param1="CONSTRAIN_SHORTABLE", vals1=[True,False],
nlv={"USD":1000000},
filepath_or_buffer="shortseller_CONSTRAIN_SHORTABLE.csv")
>>> ParamscanTearsheet.from_csv("shortseller_CONSTRAIN_SHORTABLE.csv")
$ curl -X POST 'http://houston/moonshot/paramscans?strategies=shortseller&start_date=2018-04-16¶m1=CONSTRAIN_SHORTABLE&vals1=True&vals1=False&pdf=true&nlv=USD%3A1000000' > shortseller_CONSTRAIN_SHORTABLE.pdf
Interactive Brokers borrow fees
You can use a built-in slippage class to assess Interactive Brokers borrow fees on your strategy's overnight short positions. (Note that IBKR does not assess borrow fees on intraday positions.)
from moonshot import Moonshot
from moonshot.slippage import IBKRBorrowFees
class ShortSaleStrategy(Moonshot):
CODE = "shortseller"
SLIPPAGE_CLASSES = IBKRBorrowFees
...
The IBKRBorrowFees
slippage class uses get_ibkr_borrow_fees_reindexed_like
to query annualized borrow fees, converts them to a daily rate, and applies the daily rate to your short positions in backtesting. No fees are applied prior to the data's start date of April 16, 2018.
To run a parameter scan with and without borrow fees, add the IBKRBorrowFees
slippage as shown above and run a scan on the SLIPPAGE_CLASSES
parameter with values of "default" (to test the strategy as-is, that is, with borrow fees) and "None":
$ quantrocket moonshot paramscan 'shortseller' -p 'SLIPPAGE_CLASSES' -v 'default' 'None' -s '2018-04-16' --nlv 'USD:1000000' --pdf -o shortseller_with_and_without_borrow_fees.pdf
>>> from quantrocket.moonshot import scan_parameters
>>> from moonchart import ParamscanTearsheet
>>> scan_parameters("shortseller", start_date="2018-04-16",
param1="SLIPPAGE_CLASSES", vals1=["default",None],
nlv={"USD":1000000},
filepath_or_buffer="shortseller_with_borrow_fees.csv")
>>> ParamscanTearsheet.from_csv("shortseller_with_and_without_borrow_fees.csv")
$ curl -X POST 'http://houston/moonshot/paramscans?strategies=shortseller&start_date=2018-04-16¶m1=SLIPPAGE_CLASSES&vals1=default&vals1=None&pdf=true&nlv=USD%3A1000000' > shortseller_with_and_without_borrow_fees.pdf
Alpaca easy-to-borrow
Alpaca easy-to-borrow data can be used to model short sale constraints in a similar way to the Interactive Brokers shortable shares example above, but the example must be adapted since the Alpaca data provides boolean values rather than the number of available shares:
def limit_position_sizes(self, prices: pd.DataFrame):
closes = prices.loc["Close"]
are_etb = get_alpaca_etb_reindexed_like(closes)
max_shares_for_shorts = pd.DataFrame(np.nan, index=closes.index, columns=closes.columns)
max_shares_for_shorts = max_shares_for_shorts.where(are_etb, 0)
return None, max_shares_for_shorts
Live trading
Live trading quickstart
Live trading with Moonshot can be thought of as running a backtest on up-to-date historical data and placing a batch of orders based on the latest signals generated by the backtest.
Recall the moving average crossover strategy from the backtesting quickstart:
import pandas as pd
from moonshot import Moonshot
class DualMovingAverageStrategy(Moonshot):
CODE = "dma-tech"
DB = "usstock-1d"
UNIVERSES = "tech-giants"
LMAVG_WINDOW = 300
SMAVG_WINDOW = 100
def prices_to_signals(self, prices: pd.DataFrame):
closes = prices.loc["Close"]
lmavgs = closes.rolling(self.LMAVG_WINDOW).mean()
smavgs = closes.rolling(self.SMAVG_WINDOW).mean()
signals = smavgs.shift() > lmavgs.shift()
return signals.astype(int)
To trade the strategy, the first step is to define one or more accounts (live or paper) in which you want to run the strategy, and how much of each account's capital to allocate. Accounts allocations should be defined in quantrocket.moonshot.allocations.yml
, located in the /codeload
directory (that is, in the top-level directory of the Jupyter file browser). Allocations should be expressed as a decimal percent of the total capital (Net Liquidation Value) of the account:
DU12345:
dma-tech: 0.75
Next, bring your history database up-to-date if you haven't already done so:
$ quantrocket history collect 'usstock-1d'
status: the historical data will be collected asynchronously
>>> from quantrocket.history import collect_history
>>> collect_history("usstock-1d")
{'status': 'the historical data will be collected asynchronously'}
$ curl -X POST 'http://houston/history/queue?codes=usstock-1d'
{"status": "the historical data will be collected asynchronously"}
Now you're ready to run the strategy. Running the strategy doesn't place any orders but generates a CSV of orders to be placed in a subsequent step:
$ quantrocket moonshot trade 'dma-tech' -o orders.csv
>>> from quantrocket.moonshot import trade
>>> trade("dma-tech", filepath_or_buffer="orders.csv")
$ curl -X POST 'http://houston/moonshot/orders.csv?strategies=dma-tech' > orders.csv
If any orders were generated, the CSV will look something like this:
$ csvlook -I orders.csv
| Sid | Account | Action | OrderRef | TotalQuantity | Exchange | OrderType | Tif |
| -------------- | ------- | ------ | -------- | ------------- | -------- | --------- | --- |
| FIBBG000B9XRY4 | DU12345 | BUY | dma-tech | 501 | SMART | MKT | DAY |
| FIBBG000BVPV84 | DU12345 | BUY | dma-tech | 58 | SMART | MKT | DAY |
| FIBBG000CL9VN6 | DU12345 | BUY | dma-tech | 284 | SMART | MKT | DAY |
| FIBBG00LBLDHJ2 | DU12345 | BUY | dma-tech | 86 | SMART | MKT | DAY |
If no orders were generated, there won't be a CSV. If this happens, you can re-run the strategy with the
--review-date
option to
generate orders for an earlier date, and/or modify
prices_to_signals
to create some trades for the purpose of testing.
Finally, place the orders with QuantRocket's blotter:
$ quantrocket blotter order -f orders.csv
>>> from quantrocket.blotter import place_orders
>>> place_orders(infilepath_or_buffer="orders.csv")
$ curl -X POST 'http://houston/blotter/orders' --upload-file orders.csv
Normally, you will run your live trading in an automated manner from the countdown service using the command line interface (CLI). With the CLI, you can generate and place Moonshot orders in a one-liner by piping the orders CSV to the blotter over stdin (indicated by passing -
as the -f/--infile
option):
$ quantrocket moonshot trade 'dma-tech' | quantrocket blotter order -f '-'
How live trading works
Live trading in Moonshot starts out just like a backtest:
- Prices are queried from your history database
- The prices DataFrame is passed to your
prices_to_signals
method, which returns a DataFrame of signals - The signals DataFrame is passed to
signals_to_target_weights
, which returns a DataFrame of target weights
At this point, a backtest would proceed to simulate positions (target_weights_to_positions
) then simulate returns (positions_to_gross_returns
). In contrast, in live trading the target weights must be converted into a batch of live orders to be placed with the broker. This process happens as follows:
- First, Moonshot isolates the last row (corresponding to today) from the target weights DataFrame.
- Moonshot converts the target weights into the actual number of shares of each security to be ordered in each allocated account, taking into account the overall strategy allocation, the account balance, and any existing positions the strategy already holds.
- Moonshot provides you with a DataFrame of "order stubs" containing basic fields such as the account, action (buy or sell), order quantity, and security ID (Sid).
- You can then customize the orders in the
order_stubs_to_orders
method by adding other order fields such as the order type, time in force, etc.
By default, the base class implementation of order_stubs_to_orders
creates MKT DAY orders. The above quickstart example relies on this default behavior, but you should always override order_stubs_to_orders
with your own order specifications.
From order stubs to orders
You can specify detailed order parameters in your strategy's order_stubs_to_orders
method.
The order stubs DataFrame provided to this method resembles the following:
>>> print(orders)
Sid Account Action OrderRef TotalQuantity
0 FI12345 U12345 SELL my-strategy 100
1 FI12345 U55555 SELL my-strategy 50
2 FI23456 U12345 BUY my-strategy 100
3 FI23456 U55555 BUY my-strategy 50
4 FI34567 U12345 BUY my-strategy 200
5 FI34567 U55555 BUY my-strategy 100
Modify the DataFrame by appending additional columns. At minimum, you must provide the order type (OrderType
) and time in force (Tif
). For Interactive Brokers accounts, you must also specify an exchange to route the order to. An example is shown below:
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
orders["Exchange"] = "SMART"
orders["OrderType"] = "MKT"
orders["Tif"] = "DAY"
return orders
Moonshot isn't limited to a handful of canned order types. You can use most of the order parameters and order types supported by your broker. Learn more about required and available order fields in the blotter documentation.
As shown in the above example, Moonshot uses your strategy code (e.g. "my-strategy") to populate the
OrderRef
field, a field
used by the blotter for strategy-level tracking of your positions and performance.
Using prices and securities master fields in order creation
The prices DataFrame used throughout Moonshot is passed to order_stubs_to_orders
, allowing you to use prices or securities master fields to create your orders. This is useful, for example, for setting limit prices, or applying different order rules for different exchanges.
The prices DataFrame covers multiple dates while the orders DataFrame represents a current snapshot. You can use the reindex_like_orders
method to extract a current snapshot of data from the prices DataFrame. For example, create limit prices set to the prior close:
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
closes = prices.loc["Close"]
prior_closes = closes.shift()
prior_closes = self.reindex_like_orders(prior_closes, orders)
orders["OrderType"] = "LMT"
orders["LmtPrice"] = prior_closes
...
Or, direct-route orders to their primary exchange:
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
closes = prices.loc["Close"]
primary_exchanges = get_securities_reindexed_like(closes, fields=["ibkr_PrimaryExchange"]).loc["ibkr_PrimaryExchange"]
primary_exchanges = self.reindex_like_orders(primary_exchanges, orders)
orders["Exchange"] = primary_exchanges
...
Account allocations
An example Moonshot allocations template is available from the JupyterLab launcher.
Define your strategy allocations in quantrocket.moonshot.allocations.yml
, a YAML file located in the /codeload
directory (that is, in the top-level directory of the Jupyter file browser). You can run multiple strategies per account and/or multiple accounts per strategy. Allocations should be expressed as a decimal percent of the total capital (Net Liquidation Value) of the account:
DU12345:
dma-tech: 0.75
dma-etf: 0.5
U12345:
dma-tech: 1
By default, when you trade a strategy, Moonshot generates orders for all accounts which define allocations for that strategy. However, you can limit to particular accounts:
$ quantrocket moonshot trade 'dma-tech' -a 'U12345'
Note that you can also run multiple strategies at a time:
$ quantrocket moonshot trade 'dma-tech' 'dma-etf'
How Moonshot calculates order quantities
The behavior outlined in this section is handled automatically by Moonshot but is provided for informational purposes.
The target weights generated by signals_to_target_weights
are expressed in percentage terms (e.g. 0.1 = 10% of capital), but these weights must be converted into the actual numbers of shares, futures contracts, etc. that need to be bought or sold. Converting target weights into order quantities requires taking into account a number of factors including the strategy allocation, account NLV, exchange rates, existing positions and orders, and security price.
The conversion process is outlined below for an account with USD base currency:
Step | Source | Domestic stock example - AAPL (NASDAQ) | Foreign stock example - BP (London Stock Exchange) | Futures example - ES (CME) |
---|
What is target weight? | last row (= today) of target weights DataFrame | 0.2 | 0.2 | 0.2 |
What is account allocation for strategy? | quantrocket.moonshot.allocations.yml | 0.5 | 0.5 | 0.5 |
What is target weight for account? | multiply target weights by account allocations | 0.1 (0.2 x 0.5) | 0.1 (0.2 x 0.5) | 0.1 (0.2 x 0.5) |
What is latest account NLV? | account service | $1M USD | $1M USD | $1M USD |
What is target trade value in base currency? | multiply target weight for account by account NLV | $100K USD ($1M x 0.1) | $100K USD ($1M x 0.1) | $100K USD ($1M x 0.1) |
What is exchange rate? (if trade currency differs from base currency) | account service | Not applicable | USD.GBP = 0.75 | Not applicable |
What is target trade value in trade currency? | multiply target trade value in base currency by exchange rate | $100K USD | 75K GBP ($100K USD x 0.75 USD.GBP) | $100K USD |
What is market price of security? | prices DataFrame | $185 USD | 572 pence (quoted in pence, not pounds) | $2690 USD |
What is contract multiplier? (applicable to futures and options) | securities master service | Not applicable | Not applicable | 50x |
What is price magnifier? (used when prices are quoted in fractional units, for example, pence instead of pounds) | securities master service | Not applicable | 100 (i.e. 100 pence per pound) | Not applicable |
What is contract value? | contract value = (price x multiplier / price_magnifier) | $185 USD | 57.20 GBP (572 / 100) | $134,500 USD (2,690 x 50) |
What is target quantity? | divide target trade value by contract value | 540 shares ($100K / $185) | 1311 shares (75K GBP / 57.20 GBP) | 1 contract ($100K / $134.5K) |
Any current positions held by this strategy? | blotter service | 200 shares | 0 shares | 1 contract |
Any current open orders for this strategy? | blotter service | order for 100 shares currently active | none | none |
What is the required order quantity? | subtract current positions and open orders from target quantities | 240 shares (540 - 200 - 100) | 1311 shares (1311 - 0 - 0) | 0 contracts (1 - 1 - 0) |
Semi-manual vs automated trading
Since Moonshot generates a CSV of orders but doesn't actually place the orders, you can inspect the orders before placing them, if you prefer:
$ quantrocket moonshot trade 'my-strategy' -o orders.csv
$ csvlook -I orders.csv
| Sid | Account | Action | OrderRef | TotalQuantity | Exchange | OrderType | Tif |
| -------------- | ------- | ------ | -------- | ------------- | -------- | --------- | --- |
| FIBBG000B9XRY4 | DU12345 | BUY | dma-tech | 501 | SMART | MKT | DAY |
| FIBBG000BVPV84 | DU12345 | BUY | dma-tech | 58 | SMART | MKT | DAY |
| FIBBG000CL9VN6 | DU12345 | BUY | dma-tech | 284 | SMART | MKT | DAY |
| FIBBG00LBLDHJ2 | DU12345 | BUY | dma-tech | 86 | SMART | MKT | DAY |
If desired, you can edit the orders inside JupyterLab (right-click on filename > Open With > Editor). When ready, place the orders:
$ quantrocket blotter order -f orders.csv
For automated trading, pipe the orders CSV directly to the blotter over stdin:
$ quantrocket moonshot trade 'my-strategy' | quantrocket blotter order -f '-'
You can schedule this command to run on your countdown service. Be sure to read about collecting and using trading calendars, which enable you to run your trading command conditionally based on whether the market is open:
30 10 * * mon-fri quantrocket master isopen 'XNYS' && quantrocket moonshot trade 'my-strategy' | quantrocket blotter order -f '-'
In the event your strategy produces no orders, the blotter is designed to accept an empty file and simply do nothing.
End-of-day data collection and scheduling
For end of day strategies, you can use the same history database for live trading that you use for backtesting. Schedule your history database to be brought up-to-date overnight and schedule Moonshot to run after that. Your countdown service crontab might look like this:
30 6 * * mon-fri quantrocket history collect 'usstock-1d'
0 9 * * mon-fri quantrocket master isopen 'XNYS' --in '1h' && quantrocket moonshot trade 'eod-strategy' | quantrocket blotter order -f '-'
Intraday real-time data collection and scheduling
For intraday strategies, there are two options for real-time data: your history database, or a real-time aggregate database.
History database as real-time feed
If your strategy trades a small number of securities or uses a large bar size, it may be suitable to use your history database as a real-time feed, updating the history database during the trading session. This approach requires that your historical data vendor updates intraday data in real-time (for example Interactive Brokers) as opposed to providing overnight updates (like the US Stock 1-minute bundle). Using a history database is conceptually the simplest but historical data collection may be too slow for large universes and/or small bar sizes.
For an intraday strategy that uses 15-minute bars and enters the market at 10:00 AM based on 9:45 AM prices, you can schedule your history database to be brought current just after 9:45 AM and schedule Moonshot to run at 10:00 AM. Moonshot will generate orders based on the just-collected 9:45 AM prices.
46 9 * * mon-fri quantrocket master isopen 'ARCX' && quantrocket history collect 'arca-15min'
0 10 * * mon-fri quantrocket master isopen 'ARCX' && quantrocket moonshot trade 'intraday-strategy' | quantrocket blotter order -f '-'
In the above example, the 15-minute lag between collecting prices and placing orders mirrors the 15-minute bar size used in backtests. For smaller bar sizes, a smaller lag between data collection and order placement would be used.
The following is an example of scheduling an intraday strategy that trades throughout the day using 5-minute bars. Every 5 minutes between 8 AM and 8 PM, we collect FX data and run the strategy as soon as the data has been collected:
*/5 8-19 * * mon-fri quantrocket master isopen 'IDEALPRO' && quantrocket history collect 'fx-majors-5min' && quantrocket history wait 'fx-majors-5min' && quantrocket moonshot trade 'fx-revert' | quantrocket blotter order -f '-'
Real-time aggregate databases
If using your history database as a real-time feed is unsuitable, you should use a real-time aggregate database with a bar size equal to that of your history database.
Example 1: once-a-day equities strategy
In the first example, suppose we have backtested an Australian equities strategy using a history database of 15 minute bars called 'asx-15min'. At 15:00:00 Sydney time each day, we need to get an up-to-date quote for all ASX stocks and run Moonshot immediately afterward. To do so, we will collect real-time snapshot quotes, and aggregate them to 15-minute bars. (Even though there will only be a single quote to aggregate for each bar, aggregation is still required and ensures a uniform bar size.)
First we create the tick database and the aggregate database:
$ quantrocket realtime create-ibkr-tick-db 'asx-snapshot' --universes 'asx-stk' --fields 'LastPrice'
status: successfully created tick database asx-snapshot
$ quantrocket realtime create-agg-db 'asx-snapshot-15min' --tick-db 'asx-snapshot' --bar-size '15m' --fields 'LastPrice:Close'
status: successfully created aggregate database asx-snapshot-15min from tick database asx-snapshot
>>> from quantrocket.realtime import create_ibkr_tick_db, create_agg_db
>>> create_ibkr_tick_db("asx-snapshot", universes="asx-stk",
fields=["LastPrice"])
{'status': 'successfully created tick database asx-snapshot'}
>>> create_agg_db("asx-snapshot-15min",
tick_db_code="asx-snapshot",
bar_size="15m",
fields={"LastPrice":["Close"]})
{'status': 'successfully created aggregate database asx-snapshot-15min from tick database asx-snapshot'}
$ curl -X PUT 'http://houston/realtime/databases/asx-snapshot?universes=asx-stk&fields=LastPrice&vendor=ibkr'
{"status": "successfully created tick database asx-snapshot"}
$ curl -X PUT 'http://houston/realtime/databases/asx-snapshot/aggregates/asx-snapshot-15min?bar_size=15m&fields=LastPrice%3AClose'
{"status": "successfully created aggregate database asx-snapshot-15min from tick database asx-snapshot"}
For live trading, schedule real-time snapshots to be collected at the desired time and schedule Moonshot to run immediately afterward:
0 15 * * mon-fri quantrocket master isopen 'ASX' && quantrocket realtime collect 'asx-snapshot' --snapshot --wait && quantrocket moonshot trade 'asx-intraday-strategy' | quantrocket blotter order -f '-'
You can pull data from both your history database and your real-time aggregate database into your Moonshot strategy by specifying both databases in the DB
parameter. Also specify the combined set of fields you need from each database using the DB_FIELDS
parameter. In this example we need 'Close' from the history database and 'LastPriceClose' from the real-time aggregate database:
class ASXIntradayStrategy(Moonshot):
CODE = "asx-intraday-strategy"
DB = ["asx-15min", "asx-snapshot-15min"]
DB_FIELDS = ["Close", "LastPriceClose"]
Moonshot loads data using the get_prices
function, which supports querying a mix of history and real-time aggregate databases.
In your Moonshot code, you might combine the two data sources as follows:
>>> history_closes = prices.loc["Close"]
>>> realtime_closes = prices.loc["LastPriceClose"]
>>>
>>>
>>> combined_closes = realtime_closes.fillna(history_closes)
Example 2: continuous intraday futures strategy
In this example, we don't use a history database but rather collect real-time NYMEX futures data continuously throughout the day and run Moonshot every minute on the 1-minute aggregates.
First we create the tick database and the aggregate database:
$ quantrocket realtime create-ibkr-tick-db 'nymex-fut-tick' --universes 'nymex-fut' --fields 'LastPrice' 'BidPrice' 'AskPrice'
status: successfully created tick database nymex-fut-tick
$ quantrocket realtime create-agg-db 'nymex-fut-tick-1min' --tick-db 'nymex-fut-tick' --bar-size '1m' --fields 'LastPrice:Close' 'BidPrice:Close' 'AskPrice:Close'
status: successfully created aggregate database nymex-fut-tick-1min from tick database nymex-fut-tick
>>> from quantrocket.realtime import create_ibkr_tick_db, create_agg_db
>>> create_ibkr_tick_db("nymex-fut-tick", universes="nymex-fut",
fields=["LastPrice","BidPrice","AskPrice"])
{'status': 'successfully created tick database nymex-fut-tick'}
>>> create_agg_db("nymex-fut-tick-1min",
tick_db_code="nymex-fut-tick",
bar_size="1m",
fields={"LastPrice":["Close"],"BidPrice":["Close"],"AskPrice":["Close"]})
{'status': 'successfully created aggregate database nymex-fut-tick-1min from tick database nymex-fut-tick'}
$ curl -X PUT 'http://houston/realtime/databases/nymex-fut-tick?universes=nymex-fut&fields=LastPrice&fields=BidPrice&fields=AskPrice&vendor=ibkr'
{"status": "successfully created tick database nymex-fut-tick"}
$ curl -X PUT 'http://houston/realtime/databases/nymex-fut-tick/aggregates/nymex-fut-tick-1min?bar_size=1m&fields=LastPrice%3AClose&fields=BidPrice%3AClose&fields=AskPrice%3AClose'
{"status": "successfully created aggregate database nymex-fut-tick-1min from tick database nymex-fut-tick"}
Then, we schedule streaming market data to be collected throughout the day from 8:50 AM to 4:10 PM, and we schedule Moonshot to run every minute from 9:00 AM to 4:00 PM:
50 8 * * mon-fri quantrocket master isopen 'NYMEX' && quantrocket realtime collect 'nymex-fut-tick' --until '16:10:00 America/New_York'
* 9-15 * * mon-fri quantrocket master isopen 'NYMEX' && quantrocket moonshot trade 'nymex-futures-strategy' | quantrocket blotter order -f '-'
Since we aren't using a history database, Moonshot only needs to reference the real-time aggregate database:
class NymexFuturesStrategy(Moonshot):
CODE = "nymex-futures-strategy"
DB = "nymex-fut-tick-1min"
DB_FIELDS = ["LastPriceClose", "BidPriceClose", "AskPriceClose"]
Trade date validation
In live trading as in backtesting, a Moonshot strategy receives a DataFrame of historical prices and derives DataFrames of signals and target weights. In live trading, orders are created from the last row of the target weights DataFrame. To make sure you're not trading on stale data (for example because your history database hasn't been brought current), Moonshot validates that the target weights DataFrame is up-to-date.
Suppose our target weights DataFrame resembles the following:
>>> target_weights.tail()
AAPL(FIBBG000B9XRY4) AMZN(FIBBG000BVPV84)
Date
2020-05-05 0 0
2020-05-06 0.5 0
2020-05-07 0.5 0
2020-05-08 0 0
2020-05-11 0.25 0.25
By default, Moonshot looks for and extracts the row corresponding to today's date in the strategy timezone. (The strategy timezone can be set with the class attribute TIMEZONE
and is otherwise inferred from the timezone of the component securities.) Thus, if running the strategy on 2020-05-11, Moonshot would extract the last row from the above DataFrame. If running the strategy on 2020-05-12 or later, Moonshot will fail with the error:
msg: expected signal date 2020-05-12 not found in target weights DataFrame, is the underlying
data up-to-date? (max date is 2020-05-11)
status: error
This default validation behavior is appropriate for intraday strategies that trade once-a-day as well as end-of-day strategies that run after the market close, in both cases ensuring that today's price history is available to the strategy. However, if your strategy doesn't run until before the market open (for example because you need to collect data overnight), this validation behavior is too restrictive. In this case, you can set the CALENDAR
attribute on the strategy to an exchange code, and that exchange's trading calendar will be used for trade date validation instead of the timezone:
class MyStrategy(Moonshot):
...
CALENDAR = "XNYS"
...
Specifying the calendar allows Moonshot to be a little smarter, as it will only enforce the data being updated through the last date the exchange was open. Thus, if the strategy runs when the exchange is open, Moonshot still expects today's date to be in the target weights DataFrame. But if the exchange is currently closed, Moonshot expects the data date to correspond to the last date the exchange was open. This allows you to run the strategy before the market open using the prior session's data, while still enforcing that the data is not older than the previous session.
Intraday trade time validation
For intraday strategies that trade throughout the day (more specifically, for strategies that produce target weights DataFrames with a 'Time' level in the index), Moonshot validates the time of the data in addition to the date. For example, if you are using 15-minute bars and running a trading strategy at 11:48 AM, trade time validation ensures that the 11:45 AM target weights are used to create orders.
Trade time validation works as follows: Moonshot consults the entire date range of your DataFrame (not just the trade date) and finds the latest time that is earlier than the current time. In the example of running the strategy at 11:48 AM using 15-minute bars, this would be the 11:45 AM bar. Moonshot then checks that your prices DataFrame contains at least some non-null data for 11:45 AM on the trade date. If not, validation fails:
msg: no 11:45:00 data found in prices DataFrame for signal date 2020-05-11,
is the underlying data up-to-date? (max time for 2020-05-11 is 11:30:00)
status: error
This ensures that the intraday strategy won't run unless your data is up-to-date.
Review orders from earlier dates
At times you may want to bypass trade date validation and generate orders for an earlier date, for testing or troubleshooting purposes. You can pass a --review-date
for this purpose. For end-of-day strategies and once-a-day intraday strategies, only a date is needed:
$ quantrocket moonshot trade 'dma-tech' --review-date '2020-05-08' -o past_orders.csv
>>> from quantrocket.moonshot import trade
>>> trade("dma-tech", review_date="2020-05-08", filepath_or_buffer="past_orders.csv")
$ curl -X POST 'http://houston/moonshot/orders.csv?strategies=dma-tech&review_date=2020-05-08' > past_orders.csv
For intraday strategies that trade throughout the day, provide a date and time (you need not specify a timezone; the strategy timezone based on TIMEZONE
or inferred from the component securities is assumed):
$ quantrocket moonshot trade 'fx-revert' --review-date '2020-05-08 11:45:00' -o past_intraday_orders.csv
>>> from quantrocket.moonshot import trade
>>> trade("fx-revert", review_date="2020-05-08 11:45:00", filepath_or_buffer="past_intraday_orders.csv")
$ curl -X POST 'http://houston/moonshot/orders.csv?strategies=fx-revert&review_date=2020-05-08+11%3A45%3A00' > past_intraday_orders.csv
The --review-date
you specify determines which target weights Moonshot selects from the DataFrame returned by your signals_to_target_weights
method. However, note that using --review-date
is not a perfect simulation of the past. Specifically, to convert the selected target weights into order quantities, Moonshot consults your current positions, account balances, etc., rather than attempting to reconstruct the values as of the review date. Using --review-date
works best when your current positions are equivalent to those you held at the time you are reviewing.
Exiting positions
There are 3 ways to exit positions in Moonshot:
- Exit by rebalancing
- Attach exit orders
- Close positions with the blotter
Exit by rebalancing
By default, Moonshot calculates an order diff between your target positions and existing positions. This means that previously entered positions will be closed once the target position goes to 0, as Moonshot will generate the closing order needed to achieve the target position. This is a good fit for strategies that periodically rebalance.
Learn more about rebalancing.
Attach exit orders
Attaching exit orders is currently only supported for Interactive Brokers.
Sometimes, instead of relying on rebalancing, it's helpful to submit exit orders at the time you submit your entry orders. For example, if your strategy enters the market intraday and exits at market close, it's easiest to submit the entry and exit orders at the same time.
This is referred to as attaching a child order , and can be used for bracket orders , hedging orders , or in this case, simply a pre-planned exit order. The attached order is submitted to IBKR's system but is only executed if the parent order executes.
Moonshot provides a utility method for creating attached child orders, orders_to_child_orders
, which can be used like this:
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
orders["Exchange"] = "SMART"
orders["OrderType"] = "MKT"
orders["Tif"] = "Day"
child_orders = self.orders_to_child_orders(orders)
child_orders.loc[:, "OrderType"] = "MOC"
orders = pd.concat([orders, child_orders])
return orders
The orders_to_child_orders
method creates child orders by copying your orders DataFrame but reversing the Action (BUY/SELL), and linking the child orders to the parent orders via an OrderId
column on the parent orders and a ParentId
column on the child orders. Interactively, the above example would look like this:
>>> orders.head()
Sid Action TotalQuantity Exchange OrderType Tif
0 FI12345 BUY 200 SMART MKT Day
1 FI23456 BUY 400 SMART MKT Day
>>>
>>> child_orders = self.orders_to_child_orders(orders)
>>>
>>> child_orders.loc[:, "OrderType"] = "MOC"
>>> orders = pd.concat([orders, child_orders])
>>> orders.head()
Sid Action TotalQuantity Exchange OrderType Tif OrderId ParentId
0 FI12345 BUY 200 SMART MKT Day 0 NaN
1 FI23456 BUY 400 SMART MKT Day 1 NaN
0 FI12345 SELL 200 SMART MOC Day NaN 0
1 FI23456 SELL 400 SMART MOC Day NaN 1
Note that the OrderId
and ParentId
generated by Moonshot are not the actual order IDs used by the blotter. The blotter uses OrderId
/ParentId
(if provided) to identify linked orders but then generates the actual order IDs at the time of order submission to the broker.
Close positions with the blotter
A third option for closing positions is to use the blotter to flatten all positions for a strategy. For example, if your strategy enters positions in the morning and exits on the close, you could design the strategy to create the entry orders only, then schedule a command in the afternoon to flatten the positions:
0 10 * * mon-fri quantrocket master isopen 'TSE' && quantrocket moonshot trade 'canada-intraday' | quantrocket blotter order -f '-'
0 15 * * mon-fri quantrocket blotter close --order-refs 'canada-intraday' --params 'OrderType:MOC' 'Tif:Day' 'Exchange:TSE' | quantrocket blotter order -f '-'
This approach works best in scenarios where you want to flatten all positions in between each successive run of the strategy. Such scenarios can also be handled by attaching exit orders.
Learn more about closing positions with the blotter.
Tick sizes
When placing limit orders, stop orders, or other orders that specify price levels, it is necessary to ensure that the price you submit to the broker adheres to the security's tick size rules. This refers to the minimum difference between price levels at which a security can trade.
Price rounding
For securities with constant tick sizes, for example US stocks that trade in penny increments, you can simply round the prices in your strategy code using Pandas' round()
:
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
...
orders["OrderType"] = "LMT"
limit_prices = prior_closes * 1.02
orders["LmtPrice"] = limit_prices.round(2)
...
Dynamic price rounding
Dynamic price rounding requires collecting securities master listings from Interactive Brokers.
Some securities have different tick sizes on different exchanges on which they trade and/or different tick sizes at different price levels. For example, these are the tick size rules for orders for MITSUBISHI CORP direct-routed to the Tokyo Stock Exchange:
If price is between... | Tick size is... |
---|
0 - 1,000 | 0.1 |
1,000 - 3,000 | 0.5 |
3,000 - 10,000 | 1 |
10,000 - 30,000 | 5 |
30,000 - 100,000 | 10 |
100,000 - 300,000 | 50 |
300,000 - 1,000,000 | 100 |
1,000,000 - 3,000,000 | 500 |
3,000,000 - 10,000,000 | 1,000 |
10,000,000 - 30,000,000 | 5,000 |
30,000,000 - | 10,000 |
In contrast, SMART-routed orders for Mitsubishi must adhere to a different, simpler set of tick size rules:
If price is between... | Tick size is... |
---|
0 - 5,000 | 0.1 |
5,000 - 100,000 | 1 |
100,000 - | 10 |
Luckily you don't need to keep track of tick size rules as they are stored in the securities master database when you collect listings from Interactive Brokers. You can create your Moonshot orders CSV with unrounded prices then pass the CSV to the master service for price rounding. For example, consider two limit orders for Mitsubishi, one SMART-routed and one direct-routed to TSEJ, with unrounded limit prices of 15203.1135 JPY:
$ csvlook -I orders.csv
| Sid | Account | Action | OrderRef | TotalQuantity | Exchange | OrderType | LmtPrice | Tif |
| -------------- | ------- | ------ | -------------- | ------------- | -------- | --------- | ---------- | --- |
| FIBBG000BB8GZ0 | DU12345 | BUY | japan-strategy | 1000 | SMART | LMT | 15203.1135 | DAY |
| FIBBG000BB8GZ0 | DU12345 | BUY | japan-strategy | 1000 | TSEJ | LMT | 15203.1135 | DAY |
If you pass this CSV to the master service and tell it which columns to round, it will round the prices in those columns based on the tick size rules for that Sid and Exchange:
$ quantrocket master ticksize -f orders.csv --round 'LmtPrice' -o rounded_orders.csv
>>> from quantrocket.master import round_to_tick_sizes
>>> round_to_tick_sizes("orders.csv", round_fields=["LmtPrice"], outfilepath_or_buffer="rounded_orders.csv")
$ curl -X GET 'http://houston/master/ticksizes.csv?round_fields=LmtPrice' --upload-file orders.csv > rounded_orders.csv
The SMART-routed order is rounded to the nearest Yen while the TSEJ-routed order is rounded to the nearest 5 Yen, as per the tick size rules. Other columns are returned unchanged:
$ csvlook -I rounded_orders.csv
| Sid | Account | Action | OrderRef | TotalQuantity | Exchange | OrderType | LmtPrice | Tif |
| -------------- | ------- | ------ | -------------- | ------------- | -------- | --------- | -------- | --- |
| FIBBG000BB8GZ0 | DU12345 | BUY | japan-strategy | 1000 | SMART | LMT | 15203.0 | DAY |
| FIBBG000BB8GZ0 | DU12345 | BUY | japan-strategy | 1000 | TSEJ | LMT | 15205.0 | DAY |
The ticksize command accepts file input over stdin, so you can pipe your moonshot orders directly to the master service for rounding, then pipe the rounded orders to the blotter for submission:
$ quantrocket moonshot trade 'my-japan-strategy' | quantrocket master ticksize -f '-' --round 'LmtPrice' | quantrocket blotter order -f '-'
In the event your strategy produces no orders, the ticksize command, like the blotter, is designed to accept an empty file and simply do nothing.
If you need the actual tick sizes and not just the rounded prices, you can instruct the ticksize endpoint to include the tick sizes in the resulting file:
$ quantrocket master ticksize -f orders.csv --round 'LmtPrice' --append-ticksize -o rounded_orders.csv
>>> from quantrocket.master import round_to_tick_sizes
>>> round_to_tick_sizes("orders.csv", round_fields=["LmtPrice"], append_ticksize=True, outfilepath_or_buffer="rounded_orders.csv")
$ curl -X GET 'http://houston/master/ticksizes.csv?round_fields=LmtPrice&append_ticksize=true' --upload-file orders.csv > rounded_orders.csv
A new column with the tick sizes will be appended, in this case called "LmtPriceTickSize":
$ csvlook -I rounded_orders.csv
| Sid | Account | Action | OrderRef | TotalQuantity | Exchange | OrderType | LmtPrice | Tif | LmtPriceTickSize |
| -------------- | ------- | ------ | -------------- | ------------- | -------- | --------- | -------- | --- | ---------------- |
| FIBBG000BB8GZ0 | DU12345 | BUY | japan-strategy | 1000 | SMART | LMT | 15203.0 | DAY | 1.0 |
| FIBBG000BB8GZ0 | DU12345 | BUY | japan-strategy | 1000 | TSEJ | LMT | 15205.0 | DAY | 5.0 |
Tick sizes can be used for submitting orders that require price offsets such as Relative/Pegged-to-Primary orders.
Price offsets
Some order types, such as Interactive Brokers' Relative/Pegged-to-Primary orders, require defining an offset amount using the AuxPrice
field. In the case of Relative orders, which move dynamically with the market, the offset amount defines how much more aggressive than the NBBO the order should be.
In some cases, it may suffice to hard-code an offset amount, e.g. $0.01:
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
orders["Exchange"] = "SMART"
orders["OrderType"] = "REL"
orders["AuxPrice"] = 0.01
...
However, as the offset must conform to the security's tick size rules, for some exchanges it's necessary to look up the tick size and use that to define the offset:
import pandas as pd
import io
from quantrocket.master import round_to_tick_sizes
...
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
orders["Exchange"] = "SMART"
orders["OrderType"] = "REL"
prior_closes = prices.loc["Close"].shift()
prior_closes = self.reindex_like_orders(prior_closes, orders)
orders["PriorClose"] = prior_closes
infile = io.StringIO()
outfile = io.StringIO()
orders.to_csv(infile, index=False)
round_to_tick_sizes(infile, round_fields=["PriorClose"], append_ticksize=True, outfilepath_or_buffer=outfile)
tick_sizes = pd.read_csv(outfile).PriorCloseTickSize
orders["AuxPrice"] = tick_sizes * 2
orders.drop("PriorClose", axis=1, inplace=True)
...
Round lots
Some exchanges such as the Toyko Stock Exchange require round lots, also known as 100-share trading units. Moonshot does not calculate round lots, but you can round the share quantities yourself in order_stubs_to_orders
:
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
orders["TotalQuantity"] = orders.TotalQuantity.div(100).round() * 100
...
Paper trading
There are several options for testing your trades before you run your strategy on a live account. You can log the trades to flightlog, you can inspect the orders before placing them, and you can trade against your paper brokerage account.
Log trades to flightlog
After researching and backtesting a strategy in aggregate it's often nice to carefully inspect a handful of actual trades before committing real money. A good option is to start running the strategy but log the trades to flightlog instead of sending them to the blotter:
0 9 * * mon-fri quantrocket master isopen 'XNYS' --in 1h && quantrocket moonshot trade 'mean-reverter' | quantrocket flightlog log --name 'mean-reverter'
Then manually inspect the trades to see if you're happy with them.
Semi-manual trading
Another option which works well for end-of-day strategies is to generate the Moonshot orders, inspect the CSV file, then manually place the orders if you're happy. See the section on semi-manual trading.
Paper trading with broker
You can also paper trade the strategy using your paper trading brokerage account. To do so, allocate the strategy to your paper account in quantrocket.moonshot.allocations.yml
:
DU12345:
mystrategy: 0.5
Then add the appropriate command to your countdown crontab, just as you would for a live account.
Paper trading limitations
Paper trading accounts provide a useful way to dry-run your strategy, but it's important to note that most brokers' paper trading environments do not offer a full-scale simulation. For example, Interactive Brokers doesn't attempt to simulate certain order types such as on-the-open and on-the-close orders; such orders are accepted by the system but never filled. You may need to work around this limitation by modifying your orders for live vs paper accounts.
Paper trading is primarily useful for validating that your strategy is generating the orders you expect. It's less helpful for seeing what those orders do in the market or performing out-of-sample testing. For that, consider a small allocation to a live account.
See IBKR's website for a list of IBKR paper trading limitations .
Different orders for live vs paper accounts
As some order types aren't supported in paper accounts, you can specify different orders for paper vs live accounts:
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
orders["OrderType"] = "MKT"
orders["Tif"] = "OPG"
orders.loc[orders.Account.str.startswith("D"), "Tif"] = "DAY"
...
Rebalancing
Periodic rebalancing
A Moonshot strategy's prices_to_signals
logic will typically calculate signals for each day in the prices DataFrame. However, for many factor model or cross-sectional strategies, you may not wish to rebalance that frequently. For example, suppose our strategy logic ranks stocks every day by momentum and buys the top 10%:
>>>
>>> returns = closes.shift(252)/closes - 1
>>>
>>> ranks = returns.rank(axis=1, ascending=False, pct=True)
>>>
>>> signals = (ranks <= 0.1).astype(int)
>>> signals.head()
Sid FI123456 FI234567 ...
Date
2018-05-31 1 0
2018-06-01 0 1
2018-06-02 0 0
2018-06-03 1 0
...
2018-06-30 0 1
2018-07-01 0 1
2018-07-02 1 0
As implemented above, the strategy will trade in and out of positions daily. Instead, we can limit the strategy to monthly rebalancing:
>>>
>>>
>>>
>>>
>>>
>>> signals = signals.resample("M").last()
>>> signals = signals.reindex(closes.index, method="ffill")
>>> signals.head()
Sid FI123456 FI234567 ...
Date
2018-05-31 1 0
2018-06-01 1 0
2018-06-02 1 0
2018-06-03 1 0
...
2018-06-30 0 1
2018-07-01 0 1
2018-07-02 0 1
Then, in live trading, to mirror the resampling logic, schedule the strategy to run only on the first trading day of the month:
0 9 * * mon-fri quantrocket master isclosed 'XNYS' --since 'M' && quantrocket master isopen 'XNYS' --in '1h' && quantrocket moonshot trade 'us-momentum' | quantrocket blotter order -f '-'
Disabling rebalancing
By default, Moonshot generates orders as needed to achieve your target weights, after taking account of your existing positions. This design is well-suited for strategies that periodically rebalance positions. However, in live trading, this behavior can be suboptimal for strategies that hold multi-day positions which are not intended to be rebalanced. You may wish to disable rebalancing for such strategies.
For example, suppose your strategy calls for holding a 5% position of AAPL for a period of several days. When you enter the position, you account balance is $1M USD and the price of AAPL is $100, so you buy 500 shares ($1M X 0.05 / $100). A day later, your account balance is $1.02M, while the price of AAPL is $97, so Moonshot calculates your target position as 526 shares ($1.02M X 0.05 / $97) and create an order to buy 26 shares (526 - 500). The following day, your account balance is unchanged at $1.02M but the price of AAPL is $98.50, resulting in a target position of 518 shares and a net order to sell 8 shares (518 - 526). Day-to-day changes in the share price and/or your account balance result in small buy or sell orders for the duration of the position.
These small rebalancing orders are problematic because they incur slippage and commissions which are not reflected in a backtest. In a backtest, the position is maintained at a constant weight of 5% so there are no day-to-day transaction costs. Thus, the daily rebalancing orders will introduce hidden costs into live performance compared to backtested performance.
You can disable rebalancing for a strategy using the ALLOW_REBALANCE
parameter:
class MultiDayStrategy(Moonshot):
...
ALLOW_REBALANCE = False
When ALLOW_REBALANCE
is set to False
, Moonshot will not create orders to rebalance a position which is already on the correct side (long or short). Moonshot will still create orders as needed to open a new position, close an existing position, or change sides (long to short or short to long). When ALLOW_REBALANCE
is True
(the default), Moonshot creates orders as needed to achieve the target weight.
You can also use a decimal value with ALLOW_REBALANCE
to allow rebalancing only when the target position is sufficiently different from the existing position size. For example, don't rebalance unless the position size will change by at least 25%:
class MultiDayStrategy(Moonshot):
...
ALLOW_REBALANCE = 0.25
In this example, if the target position size is 600 shares and the current position size is 500 shares, the rebalancing order will be suppressed because 100/500 < 0.25. If the target position is 300 shares, the rebalancing order will be allowed because 200/500 > 0.25.
By disabling rebalancing, your commissions and slippage will mirror your backtest. However, your live position weights will fluctuate and differ somewhat from the constant weights of your backtest, and as a result your live returns will not match your backtest returns exactly. This is often a good trade-off because the discrepancy in position weights (and thus returns) is usually two-sided (i.e. sometimes in your favor, sometimes not) and thus roughly nets out, while the added transaction costs of daily rebalancing is a one-sided cost that degrades live performance.
IBKR algorithmic orders
Interactive Brokers provides various algorithmic order types which can be helpful for working large orders into the market. In fact, if you submit a market order that is too big based on the security's liquidity, IBKR might reject the order with this message:
quantrocket.blotter: WARNING ibg2 client 6001 got IBKR message code 202: Order Canceled - reason:In accordance with our regulatory obligations, we have rejected this order because it is too large compared to the liquidity that is generally available for this product. If you would like to submit an order of this size, please submit an algorithmic order (such as VWAP, TWAP, or Percent of Volume)
Some historical datasets include a Vwap
or Wap
field. This makes it possible to use the VWAP field to calculate returns in your backtest, then use IBKR's "Vwap" order algo in live trading (or a similar order algo) to mirror your backtest.
VWAP for end-of-day strategies
For an end-of-day strategy, the relevant example code for a backtest is shown below:
class UpMinusDown(Moonshot):
...
DB_FIELDS = ["Wap", "Volume", "Close"]
...
def positions_to_gross_returns(self, positions: pd.DataFrame, prices: pd.DataFrame):
vwaps = prices.loc["Wap"]
gross_returns = vwaps.pct_change() * positions.shift()
return gross_returns
Here, we are modeling our orders being filled at the next day's VWAP. Then, for live trading, create orders using IBKR's VWAP algo:
class UpMinusDown(Moonshot):
...
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
orders["OrderType"] = "MKT"
orders["AlgoStrategy"] = "Vwap"
orders["Tif"] = "DAY"
orders["Exchange"] = "SMART"
return orders
If placed before the market open, IBKR will seek to fill this order over the course of the day at the day's VWAP, thus mirroring our backtest.
VWAP for intraday strategies
VWAP orders can also be modeled and used on an intraday timeframe. For example, suppose we are using 30-minute bars and want to enter and exit positions gradually between 3:00 and 3:30 PM. In backtesting, we can use the 15:00:00 Wap
:
class IntradayStrategy(Moonshot):
...
DB_FIELDS = ["Wap", "Volume", "Close"]
...
def positions_to_gross_returns(self, positions: pd.DataFrame, prices: pd.DataFrame):
vwaps = prices.loc["Wap"].xs("15:00:00", level="Time")
gross_returns = vwaps.pct_change() * positions.shift()
return gross_returns
Then, for live trading, run the strategy at 15:00:00 and instruct IBKR to finish the VWAP orders by 15:30:00:
class IntradayStrategy(Moonshot):
...
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
orders["OrderType"] = "MKT"
orders["AlgoStrategy"] = "Vwap"
now = pd.Timestamp.now("America/New_York")
end_time = now.replace(hour=15, minute=30, second=0)
end_time_str = end_time.astimezone("UTC").strftime("%Y%m%d %H:%M:%S GMT")
orders["AlgoParams_endTime"] = end_time_str
orders["AlgoParams_allowPastEndTime"] = 1
orders["Tif"] = "DAY"
orders["Exchange"] = "SMART"
return orders
Algo parameters
In the IBKR API, algorithmic orders are specified by the AlgoStrategy
field, with additional algo parameters specified in the AlgoParams
fields (algo parameters are optional or required depending on the algo). The AlgoParams
field is a nested field which expects a list of multiple algo-specific parameters ; since the orders CSV (and the DataFrame it derives from) is a flat-file format, these nested parameters can be specified using underscore separators, e.g. AlgoParams_maxPctVol
:
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
orders["AlgoStrategy"] = "Vwap"
orders["AlgoParams_maxPctVol"] = 0.1
orders["AlgoParams_noTakeLiq"] = 1
...
Moonshot snippets
These snippets are meant to be useful and suggestive as starting points, but they may require varying degrees of modification to conform to the particulars of your strategy.
Multi-day holding periods
One way to implement multi-day holding periods is to forward-fill signals with a limit:
def signals_to_target_weights(self, signals: pd.DataFrame, prices: pd.DataFrame):
weights = self.allocate_fixed_weights(signals, 0.05)
weights = weights.where(weights!=0).fillna(method="ffill", limit=2)
weights.fillna(0, inplace=True)
return weights
Limit orders
To use limit orders in a backtest, you can model whether they get filled in target_weights_to_positions
. For example, suppose we generate signals after the close and place orders to enter on the open the following day using limit orders set 1% above the prior close for BUYs and 1% below the prior close for SELLs:
def target_weights_to_positions(self, weights: pd.DataFrame, prices: pd.DataFrame):
positions = weights.shift()
prior_closes = prices.loc["Close"].shift()
buy_limit_prices = prior_closes * 1.01
sell_limit_prices = prior_closes * 0.99
opens = prices.loc["Open"]
buy_orders = positions > 0
sell_orders = positions < 0
opens_below_buy_limit = opens < buy_limit_prices
opens_above_sell_limit = opens > sell_limit_prices
gets_filled = (buy_orders & opens_below_buy_limit) | (sell_orders & opens_above_sell_limit)
positions = positions.where(gets_filled, 0)
return positions
For live trading, create the corresponding order parameters in order_stubs_to_orders
:
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
prior_closes = prices.loc["Close"].shift()
prior_closes = self.reindex_like_orders(prior_closes, orders)
buy_limit_prices = prior_closes * 1.01
sell_limit_prices = prior_closes * 0.99
buy_orders = orders.Action == "BUY"
sell_orders = ~buy_orders
orders["LmtPrice"] = None
orders.loc[buy_orders, "LmtPrice"] = buy_limit_prices.loc[buy_orders]
orders.loc[sell_orders, "LmtPrice"] = sell_limit_prices.loc[sell_orders]
...
GoodAfterTime orders
Place market orders that won't become active until 3:55 PM:
def order_stubs_to_orders(self, orders: pd.DataFrame, prices: pd.DataFrame):
now = pd.Timestamp.now(self.TIMEZONE)
good_after_time = now.replace(hour=15, minute=55, second=0)
good_after_time_str = good_after_time.astimezone("UTC").strftime("%Y%m%d %H:%M:%S GMT")
orders["GoodAfterTime"] = good_after_time_str
...
Early close
For intraday strategies that use the session close bar for rolling calculations, early close days can interfere with the rolling calculations by introducing NaNs. Below, with 15-minute data, calculate 50-day moving average by using the early close bar when the close bar is missing:
session_closes = prices.loc["Close"].xs("15:45:00", level="Time")
early_close_session_closes = prices.loc["Close"].xs("12:45:00", level="Time")
session_closes.fillna(early_close_session_closes, inplace=True)
mavgs = session_closes.rolling(window=50).mean()
The scheduling section contains examples of scheduling live trading around early close days.
Moonshot cache
Moonshot implements DataFrame caching to improve performance.
When you run a Moonshot backtest, historical price data is retrieved from the database and loaded into Pandas, and the resulting DataFrame is cached to disk. If you run another backtest without changing any parameters that affect the historical data query (including start and end date, universes and sids, and database fields and times), the cached DataFrame is used without hitting the database, resulting in a faster runtime. Caching is particularly useful for parameter scans, which run repeated backtests using the same data.
No caching is used for live trading.
Bypass the cache
Moonshot tries to be intelligent about when the cache should not be used. For example, if you run a backtest with no end date (indicating you want up-to-date history from your database), Moonshot will bypass the cache if the database was recently modified (indicating there might be new data available). However, there are certain cases where you might need to manually bypass the Moonshot cache:
- if your strategy uses the
UNIVERSES
or EXCLUDE_UNIVERSES
parameters, and you change the constituents of the universe, then run another backtest, Moonshot will re-use the cached DataFrame, not realizing that the underlying universe constituents have changed. - if you run a backtest that specifies an end date, Moonshot will try to use the cache, even if the underlying history database has changed for whatever reason.
You can manually bypass the cache using the --no-cache/no_cache
option:
$ quantrocket moonshot backtest 'dma-tech' --no-cache -o dma_tech_results.csv
>>> from quantrocket.moonshot import backtest
>>> backtest("dma-tech", no_cache=True,
filepath_or_buffer="dma_tech_results.csv.csv")
$ curl -X POST 'http://houston/moonshot/backtests?strategies=dma-tech&no_cache=True' > dma_tech_results.csv
A similar parameter is available for parameter scans and machine learning walk-forward optimizations.
Machine Learning
Machine learning in QuantRocket utilizes Moonshot and this section assumes basic familiarity with Moonshot.
QuantRocket supports backtesting and live trading of machine learning strategies using Moonshot. Key features include:
- Walk-forward optimization: Support for rolling and expanding walk-forward optimization, widely considered the best technique for validating machine learning models in finance.
- Incremental/out-of-core learning: Train models and run backtests even when your data is too large to fit in memory.
- Multiple machine learning/deep learning packages: Support for multiple Python machine learning packages including scikit-learn, Keras + TensorFlow, and XGBoost.
The basic workflow of a machine learning strategy is as follows:
- use prices, fundamentals, or other data to create features and targets for your model (features are the predictors, for example past returns, and targets are what you want to predict, for example future returns)
- choose and customize a machine learning model (or rely on QuantRocket's default model)
- train the model with your features and targets
- use the model's predictions to generate trading signals
MoonshotML
An example MoonshotML strategy template is available from the JupyterLab launcher.
Below is simple machine learning strategy which asks the model to predict next-day returns based on prior 1- and 2-day returns, then uses the model's predictions to generate signals:
import pandas as pd
from moonshot import MoonshotML
class DemoMLStrategy(MoonshotML):
CODE = "demo-ml"
DB = "demo-stk-1d"
def prices_to_features(self, prices: pd.DataFrame):
closes = prices.loc["Close"]
features = {}
features["returns_1d"]= closes.pct_change()
features["returns_2d"] = (closes - closes.shift(2)) / closes.shift(2)
targets = closes.pct_change().shift(-1)
return features, targets
def predictions_to_signals(self, predictions: pd.DataFrame, prices: pd.DataFrame):
signals = predictions > 0
return signals.astype(int)
Machine learning strategies inherit from MoonshotML
instead of Moonshot
. Instead of defining a prices_to_signals
method as with a standard Moonshot strategy, a machine learning strategy should define two methods for generating signals: prices_to_features
and predictions_to_signals
.
Prices to features
The prices_to_features
method takes a DataFrame of prices and should return a tuple of features and targets that will be used to train the machine learning model.
The features should be a dict or list of DataFrames, where each DataFrame is a single feature. You can provide as many features as you want. If using a dict, assigning each feature to a unique key in the dict (the specific name of the dict keys is not used and doesn't matter).
features = {}
features["returns_1d"]= closes.pct_change()
features["returns_2d"] = (closes - closes.shift(2)) / closes.shift(2)
Alternatively features can be a list of DataFrames:
features = []
features.append(closes.pct_change())
features.append((closes - closes.shift(2)) / closes.shift(2))
The targets (what you want to predict) should be a DataFrame with an index matching that of the individual features DataFrames. The targets are only consulted by QuantRocket during the training segments of walk-forward optimization, in order to train the model. They are ignored during the backtesting segments of walk-forward optimization (as well as in live trading), when the model is used for prediction rather than training.
If using a regression model (which includes the default model), the targets should be a continuous variable such as returns. If using a classification model, the targets should represent two or more discrete classes (for example 1 and 0 for buy and don't-buy).
You can predict any variable you want; you need not predict returns.
Predictions to signals
In a backtest or live trading, the features (but not targets) from your prices_to_features
method are fed to the machine learning model to generate predictions. These predictions are in turn fed to your predictions_to_signals
method, which should use them (in conjunction with any other logic you wish to apply) to generate a DataFrame of signals. In the simple example below, we generate long signals when the predicted return is positive.
def predictions_to_signals(self, predictions: pd.DataFrame, prices: pd.DataFrame):
signals = predictions > 0
return signals.astype(int)
After you've generated signals, a MoonshotML
strategy is identical to a standard Moonshot
strategy. You can define the standard Moonshot methods including signals_to_target_weights
, target_weights_to_positions
, and positions_to_gross_returns
.
Single-security vs multi-security predictions
You can use different conventions for your features and targets, depending on how many things you are trying to predict.
The above examples demonstrate the use of DataFrames for the features and targets. This convention is suitable when you are making predictions about each security in the prices DataFrame. In the example, the model trains on the past returns of all securities and predicts the future returns of all securities.
When you create multiple DataFrames of features, QuantRocket prepares the DataFrames for the machine learning model by stacking each DataFrame into a single column and concatenating the columns into a single 2d numpy array of features, where each column is a feature.
Alternatively, you might have multiple instruments in your prices DataFrame but only wish to make predictions about one of them. This can be accomplished by using Series for the features and targets instead of DataFrames. In the following example, we want to predict the future return of the S&P 500 index using its past return and the level of the VIX:
SPX = "IB416904"
VIX = "IB13455763"
def prices_to_features(self, prices: pd.DataFrame):
closes = prices.loc["Close"]
spx_closes = closes[SPX]
vix_closes = closes[VIX]
features = {}
features["spx_returns_1d"]= spx_closes.pct_change()
features["vix_above_20"] = (vix_closes > 20).astype(int)
targets = spx_closes.pct_change().shift(-1)
return features, targets
Since the features and targets are Series, the model's predictions that are fed back to predictions_to_signals
will also be a Series, which we can use to generate our SPX signals:
def predictions_to_signals(self, predictions: 'pd.Series[float]', prices: pd.DataFrame):
closes = prices.loc["Close"]
signals = pd.DataFrame(False, index=closes.index, columns=closes.columns)
signals.loc[:, SPX] = predictions > 0
return signals.astype(int)
Predict probabilities
By default, Moonshot always calls the predict
method on your model to generate predictions. Some scikit-learn classifiers provide an additional predict_proba
method, which predicts the probability that a sample belongs to the class. To use predict_proba
, you can monkey patch the model in prices_to_features
:
def prices_to_features(self, prices: pd.DataFrame):
if self.model:
self.model.predict = self.model.predict_proba
...
The targets you define in prices_to_features
must be 0s and 1s (for example by casting a boolean DataFrame to integers). The predictions returned to predictions_to_signals
represent the probabilities that the samples belong to class label 1 (that is, True). An example is shown below:
def prices_to_features(self, prices: pd.DataFrame):
...
are_hot_stocks = next_day_returns > 0.04
targets = are_hot_stocks.astype(int)
return features, targets
def predictions_to_signals(self, predictions: pd.DataFrame, prices: pd.DataFrame):
likely_hot_stocks = predictions > 0.70
long_signals = likely_hot_stocks.astype(int)
return long_signals
Walk-forward backtesting
With the MoonshotML strategy code in place, we are ready to run a walk-forward optimization:
>>> from quantrocket.moonshot import ml_walkforward
>>> ml_walkforward("demo-ml",
start_date="2006-01-01", end_date="2012-12-31",
train="Y", min_train="4Y",
filepath_or_buffer="demo_ml*")
In a walk-forward optimization, the data is split into segments. The model is trained on the first segment of data then tested on the second segment, then trained again with the second segment and tested on the third segment, and so on. In the above example, we retrain the model annually (train="Y"
) and require 4 years of initial training (min_train="4Y"
) before performing any backtesting. (Training intervals should be specified as Pandas offset aliases.) The above parameters result in the following sequence of training and testing:
| |
---|
train | 2006-2009 |
test | 2010 |
train | 2010 |
test | 2011 |
train | 2011 |
test | 2012 |
train | 2012 |
During each training segment, the features and targets for the training dates are collected from your MoonshotML strategy and used to train the model. During each testing segment, the features for the testing dates are collected from your MoonshotML strategy and used to make predictions, which are fed back to your strategy's predictions_to_signals
method.
Walk-forward results
The walk-forward optimization returns a Zip file containing the backtest results CSV (which is a concatenation of backtest results for each individual test period) and the trained model. As a convenience, you can use an asterisk in the output filename as in the above example (filepath_or_buffer="demo_ml*"
) to instruct the QuantRocket client to automatically extract the files from the Zip file, saving them in this example to "demo_ml_results.csv" and "demo_ml_trained_model.joblib".
The backtest results CSV is a standard Moonshot CSV which can be used to generate a Moonchart tear sheet:
>>> from moonchart import Tearsheet
>>> Tearsheet.from_moonshot_csv("demo_ml_results.csv")
The model file is a pickle (serialization) of the now trained machine learning model that was used in the walk-forward optimization. (In this example we did not specify a custom model so the default model was used.) The trained model can be loaded into Python using joblib
:
>>> import joblib
>>> trained_model = joblib.load("demo_ml_trained_model.joblib")
>>> print(trained_model.coef_)
Joblib is a package which, among other features, provides a replacement of Python's standard pickle library that is optimized for serializing objects containing large numpy arrays, as is the case for some trained machine learning models.
If you like the backtest results, make sure to save the trained model so you can use it later for live trading.
Rolling vs expanding windows
QuantRocket supports rolling or expanding walk-forward optimizations.
With an expanding window (the default), the training start date remains fixed to the beginning of the simulation and consequently the size of the training window expands over time. In contrast, with a rolling window, the model is trained using a rolling window of data that moves forward over time and remains constant in size. For example, assuming a model with 3 years initial training and retrained annually, the following table depicts the difference between expanding and rolling windows:
iteration | training period (expanding) | training period (rolling 3-yr) |
---|
1 | 2006-2009 | 2006-2009 |
2 | 2006-2010 | 2007-2010 |
3 | 2006-2011 | 2008-2011 |
Thus, a rolling walk-forward optimization trains the model using recent data only, whereas an expanding walk-forward optimization trains the model using all available data since the start of the simulation.
To run a rolling optimization, specify the rolling window size using the rolling_train
parameter:
>>> ml_walkforward("demo-ml",
start_date="2006-01-01", end_date="2012-12-31",
train="Y", rolling_train="4Y",
force_nonincremental=True,
filepath_or_buffer="demo_ml*")
Note the distinction between train
and rolling_train
: the model will be re-trained at intervals of size train
using data windows of size rolling_train
.
If using the default or another model that supports incremental learning, you must also specify
force_nonincremental=True
, as rolling optimizations cannot be run incrementally. See the
incremental learning section to learn more.
Progress indicator
For long-running walk-forward optimizations, you can specify progress=True
which will instruct QuantRocket to log the ongoing progress of the walk-forward optimization to flightlog at each iteration, showing which segments are completed as well as the Sharpe ratio of each test segment:
[demo-ml] Walk-forward analysis progress
train test progress
start end start end status Sharpe
iteration
0 2005-12-31 2009-12-30 2009-12-31 2010-12-30 ✓ 0.94
1 2009-12-31 2010-12-30 2010-12-31 2011-12-30 ✓ -0.11
2 2010-12-31 2011-12-30 2011-12-31 2012-12-31 -
...
8 2017-12-31 2018-12-31 NaN NaN
Note that the logged progress indicator will include timestamps and service names like any other log line and as a result may not fit nicely in your Terminal window. You can use the Unix cut
utility to trim the log lines and produce the cleaner output shown above:
$
$ quantrocket flightlog stream | cut -d ' ' -f 5-
Model customization
From the numerous machine learning algorithms that are available, QuantRocket provides a sensible default but also allows you to choose and customize your own.
To customize the model and/or its hyper-parameters, instantiate the model as desired, serialize it to disk, and pass the serialized model to the walk-forward optimization.
>>> from sklearn.tree import DecisionTreeRegressor
>>> import joblib
>>> regr = DecisionTreeRegressor()
>>> joblib.dump(regr, "tree_model.joblib")
>>> from quantrocket.moonshot import ml_walkforward
>>> ml_walkforward("demo-ml",
start_date="2006-01-01", end_date="2012-12-31",
train="Y",
model_filepath="tree_model.joblib",
filepath_or_buffer="demo_ml_decision_tree*")
Default model
If you don't specify a model, the model used is scikit-learn's SGDRegressor
, which provides linear regression with Stochastic Gradient Descent. Because SGD is sensitive to feature scaling, the default model first runs the features through scikit-learn's StandardScaler
, using a scikit-learn Pipeline
to combine the two steps. Using the default model is equivalent to creating the model shown below:
from sklearn.pipeline import Pipeline
from sklearn.linear_model import SGDRegressor
from sklearn.preprocessing import StandardScaler
model = Pipeline([("scaler", StandardScaler()),
("estimator", SGDRegressor())])
SGDRegressor
is used as the default model in part because it supports incremental learning and thus is suitable for larger-than-memory datasets.
Scikit-learn
Scikit-learn is perhaps the most commonly used machine learning library for Python. It provides a variety of off-the-shelf machine learning algorithms and boasts a user guide that is excellent not only as an API reference but as an introduction to many machine learning concepts. Depending on your needs, your model can be a single estimator:
>>> from sklearn.tree import DecisionTreeRegressor
>>> import joblib
>>> regr = DecisionTreeRegressor(max_depth=2)
>>> joblib.dump(regr, "tree_model.joblib")
Or a multi-step pipeline:
>>> from sklearn.pipeline import Pipeline
>>> from sklearn.decomposition import IncrementalPCA
>>> from sklearn.linear_model import SGDRegressor
>>> from sklearn.preprocessing import StandardScaler
>>> import joblib
>>> model = Pipeline([("scaler", StandardScaler()),
("pca", IncrementalPCA(n_components=3))
("estimator", SGDRegressor())])
>>> joblib.dump(model, "pipeline.joblib")
Keras + TensorFlow
Keras is a neural networks/deep learning library for Python which runs on top of TensorFlow. To use Keras with your machine learning strategy, build, compile, and save your model to disk. Use Keras's save
method to serialize the model to disk, rather than joblib. Make sure your model filename ends with .keras.h5
, as this provides a hint to the walk-forward optimization that the serialized model should be opened as a Keras model.
>>> from keras.models import Sequential
>>> from keras.layers import Dense
>>> model = Sequential()
>>>
>>> model.add(Dense(1, input_dim=2))
>>> model.compile(loss='mean_squared_error', optimizer='adam')
>>> model.save('my_model.keras.h5')
After running the walk-forward optimization:
>>> ml_walkforward("demo-ml",
start_date="2006-01-01", end_date="2012-12-31",
train="Y",
model_filepath="my_model.keras.h5",
filepath_or_buffer="demo_ml_keras*")
You can load the trained Keras model using the load_model()
function:
>>> from keras.models import load_model
>>> trained_model = load_model("demo_ml_keras_trained_model.keras.h5")
Keras models support incremental learning and thus are suitable for larger-than-memory datasets.
XGBoost
XGBoost provides a popular implementation of gradient boosted trees. XGBoost provides wrappers with a scikit-learn-compatible API, which can be used with QuantRocket:
>>> from xgboost import XGBRegressor
>>> import joblib
>>> regr = XGBRegressor()
>>> joblib.dump(regr, "xgb_model.joblib")
Decision tree algorithms like XGBoost require loading the entire dataset into memory. Although XGBoost supports distributing a dataset across a cluster, this functionality isn't currently supported by QuantRocket. To use XGBoost on a large amount of data, launch a cloud server that is large enough to hold the data in memory.
Data preprocessing
Feature standardization
Many machine learning algorithms work best when the features are standardized in some way, for example have comparable scales, zero mean, etc. The first step for properly standardizing your data is to understand your machine learning algorithm and your data. (Check the scikit-learn docs for your algorithm.) Once you know what you want to do, there are generally two different places where you can standardize your features: using scikit-learn or using Pandas.
Using scikit-learn
Scikit-learn provides a variety of transformers to preprocess data before the data are used to fit your estimator. Transformers and estimators can be combined using scikit-learn pipelines. For example, QuantRocket's default model, shown below, preprocesses features using StandardScaler
, which centers the data at 0 and scales to unit variance, before using the data to fit SGDRegressor
:
from sklearn.pipeline import Pipeline
from sklearn.linear_model import SGDRegressor
from sklearn.preprocessing import StandardScaler
model = Pipeline([("scaler", StandardScaler()),
("estimator", SGDRegressor())])
See the scikit-learn user guide to learn more about available transformers.
Using pandas
You can also standardize your features in your prices_to_features
method. For example, you might rank stocks with pct=True
which nicely results in a scale of 0 to 1:
features["winners"] = twelve_month_returns.rank(axis=1, ascending=False, pct=True).fillna(1)
Or if your data has outliers and your model is sensitive to them, you might winsorize them:
features["1d_returns"] = returns.where(returns < 1, 1)
Or re-create the StandardScaler
's behavior yourself by subtracting the mean and scaling to unit variance:
pb_ratios = pb_ratios - pb_ratios.stack().mean()
features["price_to_book"] = pb_ratios / pb_ratios.stack().std()
One-hot encoding
One-hot encoding (aka dummy encoding) is a data preprocessing technique whereby a categorical feature such as stock sectors is converted to multiple features, with each feature containing a boolean 1 or 0 to indicate whether the sample (stock) belongs to the category (sector). One-hot encoding is a necessary step for using categorical data with machine learning. The snippet below illustrates the before and after of one-hot encoding:
>>> sectors
Sector
Stock
AAPL Technology
BAC Financial
>>> sectors.Sector.str.get_dummies()
Financial Technology
Stock
AAPL 0 1
BAC 1 0
To one-hot encode a Series, you can use pandas get_dummies()
method as shown above, but this isn't suitable for DataFrames. To one-hot encode a categorical feature such as sector when working with a DataFrame, loop through the sectors and add a feature per sector as shown below:
from quantrocket.master import get_securities_reindexed_like
closes = prices.loc["Close"]
securities = get_securities_reindexed_like(closes, fields="sharadar_Sector")
sectors = securities.loc["sharadar_Sector"]
features = {}
for sector in sectors.stack().unique():
features[sector] = (sectors == sector).astype(int)
Handling of NaNs
Most machine learning models do not handle NaNs, which therefore must be removed or replaced. If your features DataFrames contain any NaNs, QuantRocket replaces the NaNs with 0 before providing the data to your model. Sometimes this behavior might not be suitable; for example, if ranking stocks on a scale of 0 to 1 using pct=True
, 0 implies having the best rank, which is probably not what you want. In these cases you should fill your own NaNs:
features["winners"] = twelve_month_returns.rank(axis=1, ascending=False, pct=True).fillna(1)
Unlike features DataFrames, if there are NaNs in your targets DataFrame, they are not filled. Rather, the NaN targets and their corresponding features are dropped and thus excluded from model training.
Incremental vs non-incremental learning
To avoid overfitting, it is often desirable to train machine learning models with large amounts of data. Depending on your computer specs, this data might not fit in memory.
A subset of machine learning algorithms supports incremental learning, also known as out-of-core learning, meaning they can be trained on small, successive batches of data without the need to load the entire dataset into memory. Other machine learning algorithms cannot learn incrementally as they require seeing the complete dataset, which therefore must be loaded into memory in its entirety.
The following table summarizes the pros and cons of incremental and non-incremental algorithms:
| Incremental algorithms | Non-incremental algorithms |
---|
memory requirements | low due to loading dataset in batches | high due to loading entire dataset |
runtime | faster due to loading less data | slower due to loading more data |
supports rolling windows | no | yes |
Incremental algorithms
Algorithms that support incremental learning include:
- the default model, scikit-learn's
SGDRegressor
(linear regression with Stochastic Gradient Descent) - other scikit-learn algorithms that implement a
partial_fit
method. See the full list. - Keras + TensorFlow neural networks
Algorithms that do not support incremental learning include:
- Decision trees
- scikit-learn algorithms not included in the above list
- XGBoost
Memory and runtime
For an expanding walk-forward optimization with a 3-year initial training window and annual retraining, the following table shows the sequence of training periods for an incremental vs non-incremental learning algorithm:
iteration | training period (incremental) | training period (non-incremental) |
---|
1 | 2006-2009 | 2006-2009 |
2 | 2010 | 2006-2010 |
3 | 2011 | 2006-2011 |
... | ... | ... |
10 | 2018 | 2006-2018 |
The non-incremental algorithm must be trained from scratch at each iteration and thus must load more and more data as the simulation progresses, eventually loading the entire dataset. Moreover, the runtime is slower because many periods of data must be reloaded again and again (for example 2006 data is loaded in every iteration).
In contrast, the incremental algorithm is not re-trained from scratch at each iteration but is simply updated with the latest year of data, resulting in much lower memory usage and a faster runtime.
Sub-segmentation of incremental learning
Sometimes your dataset might be too large for your training periods, even with incremental learning. This can especially be true for the initial training period when you specify a longer value for min_train
.
You can use the segment
parameter to further limit the amount of data loaded into memory. The following example specifies annual model training (train="Y"
) with 4 years of initial training (min_train="4Y"
), but the segment
parameter ensures that the 4 years of initial training will only be loaded 1 year at a time:
>>> ml_walkforward("demo-ml",
start_date="2006-01-01", end_date="2012-12-31",
train="Y",
min_train="4Y",
segment="Y",
filepath_or_buffer="demo_ml*")
Alternatively, the following example would retrain annually but only load 1 quarter of data at a time:
>>> ml_walkforward("demo-ml",
start_date="2006-01-01", end_date="2012-12-31",
train="Y",
segment="Q",
filepath_or_buffer="demo_ml*")
The segment
parameter might seem redundant with the train
parameter: why not simply use train="Q"
to load quarterly data? Consider that the segment
parameter is a purely technical parameter that exists solely for the purpose of controlling memory usage. Meanwhile the train
and min_train
parameters, though they do affect memory usage, also express a strategic decision by the trader as to how often the model should be updated. The segment
parameter allows this strategic decision to be separated from the purely technical constraint of available memory.
Rolling optimization support
Incremental algorithms do not support rolling windows. This is because incremental learning updates a model's earlier training with new training but does not expunge the earlier training, as would be required for a rolling optimization. To using a rolling window with an incremental algorithm, you must force the algorithm to run non-incrementally (which will load the entire dataset):
>>> ml_walkforward("demo-ml",
start_date="2006-01-01", end_date="2012-12-31",
train="Y", rolling_train="4Y",
force_nonincremental=True,
filepath_or_buffer="demo_ml*")
Live trading
Live trading a MoonshotML machine learning strategy is nearly identical to live trading a standard Moonshot strategy. The only special requirement is that you must indicate which trained model to use with the strategy.
To do so, save the trained model from your walk-forward optimization to any location in or under the /codeload
directory. (Including a date or version number in the filename is a good idea.) Then, specify the full path to the model file in your MoonshotML strategy:
class DemoMLStrategy(MoonshotML):
CODE = "demo-ml"
DB = "demo-stk-1d"
MODEL = "/codeload/demo_ml_trained_model_20190101.joblib"
Then trade the strategy like any other:
$ quantrocket moonshot trade 'demo-ml' | quantrocket blotter order -f '-'
Periodically update the model based on your training interval. For example, if your walk-forward optimization used annual training (train="Y"
), you should re-run the walk-forward optimization annually to generate an updated model file, then reference this new model file in your MoonshotML strategy.
Zipline
Zipline is an open-source backtester that was originally developed by Quantopian, a crowd-sourced hedge fund that closed in 2020. QuantRocket provides a customized version of Zipline which supports live trading and the use of QuantRocket datasets.
If you're new to Zipline, the
Zipline Intro in the Code Library provides a hands-on introduction to the major components of Zipline and is the best place to start. Then, return to the Usage Guide to go deeper.
Differences from Quantopian
For users with previous experience writing algorithms on Quantopian.com, the main differences between Quantopian and Zipline are indicated below.
Import from zipline
Functions that were imported from quantopian
on Quantopian.com should be imported from zipline
:
from quantopian.pipeline import Pipeline
from zipline.pipeline import Pipeline
If you used the following convention in your Quantopian algorithms to access API functions via algo
:
import quantopian.algorithm as algo
algo.schedule_function(...)
You can modify it for Zipline as shown:
import zipline.api as algo
algo.schedule_function(...)
Unavailable imports
Some APIs that were available on Quantopian.com are not part of the open-source Zipline package. This includes the Optimize API (quantopian.optimize
and quantopian.algorithm.order_optimal_portfolio
). In addition, none of the datasets available on Quantopian.com are part of the open-source Zipline library. Thus these imports will also be unavailable (for example quantopian.pipeline.data.factset
). Instead, use QuantRocket data as documented below.
Quantopian's Research API (quantopian.research
) is not part of the open-source package, but QuantRocket provides its own Zipline research API.
QTradableStocksUS
The QTradableStocksUS
universe, described in this archived Quantopian forum post , is not part of the open-source Zipline package. However, code to replicate the universe is provided in Lesson 12 of the Pipeline tutorial in the Code Library.
Default time in force
All orders in backtesting and live trading are submitted as day orders which cancel at the end of the trading session. This differs from Quantopian.com which simulated good-till-canceled orders.
To modify the order cancellation policy, see the API Reference.
Zipline sids
When working with a Zipline Asset
, Asset.sid
contains an internal integer sid used by Zipline while Asset.real_sid
contains the QuantRocket sid.
Background: In Zipline, sids (security IDs) are required to be integers, while QuantRocket sids are alphanumeric. To accommodate this discrepancy, QuantRocket assigns each security an integer sid during the initial data ingestion and maintains a mapping of Zipline sids to QuantRocket sids throughout the life of the bundle.
Default commissions and slippage
Commissions and slippage are disabled by default. This differs from the behavior on Quantopian where commissions and slippage were enabled by default with certain assumptions. We have disabled them because commissions and slippage can differ drastically by broker and trading strategy, so it is better for traders to set them explicitly based on their particular circumstances.
To enable commissions and/or slippage, see the comissions and slippage section below.
Data bundles
Zipline stores data in a custom database format. Each Zipline database is referred to as a "data bundle." Collecting data into a data bundle is referred to as "ingesting" the data.
QuantRocket provides several prefabricated bundles and also supports creating bundles from history databases.
The API for ingesting data into Zipline bundles mirrors the API for collecting data into history databases.
US Stock minute bundle
The US Stock data bundle is available to all QuantRocket customers and provides 1-minute intraday historical prices as well as daily prices, with history back to 2007.
The US Stock bundle can be used inside or outside of Zipline and is documented in the historical data section.
Sharadar bundle
The Sharadar data bundle provides end-of-day historical prices for US stocks and ETFs, with history back to 1998.
The Sharadar bundle can be used inside or outside of Zipline and is documented in the historical data section.
Sharadar fundamental datasets are separate from the bundle and can be accessed via Pipeline.
History db bundle
Zipline bundles can also be created from history databases (or real-time aggregate databases). This approach works as follows:
- Create a history database and collect the historical data.
- Define a data bundle tied to the history database.
- Ingest data from the history database into the Zipline bundle.
- To keep the bundle current, collect updated data in the history database, then ingest the updated history.
You can ingest 1-day or 1-minute history databases (the two bar sizes Zipline supports). Suppose you have already collected 1-minute bars for crude oil futures, like this:
$
$ quantrocket master collect-ibkr --exchanges 'NYMEX' --symbols 'CL' --sec-types 'FUT'
status: the IBKR listing details will be collected asynchronously
$
$ quantrocket master get -e 'NYMEX' -s 'CL' | quantrocket master universe 'cl-fut' -f -
code: cl-fut
inserted: 140
provided: 140
total_after_insert: 140
$
$ quantrocket history create-ibkr-db 'cl-fut-1min' -u 'cl-fut' -z '1 min' --shard 'sid'
status: successfully created quantrocket.v2.history.cl-fut-1min.sqlite
$ quantrocket history collect 'cl-fut-1min'
status: the historical data will be collected asynchronously
You can create a bundle tied to the history database. To avoid confusion, it's best to name the bundle differently from the source database:
$ quantrocket zipline create-bundle-from-db 'cl-fut-1min-bundle' --from-db 'cl-fut-1min' --calendar 'us_futures' --start-date '2015-01-01'
msg: successfully created cl-fut-1min-bundle bundle
status: success
>>> from quantrocket.zipline import create_bundle_from_db
>>> create_bundle_from_db("cl-fut-1min-bundle", from_db="cl-fut-1min", calendar="us_futures", start_date="2015-01-01")
{'status': 'success', 'msg': 'successfully created cl-fut-1min-bundle bundle'}
$ curl -X PUT 'http://houston/zipline/bundles/cl-fut-1min-bundle?ingest_type=from_db&from_db=cl-fut-1min&calendar=us_futures&start_date=2015-01-01'
{"status": "success", "msg": "successfully created cl-fut-1min-bundle bundle"}
A bundle can optionally be derived from multiple source databases, as long as all the source databases have the same bar size and fields:
$ quantrocket zipline create-bundle-from-db 'fut-1min-bundle' --from-db 'cl-fut-1min' 'es-fut-1min' --calendar 'us_futures' --start-date '2015-01-01'
msg: successfully created fut-1min-bundle bundle
status: success
>>> create_bundle_from_db("fut-1min-bundle", from_db=["cl-fut-1min", "es-fut-1min"], calendar="us_futures", start_date="2015-01-01")
{'status': 'success', 'msg': 'successfully created fut-1min-bundle bundle'}
$ curl -X PUT 'http://houston/zipline/bundles/fut-1min-bundle?ingest_type=from_db&from_db=cl-fut-1min&from_db=es-fut-1min&calendar=us_futures&start_date=2015-01-01'
{"status": "success", "msg": "successfully created fut-1min-bundle bundle"}
It's important to specify the correct trading calendar for your data, using the calendar
parameter. Available calendars are described in the scheduling section. You can also pass any invalid value such as "?" to see all available choices:
$ quantrocket zipline create-bundle-from-db 'cl-fut-1min-bundle' --from-db 'cl-fut-1min' --calendar '?' --start-date '2015-01-01'
msg: 'unknown calendar ?, choices are: 24/5, 24/7, AEB, AMEX, ARCA, ARCX, ASEX, ASX,
BATS, BM, BMF, BUX, BVL, BVME, BVMF, CBOE, CBOT, CFE, CME, CMES, COMEX, EBS, ENEXT,
ENEXT.BE, FWB, ICE, ICEUS, IEPA, IEX, JKT, KSE, LSE, MEXI, MOEX, NASDAQ,
NYFE, NYMEX, NYSE, OSE, OTCB, OTCM, OTCQ, PINK, PINX, PSGM, SBF, SEHK, SEHKNTL,
SEHKSZSE, SFB, SGX, TSE, TSEJ, TSX, VSE, WSE, XAMS, XASE, XASX, XBKK, XBOG, XBOM,
XBRU, XBUD, XBUE, XCBF, XCSE, XDUB, XFRA, XHEL, XHKG, XICE, XIDX, XIST, XJSE, XKAR,
XKLS, XKRX, XLIM, XLIS, XLON, XMAD, XMEX, XMIL, XMOS, XNAS, XNYS, XNZE, XOSL, XPAR,
XPHS, XPRA, XSES, XSGO, XSHG, XSTO, XSWX, XTAI, XTKS, XTSE, XWAR, XWBO, us_futures'
status: error
>>> create_bundle_from_db("cl-fut-1min-bundle", from_db="cl-fut-1min", calendar="?", start_date="2015-01-01")
HTTPError: ('400 Client Error: BAD REQUEST for url: http://houston/zipline/bundles/cl-fut-1min-bundle2?ingest_type=from_db&from_db=cl-fut-1min&calendar=%3F', {'status': 'error', 'msg': 'unknown calendar ?, choices are: 24/5, 24/7, AEB, AMEX, ARCA, ARCX, ASEX, ASX, BATS, BM, BMF, BUX, BVL, BVME, BVMF, CBOE, CBOT, CFE, CME, CMES, COMEX, EBS, ENEXT, ENEXT.BE, FWB, ICE, ICEUS, IEPA, IEX, JKT, KSE, LSE, MEXI, MOEX, NASDAQ, NYFE, NYMEX, NYSE, OSE, OTCB, OTCM, OTCQ, PINK, PINX, PSGM, SBF, SEHK, SEHKNTL, SEHKSZSE, SFB, SGX, TSE, TSEJ, TSX, VSE, WSE, XAMS, XASE, XASX, XBKK, XBOG, XBOM, XBRU, XBUD, XBUE, XCBF, XCSE, XDUB, XFRA, XHEL, XHKG, XICE, XIDX, XIST, XJSE, XKAR, XKLS, XKRX, XLIM, XLIS, XLON, XMAD, XMEX, XMIL, XMOS, XNAS, XNYS, XNZE, XOSL, XPAR, XPHS, XPRA, XSES, XSGO, XSHG, XSTO, XSWX, XTAI, XTKS, XTSE, XWAR, XWBO, us_futures'})
$ curl -X PUT 'http://houston/zipline/bundles/cl-fut-1min-bundle?ingest_type=from_db&from_db=cl-fut-1min&calendar=%3F&start_date=2015-01-01'
{"status": "error", "msg": "unknown calendar ?, choices are: 24/5, 24/7, AEB, AMEX, ARCA, ARCX, ASEX, ASX, BATS, BM, BMF, BUX, BVL, BVME, BVMF, CBOE, CBOT, CFE, CME, CMES, COMEX, EBS, ENEXT, ENEXT.BE, FWB, ICE, ICEUS, IEPA, IEX, JKT, KSE, LSE, MEXI, MOEX, NASDAQ, NYFE, NYMEX, NYSE, OSE, OTCB, OTCM, OTCQ, PINK, PINX, PSGM, SBF, SEHK, SEHKNTL, SEHKSZSE, SFB, SGX, TSE, TSEJ, TSX, VSE, WSE, XAMS, XASE, XASX, XBKK, XBOG, XBOM, XBRU, XBUD, XBUE, XCBF, XCSE, XDUB, XFRA, XHEL, XHKG, XICE, XIDX, XIST, XJSE, XKAR, XKLS, XKRX, XLIM, XLIS, XLON, XMAD, XMEX, XMIL, XMOS, XNAS, XNYS, XNZE, XOSL, XPAR, XPHS, XPRA, XSES, XSGO, XSHG, XSTO, XSWX, XTAI, XTKS, XTSE, XWAR, XWBO, us_futures"}
The --start-date/start_date
parameter is required and should be set to the approximate start date of the source database (unless you prefer a later start date). Only data on or after the date you specify will be ingested. This date also becomes the default start date for backtests and queries that use this bundle.
You can optionally ingest a subset of the history database, filtering by date range, universe, or sid. See the API Reference.
Then, ingest the data:
$ quantrocket zipline ingest 'cl-fut-1min-bundle'
status: the data will be ingested asynchronously
>>> from quantrocket.zipline import ingest_bundle
>>> ingest_bundle("cl-fut-1min-bundle")
{'status': 'the data will be ingested asynchronously'}
$ curl -X POST 'http://houston/zipline/ingestions/cl-fut-1min-bundle'
{"status": "the data will be ingested asynchronously"}
Monitor flightlog for completion status:
quantrocket.zipline: INFO [cl-fut-1min-bundle] Ingesting cl-fut-1min-bundle bundle
quantrocket.zipline: INFO [cl-fut-1min-bundle] Ingested 10980105 total records for 72 total securities in cl-fut-1min-bundle bundle
To update the bundle with new data after updating the underlying history database, simply run the ingestion again:
$ quantrocket zipline ingest 'cl-fut-1min-bundle'
status: the data will be ingested asynchronously
>>> ingest_bundle("cl-fut-1min-bundle")
{'status': 'the data will be ingested asynchronously'}
$ curl -X POST 'http://houston/zipline/ingestions/cl-fut-1min-bundle'
{"status": "the data will be ingested asynchronously"}
For minute databases, if you ingest data again at a later time, only new data will be ingested, resulting in a faster runtime. To detect price adjustments such as splits or dividends that may have occurred in the source database after the initial ingestion, QuantRocket will request a small amount of overlapping data from the history database and compare it with the equivalently-timestamped data stored in the bundle. If the prices differ, this indicates a change in the source database for that security, in which case QuantRocket will delete the bundle data for that particular security and re-ingest the entire history from the source database, in order to make sure the bundle stays synced with the source database.
For daily databases, the entire database is re-ingested each time.
Manage bundles
You can list your bundles. The boolean output indicates whether any data has been ingested into the bundle yet:
$ quantrocket zipline list-bundles
cl-fut-1min-bundle: true
usstock-1min: true
>>> from quantrocket.zipline import list_bundles
>>> list_bundles()
{'usstock-1min': True,
'cl-fut-1min-bundle': True}
$ curl -X GET 'http://houston/zipline/bundles'
{"usstock-1min": true, "cl-fut-1min-bundle": true}
And you can delete a bundle:
$ quantrocket zipline drop-bundle 'usstock-1min' --confirm-by-typing-bundle-code-again 'usstock-1min'
status: deleted usstock-1min bundle
>>> from quantrocket.zipline import drop_bundle
>>> drop_bundle("usstock-1min", confirm_by_typing_bundle_code_again="usstock-1min")
{'status': 'deleted usstock-1min bundle'}
$ curl -X DELETE 'http://houston/zipline/bundles/usstock-1min?confirm_by_typing_bundle_code_again=usstock-1min'
{"status": "deleted usstock-1min bundle"}
Large bundles can take considerable time to delete, due to the use of highly numerous small files in Zipline's storage format. Monitor the detailed logs to track deletion progress.
Default bundle
If you primarily use a single bundle for research and backtesting, you can set it as the default bundle for convenience:
$ quantrocket zipline default-bundle 'usstock-1min'
status: successfully set default bundle
>>> from quantrocket.zipline import set_default_bundle
>>> set_default_bundle("usstock-1min")
{'status': 'successfully set default bundle'}
$ curl -X PUT 'http://houston/zipline/config' -d 'default_bundle=usstock-1min'
{"status": "successfully set default bundle"}
You can check the currently set default bundle:
$ quantrocket zipline default-bundle
default_bundle: usstock-1min
>>> from quantrocket.zipline import get_default_bundle
>>> get_default_bundle()
{'default_bundle': 'usstock-1min'}
$ curl -X GET 'http://houston/zipline/config'
{"default_bundle": "usstock-1min"}
Whenever you backtest or trade a Zipline strategy without specifying a bundle, the default bundle will be used. You can selectively override this by specifying a different bundle at the time of backtesting or trading.
Query bundle
In addition to accessing bundle data from within a Zipline strategy, you can also query bundle data directly. You can query daily data from a daily bundle, and you can query daily or minute data from a minute bundle.
The most convenient way to load bundle data into Python is using the get_prices
function, which parses the data into a Pandas DataFrame and also works for history databases and real-time aggregate databases in addition to Zipline bundles. This function is outlined in the Research section.
Alternatively, for a more raw approach, you can download a CSV file of bundle data:
$ quantrocket zipline get 'usstock-1min' --sids 'FIBBG000B9XRY4' 'FIBBG000BKZB36' --start-date '2020-04-06' --end-date '2020-04-06' --times '09:31:00' '09:32:00' | csvlook
| Field | Date | FIBBG000B9XRY4 | FIBBG000BKZB36 |
| ------ | ------------------------- | -------------- | -------------- |
| Close | 2020-04-06 09:31:00-04:00 | 250.780 | 186.635 |
| Close | 2020-04-06 09:32:00-04:00 | 250.330 | 185.730 |
| High | 2020-04-06 09:31:00-04:00 | 251.535 | 187.425 |
| High | 2020-04-06 09:32:00-04:00 | 250.960 | 186.940 |
| Low | 2020-04-06 09:31:00-04:00 | 250.560 | 186.120 |
| Low | 2020-04-06 09:32:00-04:00 | 250.200 | 185.127 |
| Open | 2020-04-06 09:31:00-04:00 | 250.850 | 186.650 |
| Open | 2020-04-06 09:32:00-04:00 | 250.689 | 186.640 |
| Volume | 2020-04-06 09:31:00-04:00 | 221,336.000 | 29,524.000 |
| Volume | 2020-04-06 09:32:00-04:00 | 185,522.000 | 23,366.000 |
>>> from quantrocket.zipline import download_bundle_file
>>> download_bundle_file("usstock-1min",
sids=["FIBBG000B9XRY4", "FIBBG000BKZB36"],
start_date="2020-04-06", end_date="2020-04-06",
times=["09:31:00", "09:32:00"],
filepath_or_buffer="minute_prices.csv")
>>> prices = pd.read_csv("minute_prices.csv", parse_dates=["Date"], index_col=["Field","Date"])
>>> prices.head()
FIBBG000B9XRY4 FIBBG000BKZB36
Field Date
Close 2020-04-06 09:31:00-04:00 250.780 186.635
2020-04-06 09:32:00-04:00 250.330 185.730
High 2020-04-06 09:31:00-04:00 251.535 187.425
2020-04-06 09:32:00-04:00 250.960 186.940
Low 2020-04-06 09:31:00-04:00 250.560 186.120
$ curl -X GET 'http://houston/zipline/bundles/data/usstock-1min.csv?start_date=2020-04-06&end_date=2020-04-06&sids=FIBBG000B9XRY4&sids=FIBBG000BKZB36×=09%3A31%3A00×=09%3A32%3A00' | csvlook
| Field | Date | FIBBG000B9XRY4 | FIBBG000BKZB36 |
| ------ | ------------------------- | -------------- | -------------- |
| Close | 2020-04-06 09:31:00-04:00 | 250.780 | 186.635 |
| Close | 2020-04-06 09:32:00-04:00 | 250.330 | 185.730 |
| High | 2020-04-06 09:31:00-04:00 | 251.535 | 187.425 |
| High | 2020-04-06 09:32:00-04:00 | 250.960 | 186.940 |
| Low | 2020-04-06 09:31:00-04:00 | 250.560 | 186.120 |
| Low | 2020-04-06 09:32:00-04:00 | 250.200 | 185.127 |
| Open | 2020-04-06 09:31:00-04:00 | 250.850 | 186.650 |
| Open | 2020-04-06 09:32:00-04:00 | 250.689 | 186.640 |
| Volume | 2020-04-06 09:31:00-04:00 | 221,336.000 | 29,524.000 |
| Volume | 2020-04-06 09:32:00-04:00 | 185,522.000 | 23,366.000 |
By default, the data returned from a minute bundle will be in minute frequency. Alternatively, you can query daily data from a minute bundle by using the --data-frequency
/data_frequency
parameter:
$ quantrocket zipline get 'usstock-1min' --data-frequency 'daily' --sids 'FIBBG000B9XRY4' 'FIBBG000BKZB36' --start-date '2020-04-06' --end-date '2020-04-06' | csvlook
| Field | Date | FIBBG000B9XRY4 | FIBBG000BKZB36 |
| ------ | ---------- | -------------- | -------------- |
| Close | 2020-04-06 | 262.47 | 191.330 |
| High | 2020-04-06 | 263.11 | 192.410 |
| Low | 2020-04-06 | 249.38 | 185.127 |
| Open | 2020-04-06 | 250.90 | 188.000 |
| Volume | 2020-04-06 | 50,455,071.00 | 7,582,690.000 |
>>> from quantrocket.zipline import download_bundle_file
>>> download_bundle_file("usstock-1min",
data_frequency="daily",
sids=["FIBBG000B9XRY4", "FIBBG000BKZB36"],
start_date="2020-04-06", end_date="2020-04-06",
filepath_or_buffer="daily_prices.csv")
>>> prices = pd.read_csv("daily_prices.csv", parse_dates=["Date"], index_col=["Field","Date"])
>>> prices.head()
FIBBG000B9XRY4 FIBBG000BKZB36
Field Date
Close 2020-04-06 262.47 191.330
High 2020-04-06 263.11 192.410
Low 2020-04-06 249.38 185.127
Open 2020-04-06 250.90 188.000
Volume 2020-04-06 50455071.00 7582690.000
$ curl -X GET 'http://houston/zipline/bundles/data/usstock-1min.csv?start_date=2020-04-06&end_date=2020-04-06&sids=FIBBG000B9XRY4&sids=FIBBG000BKZB36&data_frequency=daily' | csvlook
| Field | Date | FIBBG000B9XRY4 | FIBBG000BKZB36 |
| ------ | ---------- | -------------- | -------------- |
| Close | 2020-04-06 | 262.47 | 191.330 |
| High | 2020-04-06 | 263.11 | 192.410 |
| Low | 2020-04-06 | 249.38 | 185.127 |
| Open | 2020-04-06 | 250.90 | 188.000 |
| Volume | 2020-04-06 | 50,455,071.00 | 7,582,690.000 |
Be sure to use query parameters that will sufficiently limit the size of the query result to fit in memory. QuantRocket doesn't prevent you from trying to load too much data. If you load too much and the query is taking too long,
restart the Zipline service to kill the query.
Custom code for bundles
This is an advanced topic. Most users can ignore this section.
Occasionally, you might need to run custom code before a bundle loads. An example would be if you ingest custom price data whose history predates the default trading_calendars
start date of 1990. To run custom code, create a Python file at /var/lib/quantrocket/zipline/extension.py
. Each time Zipline loads a bundle, it will first load and execute this module, if present. The following example overwrites the CME calendar with an earlier start date; as a result, specifying the 'CME' calendar with your bundle would use this calendar:
import pandas as pd
from trading_calendars import register_calendar_type
from trading_calendars.exchange_calendar_cmes import CMESExchangeCalendar
register_calendar_type(
"CME",
lambda: CMESExchangeCalendar(
start=pd.Timestamp("1970-01-02", tz="UTC")),
force=True
)
Research
QuantRocket's research API for Zipline allows you to develop a substantial portion of your Zipline strategy code within the interactive environment of a JupyterLab notebook or console, before transitioning your code to .py
file to run a full backtest.
All research functions accept a bundle
parameter to indicate the bundle to use; however it is more convenient to set a default bundle. The following examples omit the bundle
parameter and thus assume you have set a default bundle.
Pipeline in Research
For much more detail about the Pipeline API, see the
Pipeline section of the docs.
To run pipelines in a research notebook, define the pipeline just as you would in a Zipline strategy:
>>> from zipline.pipeline import Pipeline
>>> from zipline.pipeline.factors import AverageDollarVolume, Returns
>>>
>>> pipeline = Pipeline(
columns={
"1y_returns": Returns(window_length=252),
},
screen=AverageDollarVolume(window_length=30) > 10e6
)
Then run the pipeline using the run_pipeline
function (API reference):
>>> from zipline.research import run_pipeline
>>> factors = run_pipeline(pipeline, start_date="2017-01-01", end_date="2019-01-01")
>>> factors.head()
1y_returns
2017-01-03 00:00:00+00:00 Equity(FIBBG00B3T3HD3 [AA]) 0.923288
Equity(FIBBG000B9XRY4 [AAPL]) 0.123843
Equity(FIBBG000BKZB36 [HD]) 0.044736
Equity(FIBBG000BMHYD1 [JNJ]) 0.179002
Equity(FIBBG000BFWKC0 [MON]) 0.100381
The resulting DataFrame contains a MultiIndex of (date, asset), where the assets are those that passed the Pipeline screen
(if any) on that date.
The run_pipeline
function is only intended to be used in notebooks. In a Zipline strategy, you access pipeline results one date at a time (through the pipeline_output
function). While working in a notebook, you can get the exact data structure you'll use in a Zipline algorithm by simply selecting a single date like this:
>>> day_factors = factors.xs("2017-01-03")
>>> day_factors.head()
1y_returns
Equity(FIBBG00B3T3HD3 [AA]) 0.923288
Equity(FIBBG000B9XRY4 [AAPL]) 0.123843
Equity(FIBBG000BKZB36 [HD]) 0.044736
Equity(FIBBG000BMHYD1 [JNJ]) 0.179002
Equity(FIBBG000BFWKC0 [MON]) 0.100381
Pipeline data is lagged, which means that the values for a given date represent the prior session's data. For example, the 2022-01-18 pipeline output will contain data from 2022-01-17. A timestamp of 2022-01-18 in pipeline means, "this is the most recent data that would be available to your algorithm at the start of the day on 2022-01-18".
Alphalens
Alphalens is an open-source performance analysis library which pairs well with the Pipeline API. You can use Alphalens early in your research process to determine if your ideas look promising. Alphalens lets you quickly explore whether an alpha factor is predictive, without the added time and complexity of writing an algorithm and running a full backtest.
You can pass a Pipeline
object directly to Alphalens for analysis. One of the columns in your Pipeline
will become the alpha factor that Alphalens analyzes. Start by defining a Pipeline
but don't execute it with run_pipeline
:
>>> from zipline.pipeline import Pipeline
>>> from zipline.pipeline.factors import AverageDollarVolume, Returns
>>> pipeline = Pipeline(
columns={
"1y_returns": Returns(window_length=252),
},
screen=AverageDollarVolume(window_length=30) > 10e6
)
Then pass the pipeline to the Alphalens from_pipeline
function. Alphalens will (1) execute the pipeline, (2) calculate forward returns, (3) group the securities into daily quantiles based on a specified alpha factor in the pipeline output (in this example, the "1y_returns" column), and (4) create a tear sheet analyzing the forward performance of the different quantiles:
>>> import alphalens as al
>>> al.from_pipeline(
pipeline,
start_date="2017-01-01",
end_date="2019-01-01",
bundle="usstock-1min",
factor="1y_returns",
quantiles=5)
)
You'll see a variety of graphs that look something like this:

Large date ranges that span multiple years may contain too much data to fit in memory. In such cases, you can pass a segment
parameter to from_pipeline
. This will run the analysis in segments, and combine the results at the end. For example, the following code will run the analysis in 1-year segments:
>>> al.from_pipeline(
pipeline,
start_date="2010-01-01",
end_date="2022-12-30",
bundle="usstock-1min",
factor="1y_returns",
quantiles=5,
segment="Y")
)
For hands-on examples, see the Alphalens examples in the Code Library, especially the Fundamental Factors tutorial.