Skip to content

trading.analyzer.graphing.metric_distribution

trading.analyzer.graphing.metric_distribution

build_metric_distribution

build_metric_distribution(df: DataFrame, group_by: str, target_metric: str = 'total_return', plot_type: str = 'box') -> go.Figure

Builds a distribution plot of target_metric grouped by group_by.

Parameters:

Name Type Description Default
df DataFrame

Experiment DataFrame.

required
group_by str

Column to group by — a parameter column, or a pre-binned version of one for continuous parameters with many distinct values.

required
target_metric str

Metric column to show the distribution of.

'total_return'
plot_type str

"box" (default) or "violin".

'box'

Returns:

Type Description
Figure

A plotly Figure.

Source code in src\contango\trading\analyzer\graphing\metric_distribution.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def build_metric_distribution(
    df: pd.DataFrame,
    group_by: str,
    target_metric: str = "total_return",
    plot_type: str = "box",
) -> go.Figure:
    """
    Builds a distribution plot of `target_metric` grouped by `group_by`.

    Args:
        df: Experiment DataFrame.
        group_by: Column to group by — a parameter column, or a
                  pre-binned version of one for continuous parameters with many
                  distinct values.
        target_metric: Metric column to show the distribution of.
        plot_type: "box" (default) or "violin".

    Returns:
        A plotly Figure.
    """
    plot_df = df.dropna(subset=[group_by, target_metric]).copy()
    plot_df[group_by] = plot_df[group_by].astype(str)

    fig_fn = px.box if plot_type == "box" else px.violin    # type: ignore[unknownMemberType]
    fig = fig_fn(
        plot_df,
        x=group_by,
        y=target_metric,
        points="all",
        title=f"Distribution of {target_metric} by {group_by}",
        labels={group_by: group_by, target_metric: target_metric},
    )
    fig.update_layout()  # type: ignore[unknownMemberType]
    return fig