From 9c877b574c95e487650b31ba502c40961f9100eb Mon Sep 17 00:00:00 2001 From: Peter Bakker Date: Thu, 19 Mar 2026 11:28:39 +0000 Subject: [PATCH] Add QuantRocket API documentation (14 modules) Complete Python API reference for the QuantRocket algorithmic trading platform covering all major modules: zipline (backtesting/bundles), satellite (script execution), history (historical data), realtime (tick data), master (securities), price (unified queries), blotter (orders/positions), license (API keys), account (balances), fundamental (Sharadar/Brain/IBKR), moonshot (vectorized backtesting), db (database management), flightlog (logging), and countdown (scheduling). Each doc includes: function signatures, parameter types, code examples, and CLI equivalents. Based on QuantRocket v2.11.0.0. --- .../quantrocket/docs/account/python/DOC.md | 88 +++++ .../quantrocket/docs/blotter/python/DOC.md | 128 +++++++ .../quantrocket/docs/countdown/python/DOC.md | 65 ++++ content/quantrocket/docs/db/python/DOC.md | 89 +++++ .../quantrocket/docs/flightlog/python/DOC.md | 80 +++++ .../docs/fundamental/python/DOC.md | 123 +++++++ .../quantrocket/docs/history/python/DOC.md | 161 +++++++++ .../quantrocket/docs/license/python/DOC.md | 84 +++++ content/quantrocket/docs/master/python/DOC.md | 122 +++++++ .../quantrocket/docs/moonshot/python/DOC.md | 99 ++++++ content/quantrocket/docs/price/python/DOC.md | 92 +++++ .../quantrocket/docs/realtime/python/DOC.md | 136 ++++++++ .../quantrocket/docs/satellite/python/DOC.md | 75 ++++ .../quantrocket/docs/zipline/python/DOC.md | 323 ++++++++++++++++++ 14 files changed, 1665 insertions(+) create mode 100644 content/quantrocket/docs/account/python/DOC.md create mode 100644 content/quantrocket/docs/blotter/python/DOC.md create mode 100644 content/quantrocket/docs/countdown/python/DOC.md create mode 100644 content/quantrocket/docs/db/python/DOC.md create mode 100644 content/quantrocket/docs/flightlog/python/DOC.md create mode 100644 content/quantrocket/docs/fundamental/python/DOC.md create mode 100644 content/quantrocket/docs/history/python/DOC.md create mode 100644 content/quantrocket/docs/license/python/DOC.md create mode 100644 content/quantrocket/docs/master/python/DOC.md create mode 100644 content/quantrocket/docs/moonshot/python/DOC.md create mode 100644 content/quantrocket/docs/price/python/DOC.md create mode 100644 content/quantrocket/docs/realtime/python/DOC.md create mode 100644 content/quantrocket/docs/satellite/python/DOC.md create mode 100644 content/quantrocket/docs/zipline/python/DOC.md diff --git a/content/quantrocket/docs/account/python/DOC.md b/content/quantrocket/docs/account/python/DOC.md new file mode 100644 index 00000000..6bc27c57 --- /dev/null +++ b/content/quantrocket/docs/account/python/DOC.md @@ -0,0 +1,88 @@ +--- +name: account +description: "QuantRocket Account module - query account balances, portfolio holdings, and exchange rates" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,account,balance,portfolio,exchange-rates" +--- + +# quantrocket.account + +Query account balances, portfolio holdings, and exchange rates. + +## Import + +```python +from quantrocket.account import ( + download_account_balances, + download_account_portfolio, + download_exchange_rates, +) +``` + +## Account Balances + +```python +from quantrocket.account import download_account_balances + +download_account_balances(filepath_or_buffer="/tmp/balances.csv", latest=True) + +download_account_balances( + filepath_or_buffer="/tmp/balances.csv", + start_date="2024-01-01", + accounts=["DU12345"], + fields=["NetLiquidation", "BuyingPower", "Cushion"], +) + +# Alert if cushion below threshold +download_account_balances( + filepath_or_buffer="/tmp/alert.csv", + below={"Cushion": 0.05}, + latest=True, +) +``` + +**Common fields:** `"NetLiquidation"`, `"BuyingPower"`, `"Cushion"`, `"EquityWithLoanValue"`, `"GrossPositionValue"`, `"MaintMarginReq"`, `"TotalCashValue"`, `"UnrealizedPnL"`, `"RealizedPnL"` (40+ available) + +## Portfolio + +```python +from quantrocket.account import download_account_portfolio + +download_account_portfolio(filepath_or_buffer="/tmp/portfolio.csv") + +download_account_portfolio( + filepath_or_buffer="/tmp/portfolio.csv", + brokers=["alpaca"], + fields=["Position", "MarketValue", "AverageCost", "UnrealizedPnl"], + include_zero=True, +) +``` + +**brokers:** `"alpaca"`, `"ibkr"` + +## Exchange Rates + +```python +from quantrocket.account import download_exchange_rates + +download_exchange_rates(filepath_or_buffer="/tmp/fx.csv", latest=True) +download_exchange_rates( + filepath_or_buffer="/tmp/fx.csv", + start_date="2024-01-01", + base_currencies=["AUD"], + quote_currencies=["USD"], +) +``` + +## CLI Equivalents + +```bash +quantrocket account balance --latest -o balances.csv +quantrocket account portfolio -o portfolio.csv +quantrocket account rates --latest -o fx.csv +``` diff --git a/content/quantrocket/docs/blotter/python/DOC.md b/content/quantrocket/docs/blotter/python/DOC.md new file mode 100644 index 00000000..3844f70d --- /dev/null +++ b/content/quantrocket/docs/blotter/python/DOC.md @@ -0,0 +1,128 @@ +--- +name: blotter +description: "QuantRocket Blotter module - place orders, track positions, cancel orders, download executions, and query PnL" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,blotter,orders,positions,executions,pnl,trading" +--- + +# quantrocket.blotter + +Place and manage orders, track positions and executions, query PnL. + +## Import + +```python +from quantrocket.blotter import ( + place_orders, + cancel_orders, + download_order_statuses, + download_positions, + list_positions, + close_positions, + download_executions, + record_executions, + apply_split, + download_pnl, + read_pnl_csv, +) +``` + +## Place Orders + +```python +from quantrocket.blotter import place_orders + +order_ids = place_orders(orders=[{ + "Sid": "FIBBG000BDTBL9", + "Action": "BUY", # BUY or SELL + "Exchange": "SMART", + "TotalQuantity": 100, + "OrderType": "MKT", # MKT, LMT, STP, etc. + "Tif": "DAY", # DAY, GTC, IOC, OPG + "Account": "DU12345", + "OrderRef": "my-strategy", # tags order for tracking +}]) + +# Limit order +order_ids = place_orders(orders=[{ + "Sid": "FIBBG000BDTBL9", + "Action": "BUY", + "Exchange": "SMART", + "TotalQuantity": 100, + "OrderType": "LMT", + "LmtPrice": 590.50, + "Tif": "DAY", + "Account": "DU12345", + "OrderRef": "my-strategy", +}]) +``` + +**Required fields:** `Sid`, `Action`, `Exchange`, `TotalQuantity`, `OrderType`, `Tif`, `Account`, `OrderRef` + +## Positions + +```python +from quantrocket.blotter import list_positions, download_positions, close_positions + +positions = list_positions(order_refs=["my-strategy"]) +# Returns: [{"Account": "DU12345", "Sid": "...", "Quantity": 100, ...}] + +download_positions(filepath_or_buffer="/tmp/positions.csv", order_refs=["my-strategy"]) +download_positions(filepath_or_buffer="/tmp/broker_pos.csv", view="broker") + +# Generate close orders (does NOT place them) +close_positions(filepath_or_buffer="/tmp/close_orders.csv", order_refs=["my-strategy"]) +``` + +## Orders and Cancellations + +```python +from quantrocket.blotter import download_order_statuses, cancel_orders + +download_order_statuses(filepath_or_buffer="/tmp/orders.csv", order_refs=["my-strategy"]) +download_order_statuses(filepath_or_buffer="/tmp/open.csv", open_orders=True) + +cancel_orders(order_refs=["my-strategy"]) +cancel_orders(sids=["FIBBG000BDTBL9"]) +cancel_orders(cancel_all=True) +``` + +**Order statuses:** `"Submitted"`, `"Filled"`, `"Cancelled"`, `"Error"`, `"Inactive"` + +## Executions and PnL + +```python +from quantrocket.blotter import download_executions, download_pnl, read_pnl_csv + +download_executions(filepath_or_buffer="/tmp/executions.csv", order_refs=["my-strategy"]) + +download_pnl(filepath_or_buffer="/tmp/pnl.csv", order_refs=["my-strategy"]) +download_pnl(filepath_or_buffer="/tmp/pnl.csv", details=True) # detailed +download_pnl(filepath_or_buffer="/tmp/tearsheet.pdf", output="pdf") # PDF tearsheet + +pnl = read_pnl_csv("/tmp/pnl.csv") # MultiIndex (Field, Date) DataFrame +returns = pnl.loc["Return"] +``` + +## Stock Splits + +```python +from quantrocket.blotter import apply_split +apply_split(sid="FIBBG000BDTBL9", old_shares=1, new_shares=4) +``` + +## CLI Equivalents + +```bash +quantrocket blotter order -f orders.csv +quantrocket blotter status --order-refs 'my-strategy' -o statuses.csv +quantrocket blotter cancel --order-refs 'my-strategy' +quantrocket blotter positions --order-refs 'my-strategy' -o positions.csv +quantrocket blotter executions --order-refs 'my-strategy' -o executions.csv +quantrocket blotter pnl --order-refs 'my-strategy' -o pnl.csv +``` diff --git a/content/quantrocket/docs/countdown/python/DOC.md b/content/quantrocket/docs/countdown/python/DOC.md new file mode 100644 index 00000000..8ffa3924 --- /dev/null +++ b/content/quantrocket/docs/countdown/python/DOC.md @@ -0,0 +1,65 @@ +--- +name: countdown +description: "QuantRocket Countdown module - crontab scheduling service timezone management and conditional scheduling" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,countdown,crontab,scheduling,timezone" +--- + +# quantrocket.countdown + +Crontab scheduling service and timezone management. + +## Import + +```python +from quantrocket.countdown import get_timezone, set_timezone +``` + +## Timezone + +```python +from quantrocket.countdown import get_timezone, set_timezone + +tz = get_timezone() +set_timezone("America/New_York") +tz = get_timezone(service="countdown-usa") # specific service +``` + +## Crontab Management + +Crontab is managed via file, not Python API. The countdown service auto-loads the crontab file. + +### Crontab syntax + +```bash +# minute hour day month weekday command + +# Run at 14:30 UTC, Mon-Fri +30 14 * * mon-fri quantrocket satellite exec 'mypackage.mymodule.my_function' + +# Conditional: only if NYSE is open +0 14 * * mon-fri quantrocket master isopen 'XNYS' && quantrocket satellite exec 'mypackage.run' + +# Conditional: only if NYSE will be open in 30 minutes +30 9 * * mon-fri quantrocket master isopen 'XNYS' --in '30min' && quantrocket satellite exec 'mypackage.run' +``` + +### Validate + +```bash +quantrocket countdown validate +``` + +## CLI Equivalents + +```bash +quantrocket countdown timezone +quantrocket countdown timezone 'America/New_York' +quantrocket countdown validate +quantrocket countdown crontab +``` diff --git a/content/quantrocket/docs/db/python/DOC.md b/content/quantrocket/docs/db/python/DOC.md new file mode 100644 index 00000000..237ec0bd --- /dev/null +++ b/content/quantrocket/docs/db/python/DOC.md @@ -0,0 +1,89 @@ +--- +name: db +description: "QuantRocket DB module - database management, S3 backup/restore, SQLite utilities, and disk space management" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,database,sqlite,s3,backup,restore" +--- + +# quantrocket.db + +Database management: list databases, S3 backup/restore, SQLite utilities. + +## Import + +```python +from quantrocket.db import ( + list_databases, + get_s3_config, + set_s3_config, + s3_push_databases, + s3_pull_databases, + optimize_databases, + connect_sqlite, + insert_or_fail, + insert_or_replace, + insert_or_ignore, +) +``` + +## List Databases + +```python +from quantrocket.db import list_databases + +dbs = list_databases() # {"sqlite": [...], "postgres": [...]} +dbs = list_databases(services=["history"]) # filter by service +dbs = list_databases(detail=True) # include size, path +``` + +## S3 Backup/Restore + +```python +from quantrocket.db import set_s3_config, s3_push_databases, s3_pull_databases + +set_s3_config( + access_key_id="AKIA...", secret_access_key="...", + bucket="my-backups", region="us-east-1", +) + +s3_push_databases() +s3_push_databases(services=["history"], codes=["my-db"]) +s3_pull_databases() +s3_pull_databases(force=True) # overwrite local +``` + +## SQLite Utilities + +```python +from quantrocket.db import connect_sqlite, insert_or_replace, insert_or_ignore +import pandas as pd + +engine = connect_sqlite("/path/to/database.sqlite") # SQLAlchemy engine +df = pd.read_sql("SELECT * FROM my_table LIMIT 10", engine) +insert_or_replace(df, "my_table", engine) +insert_or_ignore(df, "my_table", engine) +``` + +## Optimize + +```python +from quantrocket.db import optimize_databases +optimize_databases() # VACUUM all +optimize_databases(services=["history"]) # specific service +``` + +## CLI Equivalents + +```bash +quantrocket db list +quantrocket db list --services 'history' --detail +quantrocket db s3config --access-key-id 'AKIA...' --bucket 'my-backups' +quantrocket db s3-push +quantrocket db s3-pull --force +quantrocket db optimize +``` diff --git a/content/quantrocket/docs/flightlog/python/DOC.md b/content/quantrocket/docs/flightlog/python/DOC.md new file mode 100644 index 00000000..c971acac --- /dev/null +++ b/content/quantrocket/docs/flightlog/python/DOC.md @@ -0,0 +1,80 @@ +--- +name: flightlog +description: "QuantRocket Flightlog module - logging, log streaming, log file downloads, and message waiting" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,flightlog,logging,monitoring" +--- + +# quantrocket.flightlog + +Logging, log streaming, and log message management. + +## Import + +```python +from quantrocket.flightlog import ( + FlightlogHandler, + stream_logs, + download_logfile, + wait_for_message, + get_timezone, + set_timezone, +) +``` + +## Send Logs from Python + +```python +import logging +from quantrocket.flightlog import FlightlogHandler + +logger = logging.getLogger("my-strategy") +logger.addHandler(FlightlogHandler()) +logger.setLevel(logging.INFO) + +logger.info("Strategy started") +logger.warning("Low liquidity detected") +logger.error("Order rejected") + +# Non-blocking background logging +logger.addHandler(FlightlogHandler(background=True)) +``` + +## Stream and Wait + +```python +from quantrocket.flightlog import stream_logs, wait_for_message + +for line in stream_logs(): # tail -f style + print(line) + +for line in stream_logs(detail=True, hist=100): # last 100 lines with detail + print(line) + +result = wait_for_message("collection complete") # blocking +result = wait_for_message(r"backtest.*finished", regex=True) # regex +result = wait_for_message("done", timeout="30min") # with timeout +``` + +## Download Logs + +```python +from quantrocket.flightlog import download_logfile +download_logfile("/tmp/quantrocket.log") +download_logfile("/tmp/errors.log", match="ERROR") +``` + +## CLI Equivalents + +```bash +quantrocket flightlog stream +quantrocket flightlog stream --detail +quantrocket flightlog get -o quantrocket.log +quantrocket flightlog wait 'collection complete' --timeout '30min' +quantrocket flightlog timezone 'America/New_York' +``` diff --git a/content/quantrocket/docs/fundamental/python/DOC.md b/content/quantrocket/docs/fundamental/python/DOC.md new file mode 100644 index 00000000..6e12c583 --- /dev/null +++ b/content/quantrocket/docs/fundamental/python/DOC.md @@ -0,0 +1,123 @@ +--- +name: fundamental +description: "QuantRocket Fundamental module - Sharadar fundamentals, Brain NLP sentiment, IBKR short sale data, Alpaca ETB" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,fundamental,sharadar,brain,ibkr,alpaca,etb,short-sale" +--- + +# quantrocket.fundamental + +Collect and query fundamental data: Sharadar financials, Brain NLP, IBKR short sale, Alpaca ETB. + +## Import + +```python +from quantrocket.fundamental import ( + # Sharadar Fundamentals + collect_sharadar_fundamentals, + download_sharadar_fundamentals, + get_sharadar_fundamentals_reindexed_like, + # Sharadar S&P 500 + get_sharadar_sp500_reindexed_like, + # Brain NLP + collect_brain_bsi, + get_brain_bsi_reindexed_like, + # IBKR Short Sale + collect_ibkr_shortable_shares, + get_ibkr_shortable_shares_reindexed_like, + get_ibkr_borrow_fees_reindexed_like, + # Alpaca ETB + collect_alpaca_etb, + get_alpaca_etb_reindexed_like, +) +``` + +## Sharadar Fundamentals + +```python +from quantrocket.fundamental import ( + collect_sharadar_fundamentals, + download_sharadar_fundamentals, + get_sharadar_fundamentals_reindexed_like, +) + +collect_sharadar_fundamentals() + +download_sharadar_fundamentals( + filepath_or_buffer="/tmp/fundamentals.csv", + dimensions=["ART"], + fields=["REVENUE", "EPS", "PE", "MARKETCAP", "ROE"], + start_date="2020-01-01", +) + +# In Pipeline research (closes: DataFrame with dates x SIDs) +fundamentals = get_sharadar_fundamentals_reindexed_like( + closes, + fields=["REVENUE", "PE", "ROE"], + dimension="ART", + period_offset=0, # 0 = most recent, -1 = prior period +) +revenue = fundamentals.loc["REVENUE"] +``` + +**Dimensions:** `"ARQ"` (As Reported Quarterly), `"ARY"` (Yearly), `"ART"` (Trailing 12M), `"MRQ"` (Most Recent Quarterly), `"MRY"` (Yearly), `"MRT"` (Trailing 12M) + +**Common fields (100+):** `"REVENUE"`, `"EPS"`, `"EBITDA"`, `"MARKETCAP"`, `"PE"`, `"ROE"`, `"DEBT"`, `"FCF"`, `"NETINC"`, `"GP"`, `"ASSETS"`, `"EQUITY"`, `"DE"`, `"CURRENTRATIO"`, `"DIVYIELD"`, `"BVPS"` + +## Brain NLP Sentiment + +```python +from quantrocket.fundamental import collect_brain_bsi, get_brain_bsi_reindexed_like + +collect_brain_bsi() +sentiment = get_brain_bsi_reindexed_like(closes, N=7, fields=["SENTIMENT_SCORE", "BUZZ"]) +``` + +**N options:** `1`, `7`, or `30` (calculation window in days) + +## IBKR Short Sale Data + +```python +from quantrocket.fundamental import ( + get_ibkr_shortable_shares_reindexed_like, + get_ibkr_borrow_fees_reindexed_like, +) + +shortable = get_ibkr_shortable_shares_reindexed_like( + closes, aggregate=True, + fields=["MinQuantity", "MaxQuantity", "MeanQuantity", "LastQuantity"], +) +fees = get_ibkr_borrow_fees_reindexed_like(closes) +``` + +## Alpaca Easy-to-Borrow + +```python +from quantrocket.fundamental import get_alpaca_etb_reindexed_like + +etb = get_alpaca_etb_reindexed_like(closes) # Boolean DataFrame (True = easy to borrow) +``` + +## Sharadar S&P 500 Membership + +```python +from quantrocket.fundamental import get_sharadar_sp500_reindexed_like + +in_sp500 = get_sharadar_sp500_reindexed_like(closes) # Boolean DataFrame +``` + +## CLI Equivalents + +```bash +quantrocket fundamental collect-sharadar-fundamentals +quantrocket fundamental sharadar-fundamentals \ + --dimensions 'ART' --fields 'REVENUE' 'EPS' 'PE' -o fundamentals.csv +quantrocket fundamental collect-brain-bsi +quantrocket fundamental collect-ibkr-shortable-shares +quantrocket fundamental collect-alpaca-etb +``` diff --git a/content/quantrocket/docs/history/python/DOC.md b/content/quantrocket/docs/history/python/DOC.md new file mode 100644 index 00000000..823bb8ef --- /dev/null +++ b/content/quantrocket/docs/history/python/DOC.md @@ -0,0 +1,161 @@ +--- +name: history +description: "QuantRocket History module - create databases, collect and query historical price data from IBKR, Sharadar, EDI, US Stock" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,history,historical-data,price-data,database" +--- + +# quantrocket.history + +Create, collect, and query historical price data from multiple providers. + +## Import + +```python +from quantrocket.history import ( + create_ibkr_db, + create_usstock_db, + create_sharadar_db, + create_edi_db, + create_custom_db, + collect_history, + get_history_queue, + cancel_collections, + wait_for_collections, + download_history_file, + list_databases, + get_db_config, + drop_db, + list_sids, +) +``` + +## Create History Databases + +### IBKR database + +```python +from quantrocket.history import create_ibkr_db + +# Daily stock data +create_ibkr_db( + "ibkr-stk-1d", + universes=["us-stk"], + bar_size="1 day", + bar_type="ADJUSTED_LAST", + start_date="2007-01-01", +) + +# Minute data with time filter and sharding +create_ibkr_db( + "ibkr-stk-1m", + universes=["us-stk"], + bar_size="1 min", + bar_type="TRADES", + start_date="2023-01-01", + between_times=["09:30:00", "16:00:00"], + shard="sid,time", +) +``` + +**bar_size options:** `"1 secs"`, `"5 secs"`, `"10 secs"`, `"15 secs"`, `"30 secs"`, `"1 min"`, `"2 mins"`, `"3 mins"`, `"5 mins"`, `"10 mins"`, `"15 mins"`, `"20 mins"`, `"30 mins"`, `"1 hour"`, `"2 hours"`, `"3 hours"`, `"4 hours"`, `"8 hours"`, `"1 day"`, `"1 week"`, `"1 month"` + +**bar_type options:** `"TRADES"`, `"ADJUSTED_LAST"`, `"MIDPOINT"`, `"BID"`, `"ASK"`, `"BID_ASK"`, `"HISTORICAL_VOLATILITY"`, `"OPTION_IMPLIED_VOLATILITY"` + +**shard options:** `"year"`, `"month"`, `"day"`, `"time"`, `"sid"`, `"sid,time"`, `"off"` + +### US Stock database + +```python +from quantrocket.history import create_usstock_db +create_usstock_db("usstock-1d", bar_size="1 day") +``` + +### Custom database + +```python +from quantrocket.history import create_custom_db + +create_custom_db( + "my-custom-db", + bar_size="1 day", + columns={"Signal": "float", "Category": "str", "EventDate": "date"}, +) +``` + +**Column types:** `"int"`, `"float"`, `"str"`, `"date"`, `"datetime"` + +## Collect Data + +```python +from quantrocket.history import collect_history, get_history_queue, cancel_collections, wait_for_collections + +collect_history("ibkr-stk-1d") +collect_history("ibkr-stk-1d", start_date="2024-01-01", end_date="2024-12-31") +collect_history("ibkr-stk-1d", priority=True) # jumps the queue +queue = get_history_queue() +result = wait_for_collections("ibkr-stk-1d", timeout="2h") +cancel_collections("ibkr-stk-1d") +``` + +## Download Historical Data + +```python +from quantrocket.history import download_history_file +import pandas as pd +from io import StringIO + +# Download to file +download_history_file( + "my-history-db", + filepath_or_buffer="/tmp/prices.csv", + start_date="2024-01-01", + sids=["FIBBG000BDTBL9"], + fields=["Close", "Volume"], +) + +# Download to DataFrame +f = StringIO() +download_history_file("my-history-db", filepath_or_buffer=f, start_date="2024-01-01") +f.seek(0) +prices = pd.read_csv(f, parse_dates=["Date"]) +``` + +**Parameters:** +- `code` (str, required): Database code +- `filepath_or_buffer` (str or file-like): Output destination +- `start_date`, `end_date` (str): Date range +- `universes`, `sids` (list of str): Filter securities +- `exclude_universes`, `exclude_sids` (list of str): Exclusions +- `times` (list of str): Time filter for intraday data +- `cont_fut` (str): `"concat"` to stitch continuous futures +- `fields` (list of str): Specific fields +- `output` (str): `"csv"` (default) + +## Manage Databases + +```python +from quantrocket.history import list_databases, get_db_config, drop_db, list_sids + +dbs = list_databases() # ["ibkr-stk-1d", "usstock-1d", ...] +config = get_db_config("ibkr-stk-1d") +sids = list_sids("ibkr-stk-1d") +drop_db("old-db", confirm_by_typing_db_code_again="old-db") # IRREVERSIBLE +``` + +## CLI Equivalents + +```bash +quantrocket history create-ibkr-db 'ibkr-stk-1d' \ + --universes 'us-stk' --bar-size '1 day' --bar-type 'ADJUSTED_LAST' \ + --start-date '2007-01-01' +quantrocket history collect 'ibkr-stk-1d' +quantrocket history get 'my-history-db' --start-date '2024-01-01' -o prices.csv +quantrocket history list-databases +quantrocket history queue +``` diff --git a/content/quantrocket/docs/license/python/DOC.md b/content/quantrocket/docs/license/python/DOC.md new file mode 100644 index 00000000..493170b4 --- /dev/null +++ b/content/quantrocket/docs/license/python/DOC.md @@ -0,0 +1,84 @@ +--- +name: license +description: "QuantRocket License module - manage license keys and broker API credentials (Alpaca, Polygon, Quandl)" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,license,api-keys,alpaca,credentials" +--- + +# quantrocket.license + +Manage QuantRocket license and broker API credentials. + +## Import + +```python +from quantrocket.license import ( + get_license_profile, + set_license, + get_alpaca_key, + set_alpaca_key, + get_polygon_key, + set_polygon_key, + get_quandl_key, + set_quandl_key, +) +``` + +## License + +```python +from quantrocket.license import get_license_profile, set_license + +profile = get_license_profile() +profile = get_license_profile(force_refresh=True) +set_license("your-license-key") +``` + +## Alpaca API Keys + +```python +from quantrocket.license import get_alpaca_key, set_alpaca_key + +creds = get_alpaca_key() + +# Paper trading +set_alpaca_key(api_key="PK...", secret_key="...", trading_mode="paper") + +# Live trading +set_alpaca_key(api_key="AK...", secret_key="...", trading_mode="live") + +# With SIP data feed (paid, all exchanges) +set_alpaca_key(api_key="AK...", secret_key="...", trading_mode="live", realtime_data="sip") +``` + +**Parameters:** +- `api_key` (str, required): Alpaca API key +- `trading_mode` (str, required): `"paper"` or `"live"` +- `secret_key` (str): Alpaca secret key +- `realtime_data` (str): `"iex"` (default, free) or `"sip"` (paid) + +## Polygon.io and Quandl + +```python +from quantrocket.license import set_polygon_key, set_quandl_key + +set_polygon_key("your-polygon-api-key") +set_quandl_key("your-quandl-api-key") +``` + +## CLI Equivalents + +```bash +quantrocket license get +quantrocket license set 'YOUR-LICENSE-KEY' +quantrocket license alpaca-key +quantrocket license alpaca-key --api-key 'AK...' --secret-key '...' --live +quantrocket license alpaca-key --api-key 'PK...' --secret-key '...' --paper +quantrocket license polygon-key 'your-polygon-api-key' +quantrocket license quandl-key 'your-quandl-api-key' +``` diff --git a/content/quantrocket/docs/master/python/DOC.md b/content/quantrocket/docs/master/python/DOC.md new file mode 100644 index 00000000..0656387f --- /dev/null +++ b/content/quantrocket/docs/master/python/DOC.md @@ -0,0 +1,122 @@ +--- +name: master +description: "QuantRocket Master module - securities master database, universes, listings, calendars, and security lookups" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,master,securities,universes,listings,calendar" +--- + +# quantrocket.master + +Securities master database: listings, universes, calendars, and security lookups. + +## Import + +```python +from quantrocket.master import ( + get_securities, + get_securities_reindexed_like, + download_master_file, + create_universe, + delete_universe, + list_universes, + collect_ibkr_listings, + collect_alpaca_listings, + collect_usstock_listings, + collect_edi_listings, + collect_figi_listings, + collect_ibkr_option_chains, + list_ibkr_exchanges, + list_calendar_statuses, + collect_ibkr_calendar, + delist_ibkr_security, + create_ibkr_combo, + round_to_tick_sizes, +) +``` + +## Query Securities + +```python +from quantrocket.master import get_securities + +# By symbol, universe, or SID +securities = get_securities(symbols=["SPY", "QQQ", "IWM"]) +securities = get_securities(universes=["us-stk"]) +securities = get_securities(sids=["FIBBG000BDTBL9"]) + +# With filters +securities = get_securities( + exchanges=["XNYS", "XNAS"], + sec_types=["STK"], + exclude_delisted=True, + fields=["Symbol", "Name", "Exchange", "Currency", "SecType"], +) +``` + +**Returns:** DataFrame with SIDs as index. + +**sec_types:** `"STK"`, `"ETF"`, `"FUT"`, `"CASH"`, `"IND"`, `"OPT"`, `"FOP"`, `"BAG"`, `"CFD"` + +**vendors:** `"alpaca"`, `"edi"`, `"ibkr"`, `"sharadar"`, `"usstock"` + +### Aligned to price data + +```python +from quantrocket.master import get_securities_reindexed_like + +# prices: DataFrame with dates as index, SIDs as columns +symbols = get_securities_reindexed_like(prices, fields=["Symbol", "Name"]) +spy_symbols = symbols.loc["Symbol"] # MultiIndex (Field, Date) DataFrame +``` + +## Universes + +```python +from quantrocket.master import create_universe, delete_universe, list_universes + +create_universe("my-universe", sids=["FIBBG000BDTBL9", "FIBBG000BSWKH7"]) +create_universe("my-universe", infilepath_or_buffer="/tmp/sids.csv") +create_universe("combined", from_universes=["us-large", "us-mid"]) +create_universe("my-universe", sids=["FIBBG000CN1S49"], append=True) +create_universe("my-universe", sids=["FIBBG000BDTBL9"], replace=True) +create_universe("active-stocks", from_universes=["us-stk"], exclude_delisted=True) + +universes = list_universes() # {"us-stk": 5000, "my-universe": 3} +delete_universe("old-universe") +``` + +## Exchange Calendars + +```python +from quantrocket.master import list_calendar_statuses + +statuses = list_calendar_statuses(exchanges=["XNYS"], sec_type="STK") +# Returns: {"XNYS": "open"} or {"XNYS": "closed"} + +statuses = list_calendar_statuses(exchanges=["XNYS"], in_="30min") # open in 30 min? +statuses = list_calendar_statuses(exchanges=["XNYS"], ago="1h") # open 1h ago? +``` + +## Collect Listings + +```python +from quantrocket.master import collect_alpaca_listings, collect_ibkr_listings + +collect_alpaca_listings() +collect_ibkr_listings(exchanges=["XNYS", "XNAS"], sec_types=["STK"], currencies=["USD"]) +``` + +## CLI Equivalents + +```bash +quantrocket master get --symbols 'SPY' 'QQQ' -o securities.csv +quantrocket master list-universes +quantrocket master create-universe 'my-universe' -f sids.csv +quantrocket master collect-alpaca-listings +quantrocket master calendar 'XNYS' --sec-type 'STK' +``` diff --git a/content/quantrocket/docs/moonshot/python/DOC.md b/content/quantrocket/docs/moonshot/python/DOC.md new file mode 100644 index 00000000..8eb80f98 --- /dev/null +++ b/content/quantrocket/docs/moonshot/python/DOC.md @@ -0,0 +1,99 @@ +--- +name: moonshot +description: "QuantRocket Moonshot module - vectorized backtesting, parameter scans, ML walkforward optimization" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,moonshot,backtest,vectorized,parameter-scan,ml" +--- + +# quantrocket.moonshot + +Vectorized backtesting framework with parameter scans and ML walkforward. + +## Import + +```python +from quantrocket.moonshot import ( + backtest, + read_moonshot_csv, + scan_parameters, + ml_walkforward, + trade, +) +``` + +## Backtesting + +```python +from quantrocket.moonshot import backtest, read_moonshot_csv + +backtest( + strategies=["my-strategy"], + start_date="2020-01-01", + end_date="2024-12-31", + filepath_or_buffer="/tmp/results.csv", +) + +# Multi-strategy with allocations +backtest( + strategies=["strategy-a", "strategy-b"], + allocations={"strategy-a": 0.6, "strategy-b": 0.4}, + nlv={"USD": 1_000_000}, + filepath_or_buffer="/tmp/results.csv", +) + +# Segmented (reduces memory) +backtest(strategies=["my-strategy"], start_date="2010-01-01", segment="A", + filepath_or_buffer="/tmp/results.csv") + +# PDF tearsheet +backtest(strategies=["my-strategy"], output="pdf", filepath_or_buffer="/tmp/tearsheet.pdf") + +result = read_moonshot_csv("/tmp/results.csv") # MultiIndex (Field, Date) DataFrame +returns = result.loc["Return"] +``` + +## Parameter Scans + +```python +from quantrocket.moonshot import scan_parameters + +scan_parameters( + strategies=["my-strategy"], + start_date="2020-01-01", + param1="LOOKBACK", vals1=["20", "40", "60"], + param2="THRESHOLD", vals2=["0.3", "0.5", "0.7"], + num_workers=4, + filepath_or_buffer="/tmp/scan.csv", +) +``` + +## ML Walkforward + +```python +from quantrocket.moonshot import ml_walkforward + +ml_walkforward( + strategy="my-ml-strategy", + start_date="2015-01-01", + end_date="2024-12-31", + train="3Y", + min_train="2Y", + rolling_train="3Y", + segment="A", + filepath_or_buffer="/tmp/ml_results.csv", +) +``` + +## CLI Equivalents + +```bash +quantrocket moonshot backtest 'my-strategy' --start-date '2020-01-01' -o results.csv +quantrocket moonshot param-scan 'my-strategy' \ + --param1 'LOOKBACK' --vals1 20 40 60 --num-workers 4 -o scan.csv +quantrocket moonshot trade 'my-strategy' -o orders.csv +``` diff --git a/content/quantrocket/docs/price/python/DOC.md b/content/quantrocket/docs/price/python/DOC.md new file mode 100644 index 00000000..14823c28 --- /dev/null +++ b/content/quantrocket/docs/price/python/DOC.md @@ -0,0 +1,92 @@ +--- +name: price +description: "QuantRocket Price module - unified price querying across history databases, real-time databases, and Zipline bundles" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,price,get_prices,data,research" +--- + +# quantrocket.price + +Unified price querying across history databases, real-time aggregate databases, and Zipline bundles. + +## Import + +```python +from quantrocket import get_prices, get_prices_reindexed_like +``` + +## get_prices + +```python +from quantrocket import get_prices + +# Query a single database/bundle +prices = get_prices( + "my-bundle", + start_date="2024-01-01", + end_date="2024-12-31", + sids=["FIBBG000BDTBL9", "FIBBG000BSWKH7"], + fields=["Close", "Volume"], + data_frequency="daily", +) +closes = prices.loc["Close"] # DataFrame: dates x SIDs +volumes = prices.loc["Volume"] + +# Query multiple databases +prices = get_prices( + ["stocks-db", "custom-data-db"], + start_date="2024-01-01", + fields=["Close"], +) + +# Intraday data with timezone +prices = get_prices( + "my-agg-db", + start_date="2024-01-15", + timezone="America/New_York", +) +# Returns: MultiIndex (Field, Date, Time) DataFrame +``` + +**Parameters:** +- `codes` (str or list of str, required): Database/bundle code(s) +- `start_date`, `end_date` (str): YYYY-MM-DD +- `universes`, `sids` (list of str): Filter securities +- `exclude_universes`, `exclude_sids` (list of str): Exclusions +- `times` (list of str): Time filter for intraday (HH:MM:SS) +- `fields` (list of str): `"Open"`, `"High"`, `"Low"`, `"Close"`, `"Volume"` +- `timezone` (str): Timezone for intraday data (e.g., `"America/New_York"`) +- `cont_fut` (str): `"concat"` for continuous futures +- `data_frequency` (str): `"daily"` or `"minute"` + +**Returns:** MultiIndex DataFrame — daily: `(Field, Date)`, intraday: `(Field, Date, Time)`, SIDs as columns + +## get_prices_reindexed_like + +Align prices to another DataFrame's shape — essential for Pipeline-style research. + +```python +from quantrocket import get_prices_reindexed_like + +# closes: DataFrame with dates as index, SIDs as columns +other_prices = get_prices_reindexed_like( + closes, + "my-bundle", + fields=["Close", "Volume"], + shift=1, # shift forward 1 period (avoid lookahead bias) +) +``` + +**Parameters:** +- `reindex_like` (DataFrame, required): Shape template (dates x SIDs) +- `codes` (str or list of str, required): Database/bundle code(s) +- `fields` (list of str): Fields to return +- `shift` (int, default 1): Shift forward by N periods to avoid lookahead bias +- `ffill` (bool, default True): Forward-fill sparse data +- `lookback_window` (int, default 10): Calendar days of back data to load +- `agg` (str or function, default `"last"`): Aggregation for intraday to daily diff --git a/content/quantrocket/docs/realtime/python/DOC.md b/content/quantrocket/docs/realtime/python/DOC.md new file mode 100644 index 00000000..9a3e9e38 --- /dev/null +++ b/content/quantrocket/docs/realtime/python/DOC.md @@ -0,0 +1,136 @@ +--- +name: realtime +description: "QuantRocket Realtime module - create tick databases, collect and query real-time market data from IBKR, Alpaca, Polygon" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,realtime,tick-data,market-data,streaming" +--- + +# quantrocket.realtime + +Create tick databases and collect/query real-time market data. + +## Import + +```python +from quantrocket.realtime import ( + create_ibkr_tick_db, + create_alpaca_tick_db, + create_polygon_tick_db, + create_agg_db, + collect_market_data, + get_active_collections, + cancel_market_data, + download_market_data_file, + list_databases, + get_db_config, + drop_db, + drop_ticks, +) +``` + +## Create Tick Databases + +### Alpaca + +```python +from quantrocket.realtime import create_alpaca_tick_db + +create_alpaca_tick_db( + "alpaca-ticks", + universes=["my-universe"], + fields=["LastPrice", "LastSize", "BidPrice", "AskPrice", "BidSize", "AskSize"], +) +``` + +**Alpaca fields:** `"AskPrice"`, `"AskSize"`, `"BidPrice"`, `"BidSize"`, `"LastPrice"`, `"LastSize"`, `"MinuteClose"`, `"MinuteOpen"`, `"MinuteHigh"`, `"MinuteLow"`, `"MinuteVolume"` + +### IBKR + +```python +from quantrocket.realtime import create_ibkr_tick_db + +create_ibkr_tick_db( + "ibkr-ticks", + universes=["us-stk"], + fields=["LastPrice", "LastSize", "BidPrice", "AskPrice", "Volume"], +) +``` + +**IBKR fields (55+):** `"AskExch"`, `"AskPrice"`, `"AskSize"`, `"BidPrice"`, `"BidSize"`, `"LastPrice"`, `"LastSize"`, `"Volume"`, `"OptionImpliedVol"`, `"OptionCallOpenInterest"`, `"OptionPutOpenInterest"`, and many more. + +### Aggregate database + +```python +from quantrocket.realtime import create_agg_db + +create_agg_db( + "alpaca-1min", + tick_db_code="alpaca-ticks", + bar_size="1m", # Pandas timedelta: "10s", "1m", "5m", "1h", "1d" + fields={ + "LastPrice": ["Close", "Open", "High", "Low"], + "LastSize": ["Sum"], + }, +) +``` + +**Aggregate functions:** `"Close"`, `"Open"`, `"High"`, `"Low"`, `"Mean"`, `"Sum"`, `"Count"` + +## Collect Data + +```python +from quantrocket.realtime import collect_market_data, get_active_collections, cancel_market_data + +collect_market_data("alpaca-ticks") # continuous +collect_market_data("alpaca-ticks", until="2h") # auto-cancel after 2h +collect_market_data("alpaca-ticks", snapshot=True, wait=True) # single snapshot + +active = get_active_collections(detail=True) +# Returns: {"alpaca": {"alpaca-ticks": 14}} + +cancel_market_data("alpaca-ticks") +cancel_market_data(cancel_all=True) +``` + +## Download Data + +```python +from quantrocket.realtime import download_market_data_file + +download_market_data_file( + "alpaca-ticks", + filepath_or_buffer="/tmp/ticks.csv", + start_date="2024-01-15", + sids=["FIBBG000BDTBL9"], +) +``` + +## Manage Databases + +```python +from quantrocket.realtime import list_databases, drop_ticks, drop_db + +dbs = list_databases() # {"alpaca-ticks": ["alpaca-1min"]} +drop_ticks("alpaca-ticks", older_than="7d") +drop_db("old-ticks", confirm_by_typing_db_code_again="old-ticks", cascade=True) +``` + +## CLI Equivalents + +```bash +quantrocket realtime create-alpaca-tick-db 'alpaca-ticks' \ + --universes 'my-universe' --fields 'LastPrice' 'LastSize' +quantrocket realtime collect 'alpaca-ticks' +quantrocket realtime active +quantrocket realtime cancel 'alpaca-ticks' +quantrocket realtime get 'alpaca-ticks' --start-date '2024-01-15' -o ticks.csv +quantrocket realtime create-agg-db 'alpaca-1min' \ + --tick-db 'alpaca-ticks' --bar-size '1m' \ + --fields 'LastPrice:Close,Open,High,Low' 'LastSize:Sum' +quantrocket realtime drop-ticks 'alpaca-ticks' --older-than '7d' +``` diff --git a/content/quantrocket/docs/satellite/python/DOC.md b/content/quantrocket/docs/satellite/python/DOC.md new file mode 100644 index 00000000..5d2ddc06 --- /dev/null +++ b/content/quantrocket/docs/satellite/python/DOC.md @@ -0,0 +1,75 @@ +--- +name: satellite +description: "QuantRocket Satellite module - execute custom Python functions and shell commands on the satellite service" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,satellite,custom-scripts,execution" +--- + +# quantrocket.satellite + +Execute custom Python functions or shell commands on the satellite service. + +## Import + +```python +from quantrocket.satellite import execute_command +``` + +## Execute a Python function + +```python +from quantrocket.satellite import execute_command + +# Execute a Python function (dotted module path) +execute_command("mypackage.mymodule.my_function") + +# Execute with parameters +execute_command( + "mypackage.scripts.run", + params={"start_date": "2024-01-01", "debug": "true"}, +) + +# Execute and retrieve a return file +execute_command( + "mypackage.reports.generate", + return_file="/path/to/output/report.csv", + filepath_or_buffer="/tmp/report.csv", +) +``` + +**Parameters:** +- `cmd` (str, required): Dotted Python path to function (e.g., `"mypackage.module.function"`) +- `return_file` (str): Path to file on satellite to return after execution +- `filepath_or_buffer` (str or file-like): Local destination for return_file +- `params` (dict): Key-value pairs passed to the Python function +- `service` (str): Service name (default `"satellite"`) + +**Returns:** dict (status message) or None (if return_file specified) + +## CLI Equivalents + +```bash +# Execute a Python function +quantrocket satellite exec 'mypackage.mymodule.my_function' + +# Execute with parameters +quantrocket satellite exec 'mypackage.scripts.run' \ + --params 'start_date:2024-01-01' 'debug:true' + +# Execute and retrieve output file +quantrocket satellite exec 'mypackage.reports.generate' \ + --return-file '/path/to/output/report.csv' -o report.csv +``` + +## Notes + +- The function path uses Python dot notation: `package.module.function` +- The satellite service runs from the codeload directory +- Functions must be importable from the satellite container's Python path +- Parameters are passed as string key-value pairs +- Crontab entries use: `quantrocket satellite exec 'dotted.path.to.function'` diff --git a/content/quantrocket/docs/zipline/python/DOC.md b/content/quantrocket/docs/zipline/python/DOC.md new file mode 100644 index 00000000..674c4fce --- /dev/null +++ b/content/quantrocket/docs/zipline/python/DOC.md @@ -0,0 +1,323 @@ +--- +name: zipline +description: "QuantRocket Zipline module - backtesting, bundle management, trading, parameter scans, and data download" +metadata: + languages: "python" + versions: "2.11.0.0" + revision: 1 + updated-on: "2026-03-19" + source: community + tags: "quantrocket,zipline,backtest,bundle,trading,algorithmic-trading,parameter-scan" +--- + +# quantrocket.zipline + +Zipline integration for backtesting, bundle management, and live trading. + +## Import + +```python +from quantrocket.zipline import ( + backtest, + scan_parameters, + trade, + create_bundle_from_db, + create_usstock_bundle, + ingest_bundle, + list_bundles, + get_bundle_config, + download_bundle_file, + drop_bundle, + list_sids, + ZiplineBacktestResult, +) +``` + +## Backtesting + +### Run a backtest + +```python +from quantrocket.zipline import backtest + +backtest( + "my_strategy", # strategy filename (without .py) + bundle="usstock-1min", # data bundle + start_date="2020-01-01", + end_date="2024-12-31", + capital_base=1_000_000, + data_frequency="daily", # "daily" or "minute" + progress="M", # progress: "D", "W", "M", "A" + filepath_or_buffer="/tmp/results.csv", +) + +# With custom parameters +backtest( + "my_strategy", + bundle="usstock-1min", + start_date="2020-01-01", + params={"LOOKBACK": "60", "THRESHOLD": "0.5"}, + filepath_or_buffer="results.csv", +) +``` + +**Parameters:** +- `strategy` (str, required): Strategy filename without .py extension +- `data_frequency` (str): `"daily"` or `"minute"` (or `"d"`, `"m"`). Default is minute +- `capital_base` (float): Starting capital (default 1,000,000) +- `bundle` (str): Data bundle name +- `start_date` (str): YYYY-MM-DD format +- `end_date` (str): YYYY-MM-DD format +- `progress` (str): Pandas offset alias for progress meter (`"D"`, `"W"`, `"M"`, `"A"`) +- `params` (dict): Key-value pairs passed to algorithm as module-level attributes +- `filepath_or_buffer` (str or file-like): Output destination for results CSV + +**Returns:** None (writes CSV to filepath_or_buffer) + +### Parameter scan (scan_parameters) + +**Function name is `scan_parameters()`** — not `param_scan()` or `parameter_scan()`. + +```python +from quantrocket.zipline import scan_parameters + +# 1-D scan: test one parameter across multiple values +scan_parameters( + "my_strategy", + bundle="usstock-1min", + data_frequency="daily", + start_date="2020-01-01", + end_date="2024-12-31", + param1="MAVG_WINDOW", # module-level attribute in algo file + vals1=[20, 50, 100], # int/float/str/tuple/True/False/None/'default' + num_workers=4, + filepath_or_buffer="scan_MAVG_WINDOW.csv", +) + +# 2-D scan: test combinations of two parameters +scan_parameters( + "my_strategy", + bundle="usstock-1min", + data_frequency="daily", + start_date="2020-01-01", + param1="LONG_MAVG", + vals1=[100, 200], + param2="SHORT_MAVG", + vals2=[20, 50], + num_workers=3, + filepath_or_buffer="scan_2d.csv", +) + +# Fix other params while scanning +scan_parameters( + "my_strategy", + bundle="usstock-1min", + start_date="2020-01-01", + param1="LOOKBACK", + vals1=[20, 40, 60], + params={"THRESHOLD": 0.5, "USE_FILTER": True}, # fixed during scan + filepath_or_buffer="scan_with_fixed.csv", +) + +# Use 'default' to include current parameter value in scan +scan_parameters( + "my_strategy", + bundle="usstock-1min", + start_date="2020-01-01", + param1="LOOKBACK", + vals1=[20, 40, "default", 100], # 'default' = current value in algo + filepath_or_buffer="scan_with_default.csv", +) + +# Visualize results +from moonchart import ParamscanTearsheet +ParamscanTearsheet.from_csv("scan_MAVG_WINDOW.csv") +``` + +**Parameters:** +- `strategy` (str, required): Strategy filename without .py extension +- `data_frequency` (str): `"daily"` or `"minute"` (default minute) +- `capital_base` (float): Starting capital (default 1,000,000) +- `bundle` (str): Data bundle name +- `start_date`, `end_date` (str): YYYY-MM-DD +- `param1` (str, required): Name of parameter to test (module-level attribute in algo) +- `vals1` (list, required): Values to test — int, float, str, tuple, True, False, None, `"default"` +- `param2` (str): Second parameter for 2-D scans +- `vals2` (list): Values for second parameter +- `params` (dict): Fix other parameters during the scan +- `num_workers` (int): Parallel workers (default 1). Avoid `progress` with num_workers > 1 +- `progress` (str): Pandas offset alias — messy with parallel workers, not recommended +- `filepath_or_buffer` (str): Output CSV path + +**Returns:** None (writes CSV to filepath_or_buffer) + +### Analyze backtest results + +```python +from quantrocket.zipline import ZiplineBacktestResult + +result = ZiplineBacktestResult.from_csv("results.csv") +returns = result.returns # pd.Series of daily returns +positions = result.positions # pd.DataFrame of positions +transactions = result.transactions # pd.DataFrame of trades +benchmark = result.benchmark_returns # pd.Series of benchmark returns +perf = result.perf # pd.DataFrame of performance metrics +``` + +## Bundle Management + +### Create bundle from history database + +```python +from quantrocket.zipline import create_bundle_from_db + +# Create from a single database +create_bundle_from_db( + "my-bundle", + from_db="my-history-db", + calendar="XNYS", # NYSE calendar + start_date="2007-01-01", + sids=["FIBBG000BDTBL9"], # optional: limit to specific SIDs + universes=["my-universe"], # optional: limit to universe +) + +# Create from multiple databases +create_bundle_from_db( + "combined-bundle", + from_db=["stocks-db", "custom-data-db"], + calendar="XNYS", + start_date="2005-01-01", +) +``` + +**Parameters:** +- `code` (str, required): Bundle name (lowercase, hyphens allowed) +- `from_db` (str or list of str, required): Source database code(s) +- `calendar` (str, required): Trading calendar (e.g., `"XNYS"`, `"XASX"`, `"XCBF"`) +- `start_date` (str): YYYY-MM-DD +- `end_date` (str): YYYY-MM-DD +- `universes` (list of str): Limit to these universes +- `sids` (list of str): Limit to these SIDs +- `exclude_universes`, `exclude_sids` (list of str): Exclusions +- `fields` (dict): Map Zipline fields to database fields + +### Create US stock bundle + +```python +from quantrocket.zipline import create_usstock_bundle + +# Daily data bundle +create_usstock_bundle("usstock-daily", data_frequency="daily") + +# Minute data for specific universe +create_usstock_bundle( + "usstock-minute", + universes=["my-universe"], + data_frequency="minute", +) + +# Free sample data +create_usstock_bundle("usstock-free", free=True) +``` + +### Ingest (refresh) bundle data + +```python +from quantrocket.zipline import ingest_bundle + +ingest_bundle("my-bundle") +ingest_bundle("my-bundle", sids=["FIBBG000BDTBL9"]) # specific SIDs only +``` + +### List and inspect bundles + +```python +from quantrocket.zipline import list_bundles, get_bundle_config, list_sids + +bundles = list_bundles() # {"my-bundle": True, "new-bundle": False} +config = get_bundle_config("my-bundle") +sids = list_sids("my-bundle") +``` + +### Delete a bundle + +```python +from quantrocket.zipline import drop_bundle + +drop_bundle("old-bundle", confirm_by_typing_bundle_code_again="old-bundle") +``` + +## Download Bundle Data + +```python +from quantrocket.zipline import download_bundle_file +import pandas as pd +from io import StringIO + +# Download to file +download_bundle_file( + "my-bundle", + filepath_or_buffer="/tmp/prices.csv", + start_date="2024-01-01", + sids=["FIBBG000BDTBL9"], + fields=["Close", "Volume"], + data_frequency="daily", +) + +# Download to DataFrame +f = StringIO() +download_bundle_file("my-bundle", filepath_or_buffer=f, start_date="2024-01-01") +f.seek(0) +prices = pd.read_csv(f, parse_dates=["Date"]) +``` + +**Parameters:** +- `code` (str, required): Bundle name +- `filepath_or_buffer` (str or file-like): Output destination +- `start_date`, `end_date` (str): Date range filter +- `data_frequency` (str): `"daily"` or `"minute"` +- `universes`, `sids` (list of str): Filter securities +- `exclude_universes`, `exclude_sids` (list of str): Exclusions +- `times` (list of str): Filter by time (HH:MM:SS) for minute data +- `fields` (list of str): `"Open"`, `"High"`, `"Low"`, `"Close"`, `"Volume"` + +## Live Trading + +```python +from quantrocket.zipline import trade, list_active_strategies, cancel_strategies + +trade("my_strategy", bundle="my-bundle", account="DU12345", data_frequency="daily") +trade("my_strategy", bundle="my-bundle", dry_run=True) # no actual orders +active = list_active_strategies() +cancel_strategies(strategies=["my_strategy"]) +cancel_strategies(cancel_all=True) +``` + +## CLI Equivalents + +```bash +# Backtest +quantrocket zipline backtest 'my_strategy' --bundle 'usstock-1min' \ + --start-date '2020-01-01' --end-date '2024-12-31' -o results.csv + +# Parameter scan +quantrocket zipline param-scan 'my_strategy' --bundle 'usstock-1min' \ + --param1 'MAVG_WINDOW' --vals1 20 50 100 --num-workers 4 -o scan.csv + +# Create bundle from database +quantrocket zipline create-db-bundle 'my-bundle' \ + --from-db 'my-history-db' --calendar 'XNYS' --start-date '2007-01-01' + +# Ingest bundle +quantrocket zipline ingest 'my-bundle' + +# List bundles +quantrocket zipline list-bundles + +# Download bundle data +quantrocket zipline get 'my-bundle' --start-date '2024-01-01' \ + --sids 'FIBBG000BDTBL9' -o prices.csv + +# Trade +quantrocket zipline trade 'my_strategy' --bundle 'my-bundle' +```