Skip to content

contango.trading.analysis.graphing.pairwise_heatmap_grid

contango.trading.analysis.graphing.pairwise_heatmap_grid

PairwiseHeatmapGrid

PairwiseHeatmapGrid(config: C)

Bases: GraphType[PairwiseHeatmapGridConfig]

A graph type that shows a grid of 2D heatmaps, one panel per facet value.

Source code in src\contango\trading\analysis\graph_type.py
26
27
28
29
30
31
32
33
def __init__(self, config: C) -> None:
    """
    Initializes `GraphType`.

    Args:
        config: The matching configuration for the graph type.
    """
    self._config = config

build

build(df: DataFrame) -> go.Figure

Builds a grid of 2D heatmaps: param_x vs. param_y, one panel per unique value of facet_param.

Parameters:

Name Type Description Default
df DataFrame

The experiment DataFrame.

required

Returns:

Type Description
Figure

A plotly Figure with one subplot per facet_param value.

Source code in src\contango\trading\analysis\graphing\pairwise_heatmap_grid.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def build(self, df: pd.DataFrame) -> go.Figure:
    """
    Builds a grid of 2D heatmaps: param_x vs. param_y, one panel per unique
    value of facet_param.

    Args:
        df: The experiment DataFrame.

    Returns:
        A plotly Figure with one subplot per facet_param value.
    """
    plot_df = df.dropna(subset=[self.config.param_x, self.config.param_y, self.config.facet_param, self.config.target_metric])
    facet_values = sorted(plot_df[self.config.facet_param].unique())

    n = len(facet_values)
    cols = min(n, self.config.max_cols)

    if cols == 0:
        raise ValueError("No trades were made! Could not graph the pairwise heatmap grid.")

    rows = math.ceil(n / cols)

    fig = make_subplots(
        rows=rows,
        cols=cols,
        subplot_titles=[f"{self.config.facet_param}={v}" for v in facet_values],
        shared_xaxes=True,
        shared_yaxes=True,
    )

    zmin, zmax = plot_df[self.config.target_metric].min(), plot_df[self.config.target_metric].max()

    for i, val in enumerate(facet_values):
        mask: pd.Series = plot_df[self.config.facet_param] == val
        subset: pd.DataFrame = plot_df[mask]
        pivot = subset.pivot_table(
            index=self.config.param_y,
            columns=self.config.param_x,
            values=self.config.target_metric,
            aggfunc="mean",
        )

        fig.add_trace(  # type: ignore[unknownMemberType]
            go.Heatmap(
                z=pivot.values,
                x=pivot.columns,
                y=pivot.index,
                coloraxis="coloraxis",
            ),
            row=(i // cols) + 1,
            col=(i % cols) + 1,
        )

    fig.update_layout(  # type: ignore[unknownMemberType]
        title=f"Pairwise Heatmap Grid: {self.config.param_x} × {self.config.param_y}, faceted by {self.config.facet_param} (color = {self.config.target_metric})",
        coloraxis={"colorscale": "RdYlGn", "cmin": zmin, "cmax": zmax},
        height=320 * rows,
    )
    return fig

PairwiseHeatmapGridConfig dataclass

PairwiseHeatmapGridConfig(param_x: str, param_y: str, facet_param: str, target_metric: str = 'calmar_ratio', max_cols: int = 4)

Bases: GraphConfig

A graph configuration specific to the pairwise heatmap grid graph.

Attributes:

Name Type Description
param_x str

The parameter column for the heatmap x-axis.

param_y str

The parameter column for the heatmap y-axis.

facet_param str

The parameter column to facet panels by.

target_metric str

The name for the targeted metric used for cell color.

max_cols int

The maximum amount of panels per row before wrapping.