<a id="skfolio-distance-graphdistance"></a>

# skfolio.distance.GraphDistance

<a id="skfolio.distance.GraphDistance"></a>

### *class* skfolio.distance.GraphDistance(\*, max_hops=2, decay=0.5, normalize_adjacency=True)

Graph Distance estimator.

The codependence is computed from cosine similarities between the assets’
dependency profiles. The distance is then computed as $\sqrt{1-S}$, where
$S$ is the codependence matrix.

A dependency profile contains the weights of an asset’s direct and indirect
dependencies. An edge from $i$ to $j$ represents a dependency of
$i$ on $j$. For adjacency matrix $M$, after optional row
normalization, the profiles are the asset rows of:

$$
\sum_{h=1}^{H} \alpha^{h-1} M^h
$$

where $H$ = `max_hops` and $\alpha$ = `decay`.

* **Parameters:**
  **max_hops** *int, default=2*
  : Maximum number of edges traversed when computing dependencies. A value of 1
    includes only direct dependencies and 2 also includes their dependencies. Must
    be at least 1. Nodes can be revisited through cycles.

  **decay** *float, default=0.5*
  : Weight multiplier for each additional hop, in $[0, 1]$. A value of zero
    includes only direct dependencies.

  **normalize_adjacency** *bool, default=True*
  : If True, the outgoing weights of each node are normalized to sum to one before
    propagation. If False, the original edge weights are used.
* **Attributes:**
  **codependence_** *ndarray of shape (n_assets, n_assets)*
  : Codependence matrix of cosine similarities between dependency profiles, with
    values in $[0, 1]$.

  **distance_** *ndarray of shape (n_assets, n_assets)*
  : Euclidean distances between dependency profiles normalized to unit length,
    divided by $\sqrt{2}$. Values are in $[0, 1]$, with a zero diagonal
    for assets with positive outgoing edge weights.

  **n_features_in_** *int*
  : Number of assets seen during fitting.

  **feature_names_in_** *ndarray of shape (`n_features_in_`,)*
  : Names of assets seen during fitting.

### Methods

