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 (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:

  • corr_matrix (ndarray) –

    An n_stocks x n_stocks symmetric correlation matrix.

  • k (int) –

    Number of clusters to form.

  • stock_names (list[str] | None, default: None ) –

    Identifiers for each stock. Auto-generated if None.

Returns:

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

Plot the correlation matrix as a heatmap.

Parameters:

  • ax (Axes | None, default: None ) –

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

Returns:

  • Axes

    The axes with the plot.

to_string() -> str

Return a string describing the data.

Returns:

  • 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:

  • n_stocks (int, default: 6 ) –

    Number of stocks, by default 6.

  • n_observations (int, default: 20 ) –

    Number of return observations per stock, by default 20.

  • k (int, default: 2 ) –

    Number of clusters, by default 2.

  • seed (int | None, default: None ) –

    Random seed for reproducibility, by default None.

Returns:

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:

Returns:

  • str

    String representation of the formulation.

formulate(data: MarketGraphClusteringData) -> Model staticmethod

Formulate the Market Graph Clustering problem.

Parameters:

Returns:

  • Model

    A LunaModel ready to be solved.

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

Extract solution from quantum result.

Parameters:

Returns:

Solution

Solution model for Market Graph Clustering use case.

MarketGraphClusteringSolution

Bases: UcSolution

Solution for the Market Graph Clustering use case.

Attributes:

  • 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:

  • data (MarketGraphClusteringData | None, default: None ) –

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

  • ax (Axes | None, default: None ) –

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

Returns:

  • Axes

    The axes with the plot.

to_string() -> str

Return a string describing the solution.

Returns:

  • 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:

  • min_size (int | None, default: None ) –

    Minimum number of stocks.

  • max_size (int | None, default: None ) –

    Maximum number of stocks.

  • num_instances (int, default: 1 ) –

    Number of instances per size, by default 1.

  • n_observations (int, default: 20 ) –

    Number of return observations, by default 20.

  • k (int, default: 2 ) –

    Number of clusters, by default 2.

  • seed (int | None, default: None ) –

    Random seed for reproducibility, by default None.

  • sizes (Sequence[int] | None, default: None ) –

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

Returns:

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:

  • max_runtime (float, default: 3600 ) –

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

  • quiet (bool, default: True ) –

    Suppress the SCIP solver output.

Returns:

  • 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: