Source code for kaxanuk.attribution_analysis.dashboard.attribution_dashboard

"""
Attribution Dashboard — Main orchestrator class.

Coordinates all dashboard components, layouts, callbacks, and visualizations.
Follows the same pattern as kaxanuk.backtest_engine.dashboard.backtest_dashboard.
"""

import base64
import ipaddress
import logging
from pathlib import Path
from typing import TypedDict

import dash
import plotly.graph_objects as go
import pyarrow as pa
import pyarrow.compute as pc

from kaxanuk.attribution_analysis.dashboard.callbacks import register_callbacks
from kaxanuk.attribution_analysis.dashboard.components import create_header_with_logo
from kaxanuk.attribution_analysis.dashboard.constants import EXTERNAL_STYLESHEETS
from kaxanuk.attribution_analysis.dashboard.layouts import create_main_layout
from kaxanuk.attribution_analysis.dashboard.styles import INDEX_STRING
from kaxanuk.attribution_analysis.entities.attribution_options import LinkingMethod
from kaxanuk.attribution_analysis.entities.attribution_result import AttributionResult
from kaxanuk.attribution_analysis.modules.factor_totals import cumulative_totals_from_contributions

from kaxanuk.attribution_analysis.modules.attribution_visualizers_arrow import (
    create_factor_attribution_summary_chart,
    create_decomposition_bar_chart,
)

logger = logging.getLogger(__name__)


def _is_loopback_host(host: str) -> bool:
    """
    Whether `host` only accepts connections from this machine.

    Parameters
    ----------
    host : str
        Interface the server binds to: a host name or an IP address.

    Returns
    -------
    bool
        True for ``localhost`` and any loopback address (``127.0.0.0/8``,
        ``::1``); False otherwise, including ``0.0.0.0`` and host names.
    """
    if host.lower() == "localhost":
        return True
    try:
        return ipaddress.ip_address(host.strip("[]")).is_loopback
    except ValueError:
        return False


def _placeholder_figure(message: str) -> go.Figure:
    """
    Build an empty figure carrying a centred explanatory message.

    Used in place of a chart whose backing data was not produced (for
    example the factor-model charts when only Brinson-Fachler ran).

    Parameters
    ----------
    message : str
        Text to display in the middle of the otherwise blank figure.

    Returns
    -------
    plotly.graph_objects.Figure
        A figure with no traces, no axes, and a single annotation.
    """
    fig = go.Figure()
    fig.add_annotation(
        text=message,
        xref="paper", yref="paper",
        x=0.5, y=0.5, showarrow=False,
        font={"size": 14, "family": "Segoe UI"},
    )
    fig.update_layout(
        template="plotly_white",
        xaxis={"visible": False},
        yaxis={"visible": False},
        margin={"l": 40, "r": 40, "t": 40, "b": 40},
    )
    return fig


