skfolio.distance.GraphDistance#
- class skfolio.distance.GraphDistance(*, max_hops=2, decay=0.5, normalize_adjacency=True)[source]#
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_hopsand \(\alpha\) =decay.- Parameters:
- max_hopsint, 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.
- decayfloat, default=0.5
Weight multiplier for each additional hop, in \([0, 1]\). A value of zero includes only direct dependencies.
- normalize_adjacencybool, 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(X[, y, graphs])Fit the Graph Distance estimator.
Get metadata routing of this object.
get_params([deep])Get parameters for this estimator.
partial_fit(X[, y, graphs])Update distances using the latest graph.
set_fit_request(*[, graphs])Configure whether metadata should be requested to be passed to the
fitmethod.set_params(**params)Set the parameters of this estimator.
set_partial_fit_request(*[, graphs])Configure whether metadata should be requested to be passed to the
partial_fitmethod.See also
skfolio.containers.GraphWeighted directed graph with named nodes.
skfolio.containers.GraphSeriesGraphs 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=1ordecay=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:
>>> 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. ]])
- fit(X, y=None, *, graphs=None)[source]#
Fit the Graph Distance estimator.
- Parameters:
- Xpandas.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.
- yIgnored
Not used, present for API consistency by convention.
- graphsGraphSeries, required
Graphs for the training observations. The graph at the final observation must be present. Passing
graphsthrough an optimizer or cross-validation requires scikit-learn metadata routing to be enabled.
- Returns:
- selfGraphDistance
Fitted estimator.
- get_metadata_routing()#
Get metadata routing of this object.
Please check User Guide on how the routing mechanism works.
- Returns:
- routingMetadataRequest
A
MetadataRequestencapsulating routing information.
- get_params(deep=True)#
Get parameters for this estimator.
- Parameters:
- deepbool, default=True
If True, will return the parameters for this estimator and contained subobjects that are estimators.
- Returns:
- paramsdict
Parameter names mapped to their values.
- partial_fit(X, y=None, *, graphs=None)[source]#
Update distances using the latest graph.
- Parameters:
- Xpandas.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.
- yIgnored
Not used, present for API consistency by convention.
- graphsGraphSeries, required
Graphs for the new observations. The graph at the final observation must be present. Passing
graphsthrough an optimizer requires scikit-learn metadata routing to be enabled.
- Returns:
- selfGraphDistance
Updated estimator.
- property requires_covariance_input#
Whether
Xmust 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 throughset_params. Thepairwiseinput tag is derived from this property.
- set_fit_request(*, graphs='$UNCHANGED$')#
Configure whether metadata should be requested to be passed to the
fitmethod.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(seesklearn.set_config). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.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.Added in version 1.3.
- Parameters:
- graphsstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
graphsparameter infit.
- Returns:
- selfobject
The updated object.
- 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:
- **paramsdict
Estimator parameters.
- Returns:
- selfestimator instance
Estimator instance.
- set_partial_fit_request(*, graphs='$UNCHANGED$')#
Configure whether metadata should be requested to be passed to the
partial_fitmethod.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(seesklearn.set_config). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed topartial_fitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topartial_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.Added in version 1.3.
- Parameters:
- graphsstr, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED
Metadata routing for
graphsparameter inpartial_fit.
- Returns:
- selfobject
The updated object.