Skip to main content Switch to mobile version cpz-ai 4.45.1 CPZAI Python SDK — strategy framework, backtest engine, risk guards, execution algorithms, multi-broker trading, and SpiderRock MLink + Liberator data access
pip install cpz-ai==4.45.1 Copy PIP instructions
Strategy Framework, Backtesting Engine, Risk Guards, Execution Algorithms, and Multi-Broker Trading
New in 4.44.0: clean DataFrames for warehouses and Genie
Install python -m pip install --upgrade cpz-ai. The examples below require 4.44.0 or newer. Connect your provider in Data Lab > Integrations. Set CPZ_AI_API_KEY and CPZ_AI_API_SECRET in your environment or secret manager, using a CPZAI key with the data scope. Genie and other connector tools also need simons. Provider credentials stay in your saved connection. Databricks Genie uses OAuth with All APIs selected in the OAuth application.
from cpz import CPZClient client = CPZClient() df = client.warehouses.query( "databricks", "SELECT current_catalog() AS catalog, current_schema() AS schema", limit=10, ) print(df) df is a normal Polars DataFrame with named, typed columns. In a notebook, put df on the last line to display its table. Use snowflake or redshift for those saved providers, and integration_id= to select a connection when you have several.
Queries are read-only. The default returned-row limit is 1,000, configurable up to 50,000; provider limits may be lower. This does not limit the warehouse scan: filter partitions and aggregate in SQL for large tables. Truncated warehouse results emit a warning. df.cpz.response.truncated and .total_rows expose the result limits without adding metadata columns.
query_result() remains available for detailed responses, including .raw and .statement_id. Duplicate SQL column names need aliases. The existing client.data.warehouse.query(...) API remains supported.
Browse connections and tables
print(client.connectors.table()) print(client.warehouses.browse("databricks", "catalogs")) print(client.warehouses.browse("databricks", "schemas", catalog="workspace")) print(client.warehouses.browse("databricks", "tables", catalog="workspace", schema="default")) These methods return DataFrames. A connector table contains only its name, slug and enabled status. Copy the slug for the Genie example below.
Databricks supports catalogs, schemas, tables, columns and warehouses. Snowflake supports databases, schemas, tables and columns; pass database=. Redshift supports schemas and tables; pass schema= to list tables. browse() rejects truncated listings. list_objects() preserves the detailed listing and its limits; list_tables() remains available.
Ask Genie for a table
connector = "YOUR_GENIE_CONNECTOR_SLUG" df = client.genie.query( connector, "Show the five products with the highest total sales, including product name and total sales.", ) print(df) next_df = client.genie.follow_up_query(df, "Show the top ten instead.") print(next_df) Use a question that matches your connected data. Both Genie One and Genie Agent return actual SQL rows as a Polars DataFrame. Follow-ups reuse the conversation automatically; no IDs need to be copied. Keep the original returned frame for follow-ups: Polars transformations such as select() create a new frame without its conversation metadata.
A response with no query table raises IntegrationError; it never turns prose into invented data. If Genie returns several query tables, choose table_index=0 (or another index). Incomplete results raise by default. Explicitly set allow_partial=True only when partial data is acceptable; a warning remains visible. Empty successful queries return a typed empty frame.
Source information stays outside the data columns. When displaying or sharing an answer, show Powered by Genie and the source links alongside the table:
source = df.cpz.attribution print(source["label"]) if source.get("space_url"): print(source["space_url"]) for link in source.get("links", []): print(link) df.cpz.response retains the conversation, readable explanation and attribution. df.cpz.raw retains the original table result for debugging. These fields are absent from the table's printed representation.
Ask for an explanation
answer = client.genie.wait(client.genie.ask(connector, "Explain the columns available in this dataset.")) print(answer.text) follow_up = client.genie.wait(client.genie.follow_up(answer, "Which columns identify the date?")) print(follow_up.text) text contains readable prose without internal protocol comments. raw keeps the unchanged response. Use client.genie.to_polars(answer) if a completed answer includes a query table. Display the answer's attribution alongside prose as well.
query() waits automatically. ask() starts a turn; wait() polls every three seconds for up to five minutes by default. A GenieTimeout retains .response so you can resume with wait(error.response). A timeout does not cancel work. Genie One supports explicit best-effort cancel(response).
report = client.warehouses.export( catalog="workspace", schema="default", table="my_research_export", source={"data_file_id": "YOUR_EXISTING_DATA_LAB_FILE_ID"}, mode="create", method="volume", ) create fails if the table exists. append adds rows; replace overwrites data and must be chosen explicitly. volume stages in a Unity Catalog volume and uses COPY INTO. sql_insert accepts at most 20,000 rows. Inline sources use {"columns": ["column_name"], "rows": [[value]]}. Exports are never retried automatically. On transport failure, inspect the destination before retrying. Inspect report["lineage"] separately when present: export success does not prove lineage publication.
Async and detailed connector access
from cpz import AsyncCPZClient async def query(): client = AsyncCPZClient() return await client.warehouses.query("databricks", "SELECT current_catalog() AS catalog") warehouses, connectors and genie have async mirrors, including genie.query() and follow_up_query(). HTTP work runs in worker threads; cancelling an await does not cancel work already submitted.
For advanced integrations, connectors.list() includes discovered tool schemas, test(id_or_slug) refreshes discovery, and call(id_or_slug, tool, arguments) returns the detailed tool response. Inspect the schema and side effects before invoking a tool. Owner isolation, disabled connections and tool allowlists are enforced server-side. Errors raise rather than becoming empty tables. IntegrationError.status, .request_id and .details provide troubleshooting details separately from normal output.
python -m cpz.examples.integrations --help python -m cpz.examples.integrations connectors python -m cpz.examples.integrations warehouse --provider databricks --sql 'SELECT current_catalog() AS catalog' python -m cpz.examples.integrations browse --provider databricks --level catalogs python -m cpz.examples.integrations genie --connector YOUR_GENIE_CONNECTOR_SLUG --question 'Show the top five products by total sales.' --follow-up 'Show the top ten instead.' python -m cpz.examples.integrations genie --connector YOUR_GENIE_CONNECTOR_SLUG --text --question 'Explain the available datasets.' The examples print tables by default. --text explicitly requests a prose answer. The export subcommand creates a table only when invoked with a source file and destination.
What's New in v4.7.0 — Institutional Trust Suite
Five coordinated controls land together, each aligned to SEC Rule 15c3-5 (pre-trade) and SEC 17a-4 / FINRA 4511 (records) principles. This is a controls framework, not a claim of regulatory certification.
Bounded Autonomy (client.mandates): trading mandates that bound order flow per scope: symbol universe, per-order notional and quantity caps, gross exposure, leverage, daily-loss limit, and a mandatory expiry for live scopes. Enforced at every first-party order and deploy surface, backed by a hash-chained local audit ledger (cpz.audit) and mandate / killswitch / audit CLI subcommands. Expiry ends the authority to trade: once a mandate lapses with no active replacement, every opening SDK order in its scope is refused (closes still go) until a new mandate is committed; for an account-scoped mandate that is every order on the account, and an order that names no account is refused while any account mandate exists for its environment. Symbol rules compare one spelling (ETH/USD = ETHUSD), block a stock's options and a crypto base's pairs, and never refuse a close.
Backtest Trust Layer (client.backtests) — every backtest can emit a run card and validation artifact: metrics, benchmark context, data provenance, a deterministic config hash, and point-in-time / OHLC-sanity / lookahead-bias checks. The "SDK-attested" verdict is recomputed server-side, so a client can never self-certify.
Factor Library (client.factors) — fetch the platform factor catalog and bench any factor over a universe and period (IC, rank IC, IR, turnover, with alive / reversed / dead status). Formulas run through an AST-whitelisted evaluator, never eval.
Strategy Health (client.health) — a falsifiable-hypothesis registry plus a decay lifecycle (active / monitoring / decayed / disabled) computed from rolling Sharpe and IC. It records only; it never stops or modifies a deployment.
Shadow Account (client.shadow) — parse broker execution history (Alpaca, IBKR Flex, generic CSV) into normalized fills, compute behavioral diagnostics (FIFO round trips, win rate, holding periods, disposition effect), and replay an honestly-bounded counterfactual.
Behavioral changes — read before upgrading:
Live orders now require CPZ platform connectivity. The kill switch and mandate checks fail closed: if the control plane is unreachable, a live order raises rather than proceeding unchecked. Paper orders warn and proceed. Risk-reducing closes are exempt by design.
validate=True is the new backtest default. Data-quality checks and the lookahead gate now run unless you pass validate=False.
Removed the unauthenticated hardcoded-IP engine REST fallback, which cannot coexist with mandate enforcement.
v4.41.0: Data reads fail loudly: a read that returned [], None or Yahoo data now raises CPZDataRequestError, after retrying what may pass. bars and history return the same bars; news and trades work on every account.
v4.40.0: Symbol Master full-file reads and deliverable pricing (client.symbolmaster.fetch_all, deliverable_values).
v4.39.0: Symbol Master options reference data (client.symbolmaster) and VIPE Analytics (client.vipe).
v4.6.6 — Bloomberg Data License market-data provider (client.data.bloomberg); order-fill durability.
v4.6.3 — real, vendor-agnostic options chain with greeks (options() / get_option_chain()), routed through the CPZ backend instead of hitting Alpaca directly.
v4.6.0 — implied-volatility history and IV rank (client.data.get_iv_history / iv_rank), vendor-agnostic and capability-based.
v4.2.0 — client.data.scout(source, **params): one-call execution of any Data Scout starter snippet, credentials resolved server-side from your stored API connections.
v4.1.0 — institutional FIX 4.4 client (cpz.fix) for direct broker connectivity, sync and async.
v4.25.0: research Compute Fabric client and truthful local QAOA simulation; earlier real-QPU claims corrected.
v3.0.0 — Strategy Framework, Backtest Engine, Pre-Trade Risk Guard, TWAP/VWAP/Iceberg execution algos.
See CHANGELOG.md for the full reconciled history (v2.4.0 → v4.7.0).
The CPZ Python SDK is the unified interface for the CPZ quantitative trading platform. Write strategies once and run them in backtest or live mode with zero code changes.
PyPI releases intentionally contain a wheel only; no source distribution is published. The wheel includes the changelog, Data Connections Guide, and the backtest-realism and walk-forward example scripts. After installing this release, locate their readable local copies without importing the SDK:
from importlib.metadata import distribution reference = distribution("cpz-ai").locate_file("cpz/_reference") for name in ( "CHANGELOG.md", "docs/data-connections.md", "examples/backtest_realism.py", "examples/walk_forward.py", ): print(reference / name) Repository-relative links below refer to those same files. Example scripts use the credentials and provider access described in their instructions.
pip install cpz-ai # core SDK (includes classical quantum-inspired optimizers) pip install cpz-ai[risk] # + statsmodels for advanced risk analytics pip install cpz-ai[quantum] # + dwave-neal for simulated annealing pip install cpz-ai[quantum-braket] # + Amazon Braket local QAOA simulation (CPU) pip install cpz-ai[all] # + all optional dependencies Quantum Portfolio Optimization
QUBO formulations support classical exact and annealing solvers, plus an experimental Braket local CPU simulator. Remote managed simulators and physical QPUs are disabled in cpz-quant 1.1.0. Earlier hardware and cost-tracking claims were unsupported by the implementation and are superseded here.
from cpz.portfolio import BraketSolver, qubo_portfolio_selection # No AWS credentials or provider charges. Local CPU resources still have cost. solver = BraketSolver(device="local", shots=256, max_iter=8, seed=7) result = qubo_portfolio_selection(returns, target_k=2, solver=solver) This does not demonstrate quantum advantage. QHRP permutation problems have N squared binary variables; local QAOA is bounded to 20 variables.
Symbol Master: what an option contract delivers
A ticker implies 100 shares. After a merger, spin-off, split or special dividend, a contract can deliver fewer shares, a basket, cash or a mix, and several roots can list the same strike and expiry on one underlying. client.symbolmaster reads the daily reference files from Symbol Master Inc. and checks one contract's identity before you size an order.
Compute Fabric research API (v4.25.0)
client.compute provides advisory recommendations, explicit small CPU hedge solves, batch planning, and benchmark uploads. client.quantum is an alias for the research interface, not physical QPU execution.
# Existing authenticated CPZClient. All numbers below are synthetic. proposal = client.compute.optimize_hedge( backend="edge_wasm", algorithm="brute_force", request_id="hedge-demo-1", book_greeks={"DEMO": {"delta": 1, "gamma": 0, "vega": 0}}, candidates=[{ "symbol": "DEMO-HEDGE", "underlying": "DEMO", "lot": 1, "greeks_per_lot": {"delta": -1, "gamma": 0, "vega": 0}, "notional_per_lot": 100, "spread_bps": 1, }], cardinality=1, penalty=10, greek_weights={"delta": 1, "gamma": 1, "vega": 1}, ) assert proposal.production_eligible is False The endpoint requires platform schema activation, entitlement and a spending policy. It fails closed when these are unavailable. Keep the same request ID after an uncertain response; use a new ID only for intentional new work. Run uploads are caller-reported evidence, never billing authorization. Reported provider costs are not verified invoices.
Proposals validate linear Greeks only and cannot emit orders. Live orders declaring a research compute_run_id are blocked even in shadow mode. Untagged user-created orders use existing controls; manually copied numbers cannot be traced. GPU execution and physical-QPU dispatch remain unavailable.
Write your strategy once as a Strategy subclass. The same code runs against the backtest engine or live broker with zero changes.
from cpz import Strategy, StrategyConfig, StrategyRunner, CPZClient class MomentumConfig(StrategyConfig): fast_period: int = 10 slow_period: int = 30 trade_size: float = 100 class MomentumStrategy(Strategy): def on_start(self): self.subscribe_bars(self.config.instruments[0], "1D") def on_bar(self, bar): prices = self.cache.bars(bar.symbol) if len(prices) < self.config.slow_period: return fast_ma = sum(b.close for b in prices[-self.config.fast_period:]) / self.config.fast_period slow_ma = sum(b.close for b in prices[-self.config.slow_period:]) / self.config.slow_period if fast_ma > slow_ma and not self.portfolio.is_long(bar.symbol): self.buy(bar.symbol, qty=self.config.trade_size) elif fast_ma < slow_ma and self.portfolio.is_long(bar.symbol): self.flatten(bar.symbol) def on_order_filled(self, event): self.log.info(f"Filled {event.symbol} @ {event.fill_price}") def on_position_closed(self, event): self.log.info(f"Closed {event.symbol}, realized P&L: ${event.realized_pnl:,.2f}") Backtest
client = CPZClient() runner = StrategyRunner(client, mode="backtest") runner.add_strategy(MomentumStrategy(MomentumConfig(instruments=["AAPL"]))) result = runner.backtest( start="2024-01-01", end="2024-12-31", initial_cash=100_000, commission_pct=0.0003, # 3 bps slippage_pct=0.0001, # 1 bp ) print(result.summary()) Output:
============================================================ BACKTEST RESULTS ============================================================ Period: 2024-01-01 → 2024-12-31 Initial Cash: $100,000.00 Final Equity: $112,450.00 Total Return: +12.45% ------------------------------------------------------------ Sharpe Ratio: 1.842 Sortino Ratio: 2.315 Max Drawdown: -4.23% ------------------------------------------------------------ Total Trades: 47 Win Rate: 63.8% Profit Factor: 2.14 ============================================================ Backtest Realism (v4.29.0)
Every realism model is opt-in. With none set, a backtest behaves as before, and result.modeling says what that leaves out.
from cpz.strategy.sim import CashAccount, MarginAccount, VolumeParticipation, ibkr_fixed result = runner.backtest( start="2024-01-01", end="2024-12-31", order_model="intrabar", # limit, stop, stop_limit, trailing_stop, MOO, MOC fee_model=ibkr_fixed(), # or alpaca_zero_commission(), tradestation_equities(), PerShareFee(...) fill_model=VolumeParticipation(0.05), # at most 5% of each bar's volume; remainders carry forward account=CashAccount(), # or MarginAccount(debit_interest_rate=...) ) print(result.modeling.text()) Orders (order_model="intrabar"). Bars only give open, high, low and close, so each rule takes the reading least favourable to the strategy:
An order placed while handling a bar can first fill on a bar that starts after that bar ends. Time in force: DAY, GTC (with optional expire_at), IOC, FOK. Expired, cancelled and rejected orders are listed on the result with their reasons.
Fees. PercentFee (the historic default), PerShareFee(rate, min, max_pct), SecSection31Fee and FinraTafFee (dated rate tables for sells, sourced from sec.gov and finra.org), plus presets ibkr_fixed(), alpaca_zero_commission() and tradestation_equities(tier). Rates carry their source URL and effective date in cpz/strategy/sim/fees.py. A fill dated before the first published rate raises; a fill after the last one uses the rate still in effect, and result.modeling records rates_verified_as_of (2026-09-17) with a note when any fill is later than that. Per-order minimums and caps are charged once per order across partial fills, as IBKR bills them. result.fee_totals breaks fees down by component.
Accounts. CashAccount buys only with settled cash (T+2 before 2024-05-28, T+1 after) and rejects short sales. MarginAccount applies Reg T 50% initial margin, FINRA Rule 4210 maintenance, a liquidation event on a maintenance breach, and daily debit interest at the rate you pass. An order over buying power is rejected with a reason, never resized.
Scheduled events. Register in on_start; on_timer(event) fires in backtests on the NYSE calendar (2010 to 2028, holidays and 13:00 early closes):
self.schedule.every("tick", minutes=15) self.schedule.at_market_open("open30", offset_minutes=30) self.schedule.at_market_close("rebalance", offset_minutes=10, frequency="month_end") # daily, weekly, month_start, month_end Consolidation. self.consolidate("AAPL", "15Min", handler) rolls 1-minute bars into 15-minute bars and only ever hands the handler closed bars.
Corporate actions. price_mode="raw", corporate_actions=corporate_action_source("massive") replays unadjusted Massive bars and applies splits (position rescaled, open orders cancelled) and cash dividends (receivable on the ex-date, cash on the pay date). Providers without split and dividend data raise. The default replays bars as the data path returns them (the CPZ gateway requests split-adjusted bars from Alpaca and Polygon).
See examples/backtest_realism.py.
Walk-Forward Optimization (v4.31.0)
The optimization is a call in your own script, so whoever reads the script sees what was searched and how:
result = runner.walk_forward( MyStrategy, param_grid={"lookback": [10, 20, 40], "z_entry": [1.5, 2.0]}, config=MyConfig(instruments=["SPY"]), start="2019-01-01", end="2025-12-31", folds=5, train_bars=504, test_bars=126, anchored=False, objective="sharpe", # "sortino", "calmar", "total_return" or a callable(BacktestResult) -> float warmup_bars=40, # optional indicator history before each test window ) print(result.summary()) For each fold, every combination is backtested on the train window and the best in-sample objective is chosen (ties go to the earliest combination). Only then does that combination run on the next test_bars bars. Test windows follow one another without overlap and never influence a choice. The folds end at the last bar of the data. anchored=True keeps the first train bar fixed and grows the train window by test_bars each fold.
No lookahead. Selection sees only the fold's train bars. Warm-up bars come from before the test window; the strategy sees them, but every order placed on them is refused (result.warmup_refused_orders) and they are not scored.
Every evaluated combination is a trial. result.trials is combinations x folds, and it deflates the Sharpe of the stitched out-of-sample returns (result.deflation: deflated Sharpe, expected maximum Sharpe under the null, PSR, DSR probability). The formula is the platform's schema-2 rigor block, so SDK and Builder runs are comparable.
Everything is reported. result.folds (train and test dates, chosen params, in-sample objective, out-of-sample metrics, and both backtests), result.grid / grid_frame() (every combination's in-sample score on every fold), result.oos (the stitched out-of-sample BacktestResult), result.stability (how often the choice changed, and the objective at the chosen point's neighbouring grid points) and result.degradation (in-sample vs out-of-sample objective).
Hard budget. More than 256 combinations raises WalkForwardBudgetError; a grid is never sampled or truncated. Too few bars for train_bars + folds * test_bars raises BacktestDataError with the numbers.
Deterministic. Runs are serial; the same inputs give the same result.
Each fold's test run starts flat with initial_cash; out-of-sample returns are compounded across folds, and a position still open at a test window's end is marked to market at its last close with no exit costs, as at the end of any backtest.
upload=True (or client.backtests.upload(result)) uploads the stitched out-of-sample run with a schema-2 rigor block: deflatedSharpe.numTrials is the full trial count, walkForward.refit is true, and walkForward.anchored.oosSharpe / oosReturnPct carry the stitched out-of-sample figures (the platform reads them under that key for rolling walk-forwards too; walkForward.method says which ran).
See examples/walk_forward.py.
Live Trading (Same Code!)
runner = StrategyRunner(client, mode="live") runner.add_strategy(MomentumStrategy(MomentumConfig(instruments=["AAPL"]))) runner.run() # Blocks until Ctrl+C Strategy Lifecycle Hooks
self.buy("AAPL", qty=100) # Market buy self.sell("AAPL", qty=50) # Market sell self.buy("AAPL", qty=10, order_type="limit", limit_price=150.00) self.sell("AAPL", qty=10, order_type="trailing_stop", trail_percent=5, time_in_force="GTC") self.buy("AAPL", qty=10, order_type="market_on_close") # backtest: order_model="intrabar" self.flatten("AAPL") # Close position self.flatten_all() # Close all positions self.cancel_all_orders() # Cancel open orders self.emit_signal("crossover", value=1.0) # Emit custom signal self.subscribe_bars("AAPL", "1Min") # Subscribe to bars self.subscribe_quotes("AAPL") # Subscribe to quotes Strategy Context
Every strategy has access to:
self.cache.bars("AAPL") # Cached bar history self.cache.latest_bar("AAPL") # Most recent bar self.portfolio.equity() # Current equity self.portfolio.cash # Available cash self.portfolio.is_long("AAPL") # Position check self.portfolio.positions() # All positions self.clock.utc_now() # Current time (real or simulated) self.log.info("message") # Structured logging self.config.instruments # Strategy config Pre-Trade Risk Guard
Intercepts every order before it reaches the broker. Any violation raises RiskGuardViolation and the order is rejected.
Or use directly in a strategy:
from cpz import RiskGuard class SafeStrategy(Strategy): def on_start(self): guard = RiskGuard(max_order_value=25_000, max_daily_loss=-2_000) self._router.set_risk_guard(guard) self.subscribe_bars("AAPL", "1D") Execution Algorithms
Split large orders into smaller slices for better execution.
from cpz.execution.algos import TWAPAlgorithm, VWAPAlgorithm, IcebergAlgorithm # TWAP — equal slices over time algo = TWAPAlgorithm() slices = algo.generate_slices(order_request, { "duration_minutes": 30, "num_slices": 10, }) # VWAP: slices follow the session volume curve over THIS window # (default curve: 9:30-16:00 New York; elsewhere pass "volume_profile") algo = VWAPAlgorithm() slices = algo.generate_slices(order_request, { "start_time": "2026-11-24T10:00:00-05:00", # default: now "duration_minutes": 60, "num_slices": 12, }) # Iceberg — hidden quantity algo = IcebergAlgorithm() slices = algo.generate_slices(order_request, { "display_qty": 100, # Only show 100 shares at a time }) Typed Domain Model
Precision-safe value types that reject NaN, Infinity, and invalid data at construction time.
from cpz import Price, Quantity # Validated, immutable price = Price("150.25") # From string (exact) price = Price.from_float(150.25, precision=2) # From float qty = Quantity.from_int(100) # Type-safe arithmetic total = price * qty # Returns Money("15025.00", "USD") spread = Price("150.50") - Price("150.25") # Returns Price("0.25") # Fail-fast on invalid data Price(float("nan")) # ValueError: Price must be finite Quantity(-1) # ValueError: Quantity cannot be negative Event Bus
Thread-safe pub/sub with wildcard topic matching.
from cpz import EventBus bus = EventBus() # Subscribe with wildcards bus.subscribe("bar.AAPL.*", handle_aapl_bars) # Any timeframe for AAPL bus.subscribe("order.**", handle_all_orders) # All order events # Publish bus.publish("bar.AAPL.1Min", bar_event) Quick Start
Comprehensive quantitative risk computation powered by numpy/scipy. Install with pip install cpz-ai[risk].
On first use the risk-free rate is the newest 3-month Treasury yield (DGS3MO) from the CPZ us_macro warehouse. If that read fails, the SDK logs a risk_free_rate_unavailable warning and uses 0% until you call client.risk.set_risk_free_rate(...). All methods accept daily returns as a list of floats.
Statistical significance testing for the Sharpe ratio. Implements all 5 corrections from Lopez de Prado (2012, 2018):
Non-normality — SE adjusted for skewness and kurtosis
Serial correlation — Lo (2002) autocorrelation adjustment
Probabilistic Sharpe Ratio (PSR) — P(true Sharpe > benchmark)
Deflated Sharpe Ratio (DSR) — Multiple-testing correction
Minimum Track Record Length — How long before the Sharpe is credible?
inference = client.risk.sharpe_inference(daily_returns, num_trials=20) print(f"PSR (prob true SR > 0): {inference.psr:.1%}") print(f"DSR (adjusted for 20 trials): {inference.deflated_sharpe}") print(f"Min track record needed: {inference.min_track_record_months} months") Value at Risk
var_95 = client.risk.parametric_var(daily_returns, confidence=0.95) hist_var = client.risk.historical_var(daily_returns, confidence=0.95) mc = client.risk.monte_carlo(daily_returns, num_simulations=10000, horizon_days=5) Advanced Analytics
dd = client.risk.drawdown_analysis(daily_returns) # Drawdown decomposition tail = client.risk.tail_risk(daily_returns) # Skewness, kurtosis, Cornish-Fisher VaR sizing = client.risk.position_size(100000, returns) # Kelly criterion + vol targeting exposure = client.risk.factor_exposure(returns, factors) # OLS factor decomposition impacts = client.risk.stress_test_all(weights) # 7 historical crisis scenarios rolling = client.risk.rolling_metrics(returns, spy, 20) # Rolling Sharpe, vol, beta Trading
Broker Configuration
Kalshi symbols name one outcome of one market, "
client.execution.use_broker("kalshi", environment="paper") client.execution.submit_order( symbol="KXFED-26OCT-T4.25:YES", qty=10, side="buy", order_type="limit", limit_price=0.56, time_in_force="gtc", ) Order Placement
# Simple order order = client.execution.order( symbol="AAPL", qty=10, side="buy", strategy_id="my-strategy" ) # Full control from cpz import OrderSubmitRequest, OrderSide, OrderType, TimeInForce request = OrderSubmitRequest( symbol="AAPL", side=OrderSide.BUY, qty=10, order_type=OrderType.LIMIT, time_in_force=TimeInForce.GTC, limit_price=150.00, strategy_id="my-strategy" ) order = client.execution.submit_order(request) Account and Positions
account = client.execution.get_account() print(f"Buying Power: ${account.buying_power:,.2f}") positions = client.execution.get_positions() for pos in positions: print(f"{pos.symbol}: {pos.qty} shares @ ${pos.avg_entry_price}") Execution: one API for every broker
Every broker exposes the same methods, on client.execution (sync), AsyncCPZClient().execution and BrokerRouter. A broker that cannot do something raises BrokerOperationUnsupported (a NotImplementedError) before it touches your account: never None, never invented data, never a cancel followed by a failed replace. Ask first with capabilities().
from cpz import BrokerOperationUnsupported client.execution.use_broker("saxo", environment="live") caps = client.execution.capabilities() if caps.close_position: client.execution.close_position("AAPL", percentage=50, strategy_id="my-strategy") order = client.execution.order( symbol="AAPL", qty=10, side="sell", order_type="stop", stop_price=180.0, strategy_id="my-strategy", ) result = client.execution.cancel_all_orders() if not result.complete: print(result.failed, result.remaining) try: client.execution.replace_order(order.id, OrderReplaceRequest(stop_price=182.0)) except BrokerOperationUnsupported as exc: print(exc.broker, exc.operation, exc.reason) OrderSubmitRequest also takes trail_price / trail_percent (trailing stops, exactly one), extended_hours, venue_symbol_id (the broker's own instrument id: IBKR conid, Saxo Uic:AssetType, tastytrade Instrument Type|symbol, SnapTrade universal id, Polymarket token id, Kalshi TICKER:YES / TICKER:NO), position_effect (open / close) and asset_class. Stop orders need stop_price, stop-limit orders need stop_price and limit_price.
Capabilities through the execution gateway (GET /cpz/brokers is the source of truth; capabilities() reads it):
Native adapters (no CPZ_PROXY_ENABLED, or explicit credentials) describe themselves with their own, narrower capabilities(): the native IBKR adapter places market and limit orders only and has no order list, replace, closes or portfolio history; the native SnapTrade adapter is read-only; the native Polymarket adapter needs a limit_price on every order; the native Alpaca adapter does not stream quotes.
Execution Gateway Routing
With CPZ_PROXY_ENABLED=1 in the environment (hosted strategy runs set it), use_broker(
import os os.environ["CPZ_PROXY_ENABLED"] = "1" client.execution.use_broker("ibkr", environment="paper") print(client.execution.router.routed_via) # "cpz_proxy" Every OrderSubmitRequest gets client_order_id = "cpz-
from cpz.execution.cpz_proxy import ( CPZBrokerRejected, CPZOrderLaneBusy, CPZSubmitUnconfirmed, ) try: order = client.execution.order(symbol="AAPL", qty=10, side="buy", strategy_id="my-strategy") except CPZSubmitUnconfirmed as exc: # The order may be live under exc.client_order_id. Look it up with # get_order_by_client_id() or resend the identical request; never use a fresh id. ... except CPZOrderLaneBusy as exc: # Another submission holds this symbol's lane and the SDK already retried # once. Retry the identical request after exc.retry_after_ms. ... except CPZBrokerRejected as exc: # Definitive broker rejection: exc.code (for example wash_trade_rejected) # and exc.broker_code carry the reason. Not retryable as-is. ... A timeout or connection error mid-submit is not treated as "not placed": the SDK looks the order up by client_order_id (twice, 500 ms apart) and returns it if the broker id is bound, and raises CPZSubmitUnconfirmed otherwise.
Quantitative Libraries (v2.5.0+)
25+ indicators computed locally (no API calls):
from cpz.indicators import sma, ema, rsi, macd, bollinger, atr, vwap fast = ema(prices, period=10) slow = ema(prices, period=30) rsi_val = rsi(prices, period=14) bb = bollinger(prices, period=20) # .upper, .middle, .lower macd_val = macd(prices) # .macd, .signal, .histogram Portfolio Optimization
12 optimizers including HRP, Black-Litterman, and Mean-CVaR:
from cpz.portfolio import mean_variance, risk_parity, hierarchical_risk_parity weights = risk_parity(returns_df) weights = hierarchical_risk_parity(returns_df) Signal Construction
from cpz.signals import vol_target, regime_filter, max_positions, normalize, max_weight # Inside generate_signal(data, state). regime_filter raises when it has no VIX # data (missing VIX is not a calm market); CPZ market data has no VIX bars. if not regime_filter(data["^VIX"], threshold=30): return {} weights = {sym: vol_target(data[sym], risk=0.02) for sym in symbols} weights = max_positions(weights, limit=10) # select weights = normalize(weights, target=1.0) # size weights = max_weight(weights, limit=0.15) # cap last, so the cap holds Alpha Research
from cpz.alpha import information_coefficient, signal_decay, quantile_returns ic = information_coefficient(signals, forward_returns) decay = signal_decay(signals, returns, max_lag=20) HFT Engine
Deploy strategies to the Rust HFT engine for autonomous microsecond-latency execution.
status = client.engine.status() client.engine.deploy( strategy_id="my-strategy", symbols=["AAPL", "NVDA"], broker="alpaca", environment="paper", ) client.engine.stop("my-strategy") Data
# Stock/crypto bars bars = client.data.bars("AAPL", timeframe="1D", limit=100) # Multi-symbol history for backtesting df = client.data.history(["AAPL", "MSFT", "NVDA"], timeframe="1D", limit=252) # Quotes, news, options, economic data, filings, sentiment quotes = client.data.quotes(["AAPL", "MSFT"]) news = client.data.news("TSLA", limit=10) gdp = client.data.economic("GDP") filings = client.data.filings("AAPL", form="10-K") sentiment = client.data.sentiment("GME") # Massive (formerly Polygon): stocks, options, indices, futures, crypto, forex bars = client.data.massive.get_bars("AAPL", timeframe="1d") chain = client.data.massive.get_options_chain("AAPL") quote = client.data.massive.realtime.get_quote("AAPL") # refuses DELAYED data # Data providers: Massive, Alpaca, TwelveData, FRED, SEC EDGAR, # Databento, CoinGecko, Finnhub, Alpha Vantage, and more Data Connections Guide — how to connect each provider, then fetch, pull and stream from it (key resolution, entitlements, streaming support, troubleshooting).
Simons — Quantitative Trading Strategist
response = client.simons.chat("Analyze AAPL for momentum trading") print(response.content) for chunk in client.simons.stream("Write a mean-reversion backtest"): if chunk.type == "text": print(chunk.content, end="", flush=True) Architecture
CPZClient ├── Strategy Framework (NEW in v3.0.0) │ ├── Strategy Base class with 20+ lifecycle hooks │ ├── StrategyConfig Serializable configuration │ ├── StrategyRunner Live and backtest orchestration │ ├── BacktestEngine Historical replay with fill simulation │ ├── RiskGuard Pre-trade order validation (10 rules) │ └── TWAP/VWAP/Iceberg Execution algorithms │ ├── Typed Domain Model (NEW in v3.0.0) │ ├── Price Decimal-backed, fail-fast on NaN/Inf │ ├── Quantity Non-negative, precision-safe │ ├── Money Currency-tracked arithmetic │ └── Events BarEvent, FillEvent, PositionEvent, ... │ ├── risk Portfolio risk analytics (numpy/scipy) │ ├── compute() Full risk snapshot │ ├── monte_carlo() Monte Carlo VaR (Rust-accelerated) │ ├── sharpe_inference() Lopez de Prado framework │ ├── stress_test_all() 7 historical crisis scenarios │ └── [20+ more methods] │ ├── execution Multi-broker trading │ ├── use_broker() Configure broker (Alpaca, IBKR, SnapTrade, Polymarket) │ ├── order() Place orders with risk guard validation │ ├── set_risk_guard() Attach pre-trade risk rules │ └── get_positions() Current positions │ ├── data Market and reference data (18 providers) │ ├── bars() OHLCV price data │ ├── history() Multi-symbol DataFrames │ ├── economic() 31 US macro series (us_macro); other FRED ids need your own key │ └── [indicators] 100+ technical indicators via TwelveData │ ├── indicators 25+ local indicators (no API calls) ├── signals Position sizing and signal filters ├── portfolio 12 portfolio optimizers ├── alpha IC analysis, signal decay, quantile returns │ ├── simons Quantitative trading strategist AI └── engine Rust HFT engine for autonomous execution Configuration
Get credentials at ai.cpz-lab.com/settings.
pytest --cov=cpz --cov-report=term-missing Python Status 3.9 Supported 3.10 Supported 3.11 Supported 3.12 Supported Support
Platform: ai.cpz-lab.com
Repository: github.com/CPZ-Lab/cpz-py
Email: contact@cpz-lab.com
Requires cpz-ai 4.39.0 or later. Save your own VIPE username/email and password in CPZAI Data Lab first. In external Python, set CPZ_AI_API_KEY and CPZ_AI_API_SECRET to your CPZAI credentials with the data scope. Simons' Python runner already supplies the account credentials; use the same code there.
The SDK preserves the full response envelope and metadata. Annual financial periods are not publication dates. Estimated rows are marked isEstimated, and point_in_time_verified is currently false: these endpoints are not verified point-in-time backtest inputs. Unsupported as-of and screening arguments fail.
Released: Nov 29, 2026
Other/Proprietary License (CPZAI SDK License Agreement)
fix fix-async fix-all spiderrock spiderrock-async spiderrock-all sklearn dev yfinance databento hft risk quantum quantum-braket all
Development Status 4 - Beta
Intended Audience Developers
License Other/Proprietary License
Programming Language Python :: 3
Release files for cpz-ai 4.45.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Built distribution (wheel)
Release files / cpz_ai-4.45.1-py3-none-any.whl
Security for cpz-ai 4.45.1
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.
Release history Release notifications | RSS feed
Nov 29, 2026 1 release file No provenance
Nov 19, 2026 1 release file No provenance
Nov 9, 2026 1 release file No provenance
Nov 5, 2026 1 release file No provenance
Nov 4, 2026 1 release file No provenance
Oct 30, 2026 1 release file No provenance
Oct 4, 2026 2 release files No provenance
Oct 4, 2026 1 release file No provenance
Sep 29, 2026 1 release file No provenance
Sep 27, 2026 1 release file No provenance
Sep 17, 2026 1 release file No provenance
Sep 15, 2026 1 release file No provenance
Sep 14, 2026 1 release file No provenance
Sep 14, 2026 2 release files No provenance
Sep 9, 2026 2 release files No provenance
Sep 8, 2026 2 release files No provenance
Aug 25, 2026 2 release files No provenance
Aug 19, 2026 2 release files No provenance
Aug 13, 2026 2 release files No provenance
Aug 12, 2026 2 release files No provenance
Aug 10, 2026 2 release files No provenance
Aug 6, 2026 2 release files No provenance
Aug 3, 2026 2 release files No provenance
Jul 30, 2026 1 release file No provenance
Jul 28, 2026 2 release files No provenance
Jul 24, 2026 2 release files No provenance
Jul 15, 2026 2 release files No provenance
Jul 14, 2026 2 release files No provenance
Jul 5, 2026 2 release files No provenance
Jul 4, 2026 2 release files No provenance
Jun 22, 2026 2 release files No provenance
May 20, 2026 2 release files No provenance
May 17, 2026 2 release files No provenance
May 14, 2026 2 release files No provenance
May 6, 2026 2 release files No provenance
Apr 30, 2026 2 release files No provenance
Apr 27, 2026 2 release files No provenance
Apr 26, 2026 2 release files No provenance
Apr 21, 2026 2 release files No provenance
Apr 14, 2026 2 release files No provenance
Apr 11, 2026 2 release files No provenance
Mar 27, 2026 2 release files No provenance
Mar 17, 2026 2 release files No provenance
Mar 11, 2026 2 release files No provenance
Mar 10, 2026 2 release files No provenance
Mar 9, 2026 2 release files No provenance
Mar 6, 2026 2 release files No provenance
Mar 5, 2026 2 release files No provenance
Mar 1, 2026 2 release files No provenance
Feb 28, 2026 2 release files No provenance
Feb 27, 2026 2 release files No provenance
Feb 26, 2026 2 release files No provenance
Feb 24, 2026 2 release files No provenance
Feb 23, 2026 2 release files No provenance
Feb 22, 2026 2 release files No provenance
Feb 21, 2026 2 release files No provenance
Feb 2, 2026 2 release files No provenance
Feb 1, 2026 2 release files No provenance
Jan 30, 2026 2 release files No provenance
Jan 28, 2026 2 release files No provenance
Jan 17, 2026 2 release files No provenance
Jan 16, 2026 2 release files No provenance
Jan 15, 2026 2 release files No provenance
Jan 13, 2026 2 release files No provenance
Jan 9, 2026 2 release files No provenance
Dec 8, 2025 2 release files No provenance
Dec 4, 2025 2 release files No provenance
Nov 28, 2025 2 release files No provenance
Nov 27, 2025 2 release files No provenance
Nov 20, 2025 2 release files No provenance
Oct 16, 2025 2 release files No provenance
Oct 15, 2025 2 release files No provenance
Oct 9, 2025 2 release files No provenance
Oct 4, 2025 2 release files No provenance
Sep 22, 2025 2 release files No provenance
Sep 8, 2025 2 release files No provenance
Sep 4, 2025 2 release files No provenance
Sep 3, 2025 2 release files No provenance
Aug 15, 2025 2 release files No provenance
"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.
© 2026 Python Software Foundation
Deployed from fc0d8e6











