Skip to content

API Reference

Everything a Python program uses from qex is importable from qex. The evaluation tools are also importable from evaluation. This page says where each name is documented, and generates the reference for the rest from the code.

Name What it is Documented in
qex, alpha, QexParser read an expression into a Signal Parsing
Signal, compute_context, get_context evaluate, weights, caching Signals; the context below
LazyData fields loaded on demand Large Datasets
BookSettings, build_book, hold_untradable, turnover, fitness, margin_bps books Books
price_returns, forward_returns, MAX_PRICE_GAP returns across gaps Books
Backtest, BacktestResult, QuantileAnalysis, QuantileResult evaluation Evaluation
sharpe_ratio, sortino_ratio, calmar_ratio, max_drawdown, top_drawdowns, annualized_return, annualized_volatility, return_on_gmv metrics Evaluation
cross_section_universe, universe_mask universes Universes from Python
explain_missing, MissingReport, qex.adjust.check, qex.kinds.numbers_only diagnostics Diagnostics
FactorRiskModel, FactorDefinition, DEFAULT_STYLE_FACTORS, PRICE_ONLY_FACTORS risk model Risk Model
SignalGraph, DistributedSignalEngine many signals, shared work, Dask Graphs and Dask, and below

The operator functions (rank, ts_mean, ...) and node classes (Rank, TsMean, ...) are importable too, for building a Signal in Python without text; what each operator does is in the Operator Reference.

Compute context

compute_context

compute_context()

Context manager for alpha computations with shared cache. The context is the current thread's: other threads see their own (or none), so contexts in parallel threads never mix.

get_context

get_context() -> Optional[ComputeContext]

The current thread's compute context, or None.

ComputeContext

Global computation context with shared cache.

get_data_hash

get_data_hash(data) -> tuple

The identity of the data the cache is valid for (see the module docstring).

check

check(data)

Clear the cache if data is not the data it was computed on.

clear

clear()

Clear the cache.

Graphs

SignalGraph

Build a unified DAG from multiple signals for efficient computation.

Deduplicates shared sub-expressions across signals using cache keys. Supports visualization with graphviz and execution with Dask.

Example

from qex import qex graph = SignalGraph() graph.add_signal(qex("rank(returns(60))"), name="mom") graph.add_signal(qex("rank(returns(60) / volatility(60))"), name="sharpe") graph.visualize("signals.png") # returns(60) appears once results = graph.compute(data)

add_signal

add_signal(signal: Signal, name: Optional[str] = None) -> str

Add a signal to the graph.

Parameters:

Name Type Description Default
signal Signal

Signal to add

required
name Optional[str]

Optional name for this output signal

None

Returns:

Type Description
str

The cache key for this signal (as string for display)

stats

stats() -> Dict[str, int]

Return statistics about the graph.

to_dask_graph

to_dask_graph() -> Dict[str, Tuple]

Convert to Dask-compatible task graph.

Returns dict suitable for dask.threaded.get() or distributed execution.

visualize

visualize(filename: str = 'signal_graph.png', format: str = None, rankdir: str = 'TB', highlight_outputs: bool = True, show_stats: bool = True) -> Optional[str]

Render the signal DAG using graphviz.

Parameters:

Name Type Description Default
filename str

Output filename (extension determines format if not specified)

'signal_graph.png'
format str

Output format ('png', 'svg', 'pdf'). Inferred from filename if None.

None
rankdir str

Graph direction ('TB'=top-bottom, 'LR'=left-right)

'TB'
highlight_outputs bool

Highlight output signal nodes

True
show_stats bool

Include stats in graph title

True

Returns:

Type Description
Optional[str]

Path to rendered file, or None if graphviz not available

Requires: pip install graphviz (and graphviz system package)

compute

compute(data: Dict[str, DataFrame], outputs: Optional[List[str]] = None) -> Dict[str, pd.DataFrame]

Compute signals using the graph (single-machine, cached).

Parameters:

Name Type Description Default
data Dict[str, DataFrame]

Price/volume data

required
outputs Optional[List[str]]

List of output names to compute (default: all)

None

Returns:

Type Description
Dict[str, DataFrame]

Dict mapping output names to result DataFrames

compute_dask

compute_dask(data: Dict[str, DataFrame], client: Optional[Any] = None, outputs: Optional[List[str]] = None) -> Dict[str, pd.DataFrame]

Compute signals using Dask distributed.

Parameters:

Name Type Description Default
data Dict[str, DataFrame]

Price/volume data

required
client Optional[Any]

Dask distributed Client (creates local cluster if None)

None
outputs Optional[List[str]]

List of output names to compute (default: all)

None

Returns:

Type Description
Dict[str, DataFrame]

Dict mapping output names to result DataFrames

Requires: pip install dask distributed

DistributedSignalEngine

High-level interface for distributed signal evaluation.

Manages data distribution and signal graph execution across a Dask cluster.

Example

from dask.distributed import Client from qex.distributed import DistributedSignalEngine

client = Client("scheduler:8786") engine = DistributedSignalEngine(client) engine.load_data(data)

expressions = [ ... "rank(returns(60))", ... "rank(returns(60) / volatility(60))", ... "rank(-returns(5))", ... ] results = engine.evaluate(expressions)

__init__

__init__(client: Optional[Any] = None)

Initialize the engine.

Parameters:

Name Type Description Default
client Optional[Any]

Dask distributed Client (creates local if None)

None

load_data

load_data(data: Dict[str, DataFrame])

Scatter data to all workers.

Call this once before evaluating signals. Data is cached on workers for efficient reuse.

evaluate

evaluate(expressions: List[str], names: Optional[List[str]] = None) -> Dict[str, pd.DataFrame]

Evaluate multiple signal expressions efficiently.

Parameters:

Name Type Description Default
expressions List[str]

List of qex expression strings

required
names Optional[List[str]]

Optional names for each expression

None

Returns:

Type Description
Dict[str, DataFrame]

Dict mapping names to result DataFrames

visualize

visualize(expressions: List[str], **kwargs) -> str

Build graph from expressions and visualize.

close

close()

Close the Dask client if we created it.