[docs] class AttributionResultDict(TypedDict, total=False): """ Pre-calculated attribution results consumed by :class:`AttributionDashboard`. Attributes ---------- portfolio_returns : pyarrow.Table Columns: ``[date, portfolio_returns]``. simulated_rets : pyarrow.Table Columns: ``[date, factor1, factor2, ...]``. portfolio_attribution_ts : pyarrow.Table Columns: ``[date, factor1, factor2, ...]``. pct_df_returns : pyarrow.Table Columns: ``[date, factor1, factor2, ...]``. total_pct_decomposition : dict Mapping of ``{factor_name: contribution_fraction}``. summary_stats : dict Mapping of ``{metric_name: value}``. brinson_fachler_indexes : pyarrow.Table or None Brinson-Fachler attribution index table, if computed. cumulative_totals : pyarrow.Table or None Columns: ``[date, portfolio_returns, factor_returns, idiosyncratic_returns]`` from the factor model, if computed, plus ``carry_returns`` / ``dividends_returns`` when those return components were supplied (``factor_returns`` then excludes them). When absent but ``simulated_rets`` and ``portfolio_returns`` are given, the dashboard derives it from them. linking : LinkingMethod or str Linking method ``simulated_rets`` was built with; only read when ``cumulative_totals`` is derived. Default ``carino``, the factor model's default. portfolio_name : str Display name of the portfolio. benchmark_name : str Display name of the benchmark. """ portfolio_returns: pa.Table simulated_rets: pa.Table portfolio_attribution_ts: pa.Table pct_df_returns: pa.Table total_pct_decomposition: dict summary_stats: dict brinson_fachler_indexes: pa.Table | None cumulative_totals: pa.Table | None linking: LinkingMethod | str portfolio_name: str benchmark_name: str
[docs] class AttributionDashboard: """ Interactive Dash-based dashboard for attribution analysis. Metrics are pre-calculated by the engine and passed in rather than computed inside the dashboard. Parameters ---------- attribution_results : AttributionResultDict Pre-calculated attribution results to display. Only ``portfolio_returns`` and ``summary_stats`` are required; every factor-model-specific key (``simulated_rets``, ``portfolio_attribution_ts``, ``pct_df_returns``, ``total_pct_decomposition``, ``cumulative_totals``) is optional and, when absent, the corresponding chart/tab renders an "enable it in configuration" placeholder. portfolio_name : str or None, default None Display name of the portfolio, shown in the dashboard header. benchmark_name : str or None, default None Display name of the benchmark. logo_path : str or None, default None Path to a logo image file to embed in the dashboard header. days_of_smoothing : int, default 45 Number of days used for smoothing in relevant chart components. date_column : str, default "date" Name of the date column shared across the attribution result tables. Attributes ---------- results : AttributionResultDict The raw attribution results passed to the constructor. date_column : str Name of the date column shared across the attribution result tables. portfolio_returns : pyarrow.Table Columns: ``[date, portfolio_returns]``. simulated_rets : pyarrow.Table Columns: ``[date, factor1, factor2, ...]``. portfolio_attribution_ts : pyarrow.Table Columns: ``[date, factor1, factor2, ...]``. pct_df_returns : pyarrow.Table Columns: ``[date, factor1, factor2, ...]``. total_pct_decomposition : dict Mapping of ``{factor_name: contribution_fraction}``. summary_stats : dict Mapping of ``{metric_name: value}``. brinson_fachler_indexes : pyarrow.Table or None Brinson-Fachler attribution index table, if computed. cumulative_totals : pyarrow.Table or None The factor model's cumulative portfolio / factor / idiosyncratic return, if computed (or derived from ``simulated_rets``); drives the headline attribution chart. portfolio_name : str or None Display name of the portfolio. benchmark_name : str or None Display name of the benchmark. logo_path : str or None Path to the logo image file, if any. days_of_smoothing : int Number of days used for smoothing in relevant chart components. app : dash.Dash The underlying Dash application instance. """ def __init__( self, attribution_results: AttributionResultDict, portfolio_name: str | None = None, benchmark_name: str | None = None, logo_path: str | None = None, days_of_smoothing: int = 45, date_column: str = "date", ) -> None: self.results = attribution_results self.date_column = date_column # Only ``portfolio_returns`` (via a fallback chain in the pipeline) and # ``summary_stats`` are always present. Every factor-model-specific key # is optional so the dashboard can run on Brinson-Fachler results alone. self.portfolio_returns = attribution_results.get('portfolio_returns') self.simulated_rets = attribution_results.get('simulated_rets') self.portfolio_attribution_ts = attribution_results.get('portfolio_attribution_ts') self.pct_df_returns = attribution_results.get('pct_df_returns') self.total_pct_decomposition = attribution_results.get('total_pct_decomposition') self.summary_stats = attribution_results.get('summary_stats') or {} self.brinson_fachler_indexes = attribution_results.get('brinson_fachler_indexes') self.cumulative_totals = attribution_results.get('cumulative_totals') if self.cumulative_totals is None and self.simulated_rets is not None and self.portfolio_returns is not None: # Results built with the earlier keys carry no totals: derive them, without linking again. self.cumulative_totals = cumulative_totals_from_contributions( self.simulated_rets, self.portfolio_returns, attribution_results.get('linking', LinkingMethod.CARINO), date_column, ) self.portfolio_name = portfolio_name self.benchmark_name = benchmark_name self.logo_path = logo_path self.days_of_smoothing = days_of_smoothing self.app = dash.Dash(__name__, external_stylesheets=EXTERNAL_STYLESHEETS) self._setup_layout() self._setup_callbacks() def _encode_logo(self) -> str | None: """ Encode the configured logo image as a base64 data URI. Returns ------- str or None A ``"data:image/jpeg;base64,..."`` data URI if `logo_path` is set, points to an existing file, and was read successfully. Returns None if no logo is configured, the file doesn't exist, or reading it fails. """ if self.logo_path: logo_path = Path(self.logo_path) if logo_path.exists(): try: with logo_path.open("rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode() return f"data:image/jpeg;base64,{encoded_string}" except Exception as e: logger.warning("Could not encode logo: %s", e) return None return None def _calculate_key_metrics(self) -> dict: """ Extract the headline metrics shown in the dashboard's metric cards. Returns ------- dict Mapping with keys ``total_return``, ``annualized_return``, ``sharpe_ratio``, ``max_drawdown``, ``annualized_vol``, and ``skewness``, each a float pulled from `summary_stats` (NaN if the key is missing, e.g. when no date has a return, so the card shows "N/A"). """ stats = self.summary_stats def _get_stat(key: str, default: float = float("nan")) -> float: return float(stats.get(key, default)) return { 'total_return': _get_stat('Total Return'), 'annualized_return': _get_stat('Annualized Return'), 'sharpe_ratio': _get_stat('Sharpe Ratio'), 'max_drawdown': _get_stat('Max Drawdown'), 'annualized_vol': _get_stat('Annualized Vol'), 'skewness': _get_stat('Skewness'), } def _header_dates(self) -> tuple[str, str]: """ First and last date shown in the header. Taken from the ``portfolio_returns`` rows with a return (non-null and non-NaN, the same mask as the KPI series behind the summary statistics); when there are none, from the Brinson-Fachler indexes; else ``"n/a"``. Returns ------- tuple[str, str] ``(start, end)`` as ``YYYY-MM-DD`` strings, or ``("n/a", "n/a")``. """ dates = None if self.portfolio_returns is not None: values = self.portfolio_returns.column("portfolio_returns") has_return = pc.and_kleene(pc.is_valid(values), pc.invert(pc.is_nan(values))) dates = self.portfolio_returns.filter(has_return).column(self.date_column) if (dates is None or len(dates) == 0) and self.brinson_fachler_indexes is not None: dates = self.brinson_fachler_indexes.column(self.date_column) if dates is None or len(dates) == 0: return "n/a", "n/a" return dates[0].as_py().strftime('%Y-%m-%d'), dates[-1].as_py().strftime('%Y-%m-%d') def _setup_layout(self) -> None: """ Build and assign the Dash application's layout. Computes the key metrics, encodes the logo, derives the portfolio's date range, and assembles the header, attribution summary chart, and decomposition bar chart into `self.app.layout`. """ metrics = self._calculate_key_metrics() logo_src = self._encode_logo() start_date, end_date = self._header_dates() header_content = create_header_with_logo( logo_src, self.portfolio_name or "Portfolio", start_date, end_date, ) if self.cumulative_totals is not None: attribution_summary_chart = create_factor_attribution_summary_chart( self.cumulative_totals, date_column=self.date_column, ) else: attribution_summary_chart = _placeholder_figure( "Factor model not available — enable factor_model_method in configuration." ) if self.total_pct_decomposition is not None: decomposition_bar = create_decomposition_bar_chart( self.total_pct_decomposition, ) else: decomposition_bar = _placeholder_figure( "Factor model not available — enable factor_model_method in configuration." ) self.app.layout = create_main_layout( header_content=header_content, metrics=metrics, attribution_summary_chart=attribution_summary_chart, decomposition_bar_chart=decomposition_bar, ) def _setup_callbacks(self) -> None: """Register all interactive Dash callbacks on `self.app`.""" register_callbacks(self.app, self)
[docs] def run_server( self, *, debug: bool = False, port: int = 8050, host: str = "127.0.0.1", **kwargs, ) -> None: """ Start the Dash development server. Parameters ---------- debug : bool, default False Whether to run the Dash app in debug mode. Debug mode serves the Werkzeug debugger: error pages show tracebacks with source code to anyone, and its console, which runs arbitrary code, is guarded only by a PIN. With a `host` that is not a loopback address a warning is logged. port : int, default 8050 Port on which to serve the dashboard. host : str, default "127.0.0.1" Interface the server binds to. **kwargs Passed through to ``dash.Dash.run``. """ if debug and not _is_loopback_host(host): logger.warning( "Dash debug mode is on and the dashboard listens on %r, which is not a loopback address: " "anyone who can reach port %s sees tracebacks with source code when an error occurs, and the " "Werkzeug debugger console, which runs code on this machine, is guarded only by its PIN. " "Use debug mode only with host 127.0.0.1.", host, port, ) self.app.index_string = INDEX_STRING logger.info("Dashboard will be available at: http://%s:%s", host, port) self.app.run(debug=debug, port=port, host=host, use_reloader=False, **kwargs)
[docs] def create_dashboard_from_attribution( attribution_results: AttributionResultDict, portfolio_name: str | None = None, benchmark_name: str | None = None, logo_path: str | None = None, days_of_smoothing: int = 45, date_column: str = "date", ) -> AttributionDashboard: """ Create an :class:`AttributionDashboard` from pre-calculated results. Parameters ---------- attribution_results : AttributionResultDict Pre-calculated attribution results to display. portfolio_name : str or None, default None Display name of the portfolio, shown in the dashboard header. benchmark_name : str or None, default None Display name of the benchmark. logo_path : str or None, default None Path to a logo image file to embed in the dashboard header. days_of_smoothing : int, default 45 Number of days used for smoothing in relevant chart components. date_column : str, default "date" Name of the date column shared across the attribution result tables. Returns ------- AttributionDashboard A dashboard instance configured with the given results and options, ready to be served with :meth:`AttributionDashboard.run_server`. """ return AttributionDashboard( attribution_results=attribution_results, portfolio_name=portfolio_name, benchmark_name=benchmark_name, logo_path=logo_path, days_of_smoothing=days_of_smoothing, date_column=date_column, )
[docs] def create_dashboard_from_result( result: AttributionResult, portfolio_name: str | None = None, benchmark_name: str | None = None, logo_path: str | None = None, days_of_smoothing: int = 45, date_column: str = "date", ) -> AttributionDashboard: """ Create an :class:`AttributionDashboard` from an :class:`AttributionResult`. Maps the result's tables to the dashboard keys, so callers holding a result never build an :class:`AttributionResultDict` by hand. When the factor model ran, its portfolio return feeds the header, metric cards and returns/drawdown tabs; otherwise the Brinson-Fachler per-period one does. Parameters ---------- result : AttributionResult What ``run_attribution`` (or ``main``) returned. portfolio_name : str or None, default None Display name of the portfolio, shown in the dashboard header. benchmark_name : str or None, default None Display name of the benchmark. logo_path : str or None, default None Path to a logo image file to embed in the dashboard header. days_of_smoothing : int, default 45 Number of days used for smoothing in relevant chart components. date_column : str, default "date" Name of the date column shared across the result tables. Returns ------- AttributionDashboard A dashboard ready to be served with :meth:`AttributionDashboard.run_server`. """ attribution_results: AttributionResultDict = {} if result.brinson_fachler is not None: attribution_results['brinson_fachler_indexes'] = result.brinson_fachler.cumulative attribution_results['portfolio_returns'] = result.brinson_fachler.per_period.select( [date_column, "portfolio_returns"] ) if result.factor_model is not None: attribution_results.update({ 'portfolio_returns': result.factor_model.portfolio_returns, 'simulated_rets': result.factor_model.cumulative_contributions, 'portfolio_attribution_ts': result.factor_model.contributions, 'pct_df_returns': result.factor_model.daily_shares, 'total_pct_decomposition': dict(result.factor_model.cumulative_shares), 'cumulative_totals': result.factor_model.cumulative_totals, 'linking': result.factor_model.linking, }) attribution_results['summary_stats'] = dict(result.summary_stats) return create_dashboard_from_attribution( attribution_results=attribution_results, portfolio_name=portfolio_name, benchmark_name=benchmark_name, logo_path=logo_path, days_of_smoothing=days_of_smoothing, date_column=date_column, )