| [`fit`](#skfolio.distance.GraphDistance.fit)(X[, y, graphs])                   | Fit the Graph Distance estimator.                                                        |
|----------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------|
| [`get_metadata_routing`](#skfolio.distance.GraphDistance.get_metadata_routing)()                | Get metadata routing of this object.                                                     |
| [`get_params`](#skfolio.distance.GraphDistance.get_params)([deep])                    | Get parameters for this estimator.                                                       |
| [`partial_fit`](#skfolio.distance.GraphDistance.partial_fit)(X[, y, graphs])           | Update distances using the latest graph.                                                 |
| [`set_fit_request`](#skfolio.distance.GraphDistance.set_fit_request)(\*[, graphs])         | Configure whether metadata should be requested to be passed to the `fit` method.         |
| [`set_params`](#skfolio.distance.GraphDistance.set_params)(\*\*params)                | Set the parameters of this estimator.                                                    |
| [`set_partial_fit_request`](#skfolio.distance.GraphDistance.set_partial_fit_request)(\*[, graphs]) | Configure whether metadata should be requested to be passed to the `partial_fit` method. |

#### SEE ALSO
[`skfolio.containers.Graph`](https://skfolio.org/generated/skfolio.containers.Graph.html.md#skfolio.containers.Graph)
: Weighted directed graph with named nodes.

[`skfolio.containers.GraphSeries`](https://skfolio.org/generated/skfolio.containers.GraphSeries.html.md#skfolio.containers.GraphSeries)
: Graphs indexed by observation.

### Notes

Estimation uses the graph at the final observation. Graph observations are assumed
to be chronological, with each graph containing only information available at that
observation.

Assets absent from the graph or without positive outgoing edges have NaN rows and
columns in both fitted matrices, including their diagonals. The prior determines
which assets are investable. Negative edge weights are not supported.

For `max_hops=1` or `decay=0`, only direct dependencies are included and row
normalization has no effect on the distances. Indirect dependencies can include
graph nodes outside the investment universe.

### Examples

Asset B depends on two suppliers, with weights 3 and 1. It shares one supplier
with A and the other with C:

```pycon
>>> import pandas as pd
>>> from skfolio.containers import Graph, GraphSeries
>>> from skfolio.distance import GraphDistance
>>> X = pd.DataFrame({"A": [0.01], "B": [-0.02], "C": [0.03]})
>>> graph = Graph.from_edges(
...     [
...         ("A", "Supplier 1", 1),
...         ("B", "Supplier 1", 3),
...         ("B", "Supplier 2", 1),
...         ("C", "Supplier 2", 1),
...     ],
...     nodes=["A", "B", "C", "Supplier 1", "Supplier 2"],
... )
>>> graphs = GraphSeries([graph], observations=X.index)
>>> model = GraphDistance().fit(X, graphs=graphs)
>>> model.distance_.round(3)
array([[0.   , 0.227, 1.   ],
       [0.227, 0.   , 0.827],
       [1.   , 0.827, 0.   ]])
```

<a id="skfolio.distance.GraphDistance.fit"></a>

#### fit(X, y=None, \*, graphs=None)

Fit the Graph Distance estimator.

* **Parameters:**
  **X** *pandas.DataFrame of shape (n_observations, n_assets)*
  : Asset returns with unique string column names identifying assets in the
    graph. At least one asset is required. Return values are not used and can
    contain NaN.

  **y** *Ignored*
  : Not used, present for API consistency by convention.

  **graphs** *GraphSeries, required*
  : Graphs for the training observations. The graph at the final observation
    must be present. Passing `graphs` through an optimizer or cross-validation
    requires scikit-learn metadata routing to be enabled.
* **Returns:**
  **self** *GraphDistance*
  : Fitted estimator.

<a id="skfolio.distance.GraphDistance.get_metadata_routing"></a>

#### get_metadata_routing()

Get metadata routing of this object.

Please check [User Guide](https://skfolio.org/user_guide/metadata_routing.html.md#metadata-routing) on how the routing
mechanism works.

* **Returns:**
  **routing** *MetadataRequest*
  : A `MetadataRequest` encapsulating
    routing information.

<a id="skfolio.distance.GraphDistance.get_params"></a>

#### get_params(deep=True)

Get parameters for this estimator.

* **Parameters:**
  **deep** *bool, default=True*
  : If True, will return the parameters for this estimator and
    contained subobjects that are estimators.
* **Returns:**
  **params** *dict*
  : Parameter names mapped to their values.

<a id="skfolio.distance.GraphDistance.partial_fit"></a>

#### partial_fit(X, y=None, \*, graphs=None)

Update distances using the latest graph.

* **Parameters:**
  **X** *pandas.DataFrame of shape (n_observations, n_assets)*
  : New asset returns with unique string column names identifying assets in the
    graph. Columns must match previous calls. Return values are not used and
    can contain NaN.

  **y** *Ignored*
  : Not used, present for API consistency by convention.

  **graphs** *GraphSeries, required*
  : Graphs for the new observations. The graph at the final observation must
    be present. Passing `graphs` through an optimizer requires scikit-learn
    metadata routing to be enabled.
* **Returns:**
  **self** *GraphDistance*
  : Updated estimator.

<a id="skfolio.distance.GraphDistance.requires_covariance_input"></a>

#### *property* requires_covariance_input

Whether `X` must contain a covariance matrix.

Return-consuming distances use the default value of `False`. Subclasses
consuming covariance override this property. Its value must be available
before fitting and reflect parameter changes made through `set_params`.
The `pairwise` input tag is derived from this property.

<a id="skfolio.distance.GraphDistance.set_fit_request"></a>

#### set_fit_request(\*, graphs='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the `fit` method.

Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with `enable_metadata_routing=True` (see `sklearn.set_config`).
Please check the [User Guide](https://skfolio.org/user_guide/metadata_routing.html.md#metadata-routing) on how the routing
mechanism works.

The options for each parameter are:

- `True`: metadata is requested, and passed to `fit` if provided. The request is ignored if metadata is not provided.
- `False`: metadata is not requested and the meta-estimator will not pass it to `fit`.
- `None`: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
- `str`: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (`sklearn.utils.metadata_routing.UNCHANGED`) retains the
existing request. This allows you to change the request for some
parameters and not others.

#### Versionadded
Added in version 1.3.

* **Parameters:**
  **graphs** *str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED*
  : Metadata routing for `graphs` parameter in `fit`.
* **Returns:**
  **self** *object*
  : The updated object.

<a id="skfolio.distance.GraphDistance.set_params"></a>

#### set_params(\*\*params)

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects
(such as `Pipeline`). The latter have
parameters of the form `<component>__<parameter>` so that it’s
possible to update each component of a nested object.

* **Parameters:**
  **\*\*params** *dict*
  : Estimator parameters.
* **Returns:**
  **self** *estimator instance*
  : Estimator instance.

<a id="skfolio.distance.GraphDistance.set_partial_fit_request"></a>

#### set_partial_fit_request(\*, graphs='$UNCHANGED$')

Configure whether metadata should be requested to be passed to the `partial_fit` method.

Note that this method is only relevant when this estimator is used as a
sub-estimator within a meta-estimator and metadata routing is enabled
with `enable_metadata_routing=True` (see `sklearn.set_config`).
Please check the [User Guide](https://skfolio.org/user_guide/metadata_routing.html.md#metadata-routing) on how the routing
mechanism works.

The options for each parameter are:

- `True`: metadata is requested, and passed to `partial_fit` if provided. The request is ignored if metadata is not provided.
- `False`: metadata is not requested and the meta-estimator will not pass it to `partial_fit`.
- `None`: metadata is not requested, and the meta-estimator will raise an error if the user provides it.
- `str`: metadata should be passed to the meta-estimator with this given alias instead of the original name.

The default (`sklearn.utils.metadata_routing.UNCHANGED`) retains the
existing request. This allows you to change the request for some
parameters and not others.

#### Versionadded
Added in version 1.3.

* **Parameters:**
  **graphs** *str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED*
  : Metadata routing for `graphs` parameter in `partial_fit`.
* **Returns:**
  **self** *object*
  : The updated object.

