Skip to content

Market Graph Clustering API Reference

Data

Data model for Market Graph Clustering use case.

MarketGraphClusteringData

Bases: UcData

Data for the Market Graph Clustering use case.

This use case clusters stocks based on their return correlations using a k-medoids approach on a correlation-derived distance metric.

Attributes:

Name Type Description
name Literal['market_graph_clustering']

Identifier for this data type.

returns_matrix NumPyArray

An n_stocks x n_observations matrix of stock returns.

k int

Number of clusters to form.

stock_names list[str]

Identifiers for each stock.

from_corr_matrix(corr_matrix: np.ndarray, k: int, stock_names: list[str] | None = None) -> MarketGraphClusteringData classmethod

Create data from a symmetric correlation matrix.

The correlation matrix is symmetrised via (C + C^T) / 2 to guard against small floating-point asymmetries.

Parameters:

Name Type Description Default
corr_matrix ndarray

An n_stocks x n_stocks symmetric correlation matrix.

required
k int

Number of clusters to form.

required
stock_names list[str] | None

Identifiers for each stock. Auto-generated if None.

None

Returns:

Type Description
MarketGraphClusteringData

A data instance backed by the correlation matrix.

plot(*, ax: Axes | None = None) -> Axes

Plot the correlation matrix as a heatmap.

Parameters:

Name Type Description Default
ax Axes | None

Matplotlib axes to draw on. Creates a new figure if None.

None

Returns:

Type Description
Axes

The axes with the plot.

to_string() -> str

Return a string describing the data.

Returns:

Type Description
str

String representation of the data.

generate_random(n_stocks: int = 6, n_observations: int = 20, k: int = 2, seed: int | None = None) -> MarketGraphClusteringData staticmethod

Generate a random Market Graph Clustering instance.

Creates correlated groups of stock returns to simulate market sectors.

Parameters:

Name Type Description Default
n_stocks int

Number of stocks, by default 6.

6
n_observations int

Number of return observations per stock, by default 20.

20
k int

Number of clusters, by default 2.

2
seed int | None

Random seed for reproducibility, by default None.

None

Returns:

Type Description
MarketGraphClusteringData

A randomly generated data instance.

Formulation

Formulation for Market Graph Clustering use case.

MarketGraphClusteringFormulation

Bases: UcFormulation[MarketGraphClusteringData, MarketGraphClusteringSolution]

Constraint-based formulation for Market Graph Clustering.

Preprocessing converts Pearson correlations to distances using d_ij = sqrt(0.5 * (1 - corr_ij)), then applies the standard k-medoids formulation.

Mathematical Formulation
Decision Variables:
    z_i in {0,1}: 1 if stock i is a medoid
    y_{i,j} in {0,1}: 1 if stock i is assigned to medoid j

Objective:
    ``minimize sum_{i,j} d[i][j] * y[i,j]``

Constraints:
    1. Exactly k medoids: sum_i z[i] == k
    2. Each stock assigned to one medoid: sum_j y[i,j] == 1 for all i
    3. Assign only to medoids: y[i,j] <= z[j] for all i,j
    4. Medoid self-assignment: y[j,j] >= z[j] for all j

to_string(data: MarketGraphClusteringData) -> str staticmethod

Return a string describing the formulation.

Parameters:

Name Type Description Default
data MarketGraphClusteringData

The problem data.

required

Returns:

Type Description
str

String representation of the formulation.

formulate(data: MarketGraphClusteringData) -> Model staticmethod

Formulate the Market Graph Clustering problem.

Parameters:

Name Type Description Default
data MarketGraphClusteringData

The problem data.

required

Returns:

Type Description
Model

A LunaModel ready to be solved.

interpret(solution: Solution, data: MarketGraphClusteringData) -> MarketGraphClusteringSolution staticmethod

Extract solution from quantum result.

Parameters:

Name Type Description Default
solution Solution

The quantum solution.

required
data MarketGraphClusteringData

The problem data.

required

Returns:

Type Description
MarketGraphClusteringSolution

Structured solution with metrics.

Solution

Solution model for Market Graph Clustering use case.

MarketGraphClusteringSolution

Bases: UcSolution

Solution for the Market Graph Clustering use case.

Attributes:

Name Type Description
name Literal['market_graph_clustering']

Identifier for this solution type.

medoids list[str]

List of selected medoid stock names.

cluster_assignments dict[str, str]

Mapping from each stock to its assigned medoid (str keys for JSON).

total_objective float

Sum of correlation-derived distances from each stock to its medoid.

is_valid bool

Whether the solution satisfies all constraints.

plot(data: MarketGraphClusteringData | None = None, *, ax: Axes | None = None) -> Axes

Plot the clustering solution as a return-vs-volatility scatter.

Each stock is positioned by its mean return (x-axis) and volatility (y-axis). Stocks are coloured by cluster, with medoids shown as larger square markers. Light lines connect each stock to its medoid.

Parameters:

Name Type Description Default
data MarketGraphClusteringData | None

Problem data used to compute return and volatility coordinates. When None a simple circular layout is used as fallback.

None
ax Axes | None

Matplotlib axes to draw on. Creates a new figure if None.

None

Returns:

Type Description
Axes

The axes with the plot.

to_string() -> str

Return a string describing the solution.

Returns:

Type Description
str

String representation of the solution.

Instance

Instance model for MarketGraphClustering use case.

MarketGraphClusteringInstance

Bases: UcInstance[MarketGraphClusteringData, MarketGraphClusteringFormulation, MarketGraphClusteringSolution]

Instance combining data and formulation for MarketGraphClustering.

Collection

Collection of Market Graph Clustering instances.

MarketGraphClusteringCollection

Bases: UcInstanceCollection[MarketGraphClusteringInstance]

Collection of Market Graph Clustering instances.

from_random(min_size: int | None = None, max_size: int | None = None, num_instances: int = 1, *, sizes: Sequence[int] | None = None, n_observations: int = 20, k: int = 2, seed: int | None = None) -> MarketGraphClusteringCollection classmethod

Generate random Market Graph Clustering instances.

Parameters:

Name Type Description Default
min_size int | None

Minimum number of stocks.

None
max_size int | None

Maximum number of stocks.

None
num_instances int

Number of instances per size, by default 1.

1
n_observations int

Number of return observations, by default 20.

20
k int

Number of clusters, by default 2.

2
seed int | None

Random seed for reproducibility, by default None.

None
sizes Sequence[int] | None

Explicit sizes to generate, e.g. [10, 50, 100], instead of a range. Mutually exclusive with min_size/max_size, by default None.

None

Returns:

Type Description
MarketGraphClusteringCollection

Collection containing generated instances.

filter_infeasible(max_runtime: float = 3600, *, quiet: bool = True) -> list[bool]

Drop the instances of this collection that have no feasible solution.

Every instance is formulated and handed to SCIP, which stops as soon as it finds the first feasible solution. An instance is removed from the collection when SCIP proves the model infeasible, when no solution turns up within max_runtime, or when formulating it fails altogether. This keeps randomly generated instances from breaking a downstream pipeline.

Parameters:

Name Type Description Default
max_runtime float

SCIP time limit per instance in seconds. Must be positive. Defaults to 3600 seconds.

3600
quiet bool

Suppress the SCIP solver output.

True

Returns:

Type Description
list[bool]

Feasibility mask over the instances as they were before filtering, in that order: True where the instance was kept, False where it was removed.

Raises:

Type Description
ValueError

If max_runtime is not positive.