Skip to content

API Reference

Main Entry Point

FinancialSankey

finflow_sankey.FinancialSankey

Main entry point for FinFlow Sankey.

Source code in finflow_sankey/__init__.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 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
 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
 98
 99
100
101
102
103
104
105
class FinancialSankey:
    """Main entry point for FinFlow Sankey."""

    @classmethod
    def income_statement(
        cls,
        data: pl.DataFrame | pl.LazyFrame,
        *,
        period: str | None = None,
        currency: str | None = None,
        mapping: AccountMapper | dict[str, Any] | str | Path | None = None,
        layout: str | None = None,
    ) -> SankeyPipeline:
        """Create an income statement Sankey pipeline."""
        template = IncomeStatementTemplate(layout=layout)
        return SankeyPipeline(
            data=data,
            template=template,
            period=period,
            currency=currency,
            mapping=mapping,
            layout=layout,
        )

    @classmethod
    def cash_flow_statement(
        cls,
        data: pl.DataFrame | pl.LazyFrame,
        *,
        period: str | None = None,
        currency: str | None = None,
        mapping: AccountMapper | dict[str, Any] | str | Path | None = None,
        layout: str | None = None,
    ) -> SankeyPipeline:
        """Create a cash flow statement Sankey pipeline."""
        from finflow_sankey.templates.cash_flow import CashFlowStatementTemplate

        template = CashFlowStatementTemplate(layout=layout)
        return SankeyPipeline(
            data=data,
            template=template,
            period=period,
            currency=currency,
            mapping=mapping,
            layout=layout,
        )

    @classmethod
    def balance_sheet_reconciliation(
        cls,
        data: pl.DataFrame | pl.LazyFrame,
        *,
        as_of: str | None = None,
        currency: str | None = None,
        mapping: AccountMapper | dict[str, Any] | str | Path | None = None,
        layout: str | None = None,
    ) -> SankeyPipeline:
        """Create a balance sheet reconciliation Sankey pipeline."""
        from finflow_sankey.templates.balance_sheet import BalanceSheetReconciliationTemplate

        template = BalanceSheetReconciliationTemplate(layout=layout)
        return SankeyPipeline(
            data=data,
            template=template,
            period=as_of,
            currency=currency,
            mapping=mapping,
            layout=layout,
        )

    @classmethod
    def multi_period_compare(
        cls,
        data: pl.DataFrame | pl.LazyFrame,
        *,
        currency: str | None = None,
        mapping: AccountMapper | dict[str, Any] | str | Path | None = None,
        layout: str | None = None,
    ) -> SankeyPipeline:
        """Create a multi-period comparison Sankey pipeline."""
        from finflow_sankey.templates.multi_period import MultiPeriodComparisonTemplate

        template = MultiPeriodComparisonTemplate(layout=layout)
        return SankeyPipeline(
            data=data,
            template=template,
            period=None,
            currency=currency,
            mapping=mapping,
            layout=layout,
        )

income_statement(data, *, period=None, currency=None, mapping=None, layout=None) classmethod

Create an income statement Sankey pipeline.

Source code in finflow_sankey/__init__.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@classmethod
def income_statement(
    cls,
    data: pl.DataFrame | pl.LazyFrame,
    *,
    period: str | None = None,
    currency: str | None = None,
    mapping: AccountMapper | dict[str, Any] | str | Path | None = None,
    layout: str | None = None,
) -> SankeyPipeline:
    """Create an income statement Sankey pipeline."""
    template = IncomeStatementTemplate(layout=layout)
    return SankeyPipeline(
        data=data,
        template=template,
        period=period,
        currency=currency,
        mapping=mapping,
        layout=layout,
    )

cash_flow_statement(data, *, period=None, currency=None, mapping=None, layout=None) classmethod

Create a cash flow statement Sankey pipeline.

Source code in finflow_sankey/__init__.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
@classmethod
def cash_flow_statement(
    cls,
    data: pl.DataFrame | pl.LazyFrame,
    *,
    period: str | None = None,
    currency: str | None = None,
    mapping: AccountMapper | dict[str, Any] | str | Path | None = None,
    layout: str | None = None,
) -> SankeyPipeline:
    """Create a cash flow statement Sankey pipeline."""
    from finflow_sankey.templates.cash_flow import CashFlowStatementTemplate

    template = CashFlowStatementTemplate(layout=layout)
    return SankeyPipeline(
        data=data,
        template=template,
        period=period,
        currency=currency,
        mapping=mapping,
        layout=layout,
    )

balance_sheet_reconciliation(data, *, as_of=None, currency=None, mapping=None, layout=None) classmethod

Create a balance sheet reconciliation Sankey pipeline.

Source code in finflow_sankey/__init__.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
@classmethod
def balance_sheet_reconciliation(
    cls,
    data: pl.DataFrame | pl.LazyFrame,
    *,
    as_of: str | None = None,
    currency: str | None = None,
    mapping: AccountMapper | dict[str, Any] | str | Path | None = None,
    layout: str | None = None,
) -> SankeyPipeline:
    """Create a balance sheet reconciliation Sankey pipeline."""
    from finflow_sankey.templates.balance_sheet import BalanceSheetReconciliationTemplate

    template = BalanceSheetReconciliationTemplate(layout=layout)
    return SankeyPipeline(
        data=data,
        template=template,
        period=as_of,
        currency=currency,
        mapping=mapping,
        layout=layout,
    )

multi_period_compare(data, *, currency=None, mapping=None, layout=None) classmethod

Create a multi-period comparison Sankey pipeline.

Source code in finflow_sankey/__init__.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@classmethod
def multi_period_compare(
    cls,
    data: pl.DataFrame | pl.LazyFrame,
    *,
    currency: str | None = None,
    mapping: AccountMapper | dict[str, Any] | str | Path | None = None,
    layout: str | None = None,
) -> SankeyPipeline:
    """Create a multi-period comparison Sankey pipeline."""
    from finflow_sankey.templates.multi_period import MultiPeriodComparisonTemplate

    template = MultiPeriodComparisonTemplate(layout=layout)
    return SankeyPipeline(
        data=data,
        template=template,
        period=None,
        currency=currency,
        mapping=mapping,
        layout=layout,
    )

Pipeline

SankeyPipeline

finflow_sankey.core.pipeline.SankeyPipeline

Pipeline for building and rendering financial Sankey diagrams.

Source code in finflow_sankey/core/pipeline.py
 23
 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
 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
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
class SankeyPipeline:
    """Pipeline for building and rendering financial Sankey diagrams."""

    def __init__(
        self,
        data: pl.DataFrame | pl.LazyFrame,
        template: StatementTemplate,
        period: str | None = None,
        currency: str | None = None,
        default_palette: ColorPalette | None = None,
        mapping: AccountMapper | dict | str | Path | None = None,
        layout: str | None = None,
    ):
        self._lf = self._to_lazy_frame(data)
        self.template = template
        self.period = period
        self.currency = currency
        self.default_palette = default_palette
        self.layout = layout
        self._mapper = self._resolve_mapper(mapping)
        self._validated_df: pl.DataFrame | None = None
        self._graph: FinancialGraph | None = None
        self._sign_normalizer = SignNormalizer(expense_sign="positive")
        self._unit_normalizer = UnitNormalizer()

    def _to_lazy_frame(self, data: pl.DataFrame | pl.LazyFrame) -> pl.LazyFrame:
        """Convert input data to Polars LazyFrame."""
        if isinstance(data, pl.LazyFrame):
            return data
        if isinstance(data, pl.DataFrame):
            return data.lazy()

        raise TypeError(
            "Input data must be a Polars DataFrame or Polars LazyFrame."
        )

    def _resolve_mapper(
        self, mapping: AccountMapper | dict | str | Path | None
    ) -> AccountMapper | None:
        if mapping is None:
            return None
        if isinstance(mapping, AccountMapper):
            return mapping
        if isinstance(mapping, dict):
            return AccountMapper.from_dict(mapping)
        return AccountMapper.from_yaml(mapping)

    def validate(self, tolerance: float = 0.01) -> "SankeyPipeline":
        """Validate input data."""
        df = self._prepare_df()
        validator = FinancialValidator(self.template.statement_type)
        self._validated_df = validator.validate(
            df,
            required_roles=self.template.required_roles(),
            tolerance=tolerance,
        )
        return self

    def normalize_signs(self) -> "SankeyPipeline":
        """Normalize signs (already done in _prepare_df by default)."""
        return self

    def group_minor(
        self,
        min_pct: float | None = None,
        min_value: float | None = None,
        top_n: int | None = None,
        label: str = "Other",
    ) -> "SankeyPipeline":
        """Group minor accounts into Other.

        Args:
            min_pct: Group accounts below this percentage of total sankey_value.
            min_value: Group accounts below this absolute sankey_value.
            top_n: Keep top_n accounts, group the rest.
            label: Label for the grouped accounts.
        """
        if self._validated_df is None:
            raise RuntimeError("Must call validate() before group_minor().")

        df = self._validated_df

        if min_pct is not None and min_value is not None:
            total = df["sankey_value"].sum()
            threshold = max(total * min_pct, min_value)
            df = group_by_threshold(df, threshold, label)
        elif min_pct is not None:
            total = df["sankey_value"].sum()
            df = group_by_threshold(df, total * min_pct, label)
        elif min_value is not None:
            df = group_by_threshold(df, min_value, label)
        elif top_n is not None:
            df = group_by_top_n(df, top_n, label)

        self._validated_df = df
        return self

    def with_palette(
        self,
        palette: str | Path | dict[str, Any] | ColorPalette | None = None,
    ) -> "SankeyPipeline":
        """Set default palette for rendering."""
        self.default_palette = get_palette(palette)
        return self

    def render(
        self,
        title: str | None = None,
        renderer: str = "plotly",
        palette: str | Path | dict[str, Any] | ColorPalette | None = None,
        theme: str | None = None,
    ) -> Figure:
        """Render the Sankey graph."""
        if self._validated_df is None:
            self.validate()

        graph = self.template.build(self._validated_df, layout=self.layout)

        resolved_palette = self._resolve_palette(palette, theme)

        renderer_obj = self._get_renderer(renderer)
        return renderer_obj.render(graph, resolved_palette, title=title)

    def export_html(
        self,
        path: str | Path,
        title: str | None = None,
        renderer: str = "plotly",
        palette: str | Path | dict[str, Any] | ColorPalette | None = None,
        theme: str | None = None,
        **render_kwargs: Any,
    ) -> str:
        """Render and export the Sankey graph to HTML.

        Args:
            path: Output HTML file path.
            title: Chart title.
            renderer: Renderer name (default: "plotly").
            palette: Custom palette override.
            theme: Built-in theme name.
            **render_kwargs: Additional kwargs passed to render().

        Returns:
            The output file path as a string.
        """
        fig = self.render(
            title=title,
            renderer=renderer,
            palette=palette,
            theme=theme,
            **render_kwargs,
        )
        fig.write_html(str(path))
        return str(path)

    def _resolve_palette(
        self,
        palette: str | Path | dict[str, Any] | ColorPalette | None,
        theme: str | None,
    ) -> ColorPalette:
        """Resolve palette with priority: palette arg > theme > default_palette > built-in."""
        if palette is not None:
            pal = get_palette(palette, theme=theme)
            return pal

        if theme is not None:
            return get_palette(theme=theme)

        if self.default_palette is not None:
            return self.default_palette

        return get_palette()

    def _get_renderer(self, renderer: str) -> Renderer:
        if renderer == "plotly":
            return PlotlyRenderer()
        raise ValueError(f"Unknown renderer: {renderer}")

    def _prepare_df(self) -> pl.DataFrame:
        """Prepare data: schema validation, normalization, sign normalization, mapping."""
        schema = InputSchema(self._lf)
        lf = schema.validate().normalize()
        lf = self._sign_normalizer.normalize(lf)
        lf = self._unit_normalizer.normalize(lf)

        df = lf.collect()

        if self.period:
            df = df.with_columns(pl.lit(self.period).alias("period"))
        if self.currency:
            df = df.with_columns(pl.lit(self.currency).alias("currency"))
        if self._mapper is not None:
            df = self._mapper.apply(df)

        return df

    @property
    def graph(self) -> FinancialGraph:
        if self._graph is None:
            if self._validated_df is None:
                self.validate()
            self._graph = self.template.build(self._validated_df, layout=self.layout)
        return self._graph

validate(tolerance=0.01)

Validate input data.

Source code in finflow_sankey/core/pipeline.py
70
71
72
73
74
75
76
77
78
79
def validate(self, tolerance: float = 0.01) -> "SankeyPipeline":
    """Validate input data."""
    df = self._prepare_df()
    validator = FinancialValidator(self.template.statement_type)
    self._validated_df = validator.validate(
        df,
        required_roles=self.template.required_roles(),
        tolerance=tolerance,
    )
    return self

group_minor(min_pct=None, min_value=None, top_n=None, label='Other')

Group minor accounts into Other.

Parameters:

Name Type Description Default
min_pct float | None

Group accounts below this percentage of total sankey_value.

None
min_value float | None

Group accounts below this absolute sankey_value.

None
top_n int | None

Keep top_n accounts, group the rest.

None
label str

Label for the grouped accounts.

'Other'
Source code in finflow_sankey/core/pipeline.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def group_minor(
    self,
    min_pct: float | None = None,
    min_value: float | None = None,
    top_n: int | None = None,
    label: str = "Other",
) -> "SankeyPipeline":
    """Group minor accounts into Other.

    Args:
        min_pct: Group accounts below this percentage of total sankey_value.
        min_value: Group accounts below this absolute sankey_value.
        top_n: Keep top_n accounts, group the rest.
        label: Label for the grouped accounts.
    """
    if self._validated_df is None:
        raise RuntimeError("Must call validate() before group_minor().")

    df = self._validated_df

    if min_pct is not None and min_value is not None:
        total = df["sankey_value"].sum()
        threshold = max(total * min_pct, min_value)
        df = group_by_threshold(df, threshold, label)
    elif min_pct is not None:
        total = df["sankey_value"].sum()
        df = group_by_threshold(df, total * min_pct, label)
    elif min_value is not None:
        df = group_by_threshold(df, min_value, label)
    elif top_n is not None:
        df = group_by_top_n(df, top_n, label)

    self._validated_df = df
    return self

with_palette(palette=None)

Set default palette for rendering.

Source code in finflow_sankey/core/pipeline.py
120
121
122
123
124
125
126
def with_palette(
    self,
    palette: str | Path | dict[str, Any] | ColorPalette | None = None,
) -> "SankeyPipeline":
    """Set default palette for rendering."""
    self.default_palette = get_palette(palette)
    return self

render(title=None, renderer='plotly', palette=None, theme=None)

Render the Sankey graph.

Source code in finflow_sankey/core/pipeline.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def render(
    self,
    title: str | None = None,
    renderer: str = "plotly",
    palette: str | Path | dict[str, Any] | ColorPalette | None = None,
    theme: str | None = None,
) -> Figure:
    """Render the Sankey graph."""
    if self._validated_df is None:
        self.validate()

    graph = self.template.build(self._validated_df, layout=self.layout)

    resolved_palette = self._resolve_palette(palette, theme)

    renderer_obj = self._get_renderer(renderer)
    return renderer_obj.render(graph, resolved_palette, title=title)

export_html(path, title=None, renderer='plotly', palette=None, theme=None, **render_kwargs)

Render and export the Sankey graph to HTML.

Parameters:

Name Type Description Default
path str | Path

Output HTML file path.

required
title str | None

Chart title.

None
renderer str

Renderer name (default: "plotly").

'plotly'
palette str | Path | dict[str, Any] | ColorPalette | None

Custom palette override.

None
theme str | None

Built-in theme name.

None
**render_kwargs Any

Additional kwargs passed to render().

{}

Returns:

Type Description
str

The output file path as a string.

Source code in finflow_sankey/core/pipeline.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
def export_html(
    self,
    path: str | Path,
    title: str | None = None,
    renderer: str = "plotly",
    palette: str | Path | dict[str, Any] | ColorPalette | None = None,
    theme: str | None = None,
    **render_kwargs: Any,
) -> str:
    """Render and export the Sankey graph to HTML.

    Args:
        path: Output HTML file path.
        title: Chart title.
        renderer: Renderer name (default: "plotly").
        palette: Custom palette override.
        theme: Built-in theme name.
        **render_kwargs: Additional kwargs passed to render().

    Returns:
        The output file path as a string.
    """
    fig = self.render(
        title=title,
        renderer=renderer,
        palette=palette,
        theme=theme,
        **render_kwargs,
    )
    fig.write_html(str(path))
    return str(path)

Core Components

ColorPalette

finflow_sankey.core.palette.ColorPalette dataclass

Complete color palette for rendering.

Source code in finflow_sankey/core/palette.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
@dataclass
class ColorPalette:
    """Complete color palette for rendering."""

    name: str = "default"
    version: str = "1.0.0"
    description: str = ""
    roles: RolePalette = field(default_factory=RolePalette)
    semantic: SemanticStyle = field(default_factory=SemanticStyle)

    @classmethod
    def from_yaml(cls, path: str | Path) -> "ColorPalette":
        """Load palette from YAML file."""
        with open(path, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f)

        return cls._from_dict(data)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> "ColorPalette":
        """Load palette from dict."""
        return cls._from_dict(data)

    @classmethod
    def _from_dict(cls, data: dict[str, Any]) -> "ColorPalette":
        roles_data = data.get("roles", {})
        semantic_data = data.get("semantic", {})

        return cls(
            name=data.get("name", "custom"),
            version=data.get("version", "1.0.0"),
            description=data.get("description", ""),
            roles=RolePalette(**roles_data),
            semantic=SemanticStyle(**semantic_data),
        )

    def override(self, overrides: dict[str, Any]) -> "ColorPalette":
        """Create a new palette with partial overrides."""
        role_fields = set(RolePalette.__dataclass_fields__.keys())
        semantic_fields = set(SemanticStyle.__dataclass_fields__.keys())

        role_overrides = {k: v for k, v in overrides.items() if k in role_fields}
        semantic_overrides = {k: v for k, v in overrides.items() if k in semantic_fields}

        return ColorPalette(
            name=f"{self.name}_overridden",
            version=self.version,
            description=self.description,
            roles=RolePalette(**{**self.roles.__dict__, **role_overrides}),
            semantic=SemanticStyle(**{**self.semantic.__dict__, **semantic_overrides}),
        )

    def validate(self) -> None:
        """Validate palette."""
        for role, color in self.roles.__dict__.items():
            if not _is_valid_hex(color):
                raise InvalidColorError(f"Invalid hex color for role '{role}': {color}")

        for semantic_key in ["background", "plot_background", "text", "border"]:
            color = getattr(self.semantic, semantic_key)
            if not _is_valid_hex(color):
                raise InvalidColorError(f"Invalid hex color for semantic '{semantic_key}': {color}")

        if not 0.0 <= self.semantic.link_opacity <= 1.0:
            raise InvalidOpacityError("link_opacity must be between 0 and 1")
        if not 0.0 <= self.semantic.hover_opacity <= 1.0:
            raise InvalidOpacityError("hover_opacity must be between 0 and 1")

        missing = REQUIRED_ROLES - set(self.roles.__dict__.keys())
        if missing:
            raise MissingRoleColorError(f"Missing required role colors: {missing}")

    def get_role_color(self, role: str) -> str:
        """Get color for a role, falling back to 'other'."""
        return getattr(self.roles, role, self.roles.other)

from_yaml(path) classmethod

Load palette from YAML file.

Source code in finflow_sankey/core/palette.py
104
105
106
107
108
109
110
@classmethod
def from_yaml(cls, path: str | Path) -> "ColorPalette":
    """Load palette from YAML file."""
    with open(path, "r", encoding="utf-8") as f:
        data = yaml.safe_load(f)

    return cls._from_dict(data)

from_dict(data) classmethod

Load palette from dict.

Source code in finflow_sankey/core/palette.py
112
113
114
115
@classmethod
def from_dict(cls, data: dict[str, Any]) -> "ColorPalette":
    """Load palette from dict."""
    return cls._from_dict(data)

override(overrides)

Create a new palette with partial overrides.

Source code in finflow_sankey/core/palette.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def override(self, overrides: dict[str, Any]) -> "ColorPalette":
    """Create a new palette with partial overrides."""
    role_fields = set(RolePalette.__dataclass_fields__.keys())
    semantic_fields = set(SemanticStyle.__dataclass_fields__.keys())

    role_overrides = {k: v for k, v in overrides.items() if k in role_fields}
    semantic_overrides = {k: v for k, v in overrides.items() if k in semantic_fields}

    return ColorPalette(
        name=f"{self.name}_overridden",
        version=self.version,
        description=self.description,
        roles=RolePalette(**{**self.roles.__dict__, **role_overrides}),
        semantic=SemanticStyle(**{**self.semantic.__dict__, **semantic_overrides}),
    )

validate()

Validate palette.

Source code in finflow_sankey/core/palette.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def validate(self) -> None:
    """Validate palette."""
    for role, color in self.roles.__dict__.items():
        if not _is_valid_hex(color):
            raise InvalidColorError(f"Invalid hex color for role '{role}': {color}")

    for semantic_key in ["background", "plot_background", "text", "border"]:
        color = getattr(self.semantic, semantic_key)
        if not _is_valid_hex(color):
            raise InvalidColorError(f"Invalid hex color for semantic '{semantic_key}': {color}")

    if not 0.0 <= self.semantic.link_opacity <= 1.0:
        raise InvalidOpacityError("link_opacity must be between 0 and 1")
    if not 0.0 <= self.semantic.hover_opacity <= 1.0:
        raise InvalidOpacityError("hover_opacity must be between 0 and 1")

    missing = REQUIRED_ROLES - set(self.roles.__dict__.keys())
    if missing:
        raise MissingRoleColorError(f"Missing required role colors: {missing}")

get_role_color(role)

Get color for a role, falling back to 'other'.

Source code in finflow_sankey/core/palette.py
166
167
168
def get_role_color(self, role: str) -> str:
    """Get color for a role, falling back to 'other'."""
    return getattr(self.roles, role, self.roles.other)

AccountMapper

finflow_sankey.core.mapper.AccountMapper

Maps raw account names to standard financial statement sections.

Source code in finflow_sankey/core/mapper.py
12
13
14
15
16
17
18
19
20
21
22
23
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
class AccountMapper:
    """Maps raw account names to standard financial statement sections."""

    def __init__(self, mapping: dict[str, list[str]]):
        """
        Args:
            mapping: Dict mapping standard section/role to list of raw account names.
                Example: {"revenue": ["Net Sales", "Sales Revenue"], ...}
        """
        self.mapping = mapping
        self._account_to_section: dict[str, str] = {}
        for section, accounts in mapping.items():
            for account in accounts:
                self._account_to_section[account] = section

    @classmethod
    def from_yaml(cls, path: str | Path) -> "AccountMapper":
        """Load mapping from YAML file."""
        with open(path, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f)
        return cls(data)

    @classmethod
    def from_dict(cls, mapping: dict[str, Any]) -> "AccountMapper":
        """Load mapping from dict (values may be list or single string)."""
        normalized: dict[str, list[str]] = {}
        for section, accounts in mapping.items():
            if isinstance(accounts, str):
                normalized[section] = [accounts]
            else:
                normalized[section] = list(accounts)
        return cls(normalized)

    def map_account(self, account: str) -> str | None:
        """Return standard section for a raw account name, or None."""
        return self._account_to_section.get(account)

    def apply(self, df: pl.DataFrame, target_col: str = "section") -> pl.DataFrame:
        """Apply mapping to DataFrame.

        Only overwrites target_col when it is null, preserving explicit sections.
        """
        if not self._account_to_section:
            return df

        return df.with_columns(
            pl.when(pl.col(target_col).is_null())
            .then(
                pl.col("account").replace_strict(
                    self._account_to_section,
                    default=None,
                )
            )
            .otherwise(pl.col(target_col))
            .alias(target_col)
        )

    def list_unmapped(self, df: pl.DataFrame) -> list[str]:
        """Return account names that are not covered by the mapping."""
        return (
            df.filter(
                pl.col("section").is_null()
                & pl.col("account").is_not_null()
            )["account"]
            .unique()
            .to_list()
        )

from_dict(mapping) classmethod

Load mapping from dict (values may be list or single string).

Source code in finflow_sankey/core/mapper.py
34
35
36
37
38
39
40
41
42
43
@classmethod
def from_dict(cls, mapping: dict[str, Any]) -> "AccountMapper":
    """Load mapping from dict (values may be list or single string)."""
    normalized: dict[str, list[str]] = {}
    for section, accounts in mapping.items():
        if isinstance(accounts, str):
            normalized[section] = [accounts]
        else:
            normalized[section] = list(accounts)
    return cls(normalized)

from_yaml(path) classmethod

Load mapping from YAML file.

Source code in finflow_sankey/core/mapper.py
27
28
29
30
31
32
@classmethod
def from_yaml(cls, path: str | Path) -> "AccountMapper":
    """Load mapping from YAML file."""
    with open(path, "r", encoding="utf-8") as f:
        data = yaml.safe_load(f)
    return cls(data)

apply(df, target_col='section')

Apply mapping to DataFrame.

Only overwrites target_col when it is null, preserving explicit sections.

Source code in finflow_sankey/core/mapper.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def apply(self, df: pl.DataFrame, target_col: str = "section") -> pl.DataFrame:
    """Apply mapping to DataFrame.

    Only overwrites target_col when it is null, preserving explicit sections.
    """
    if not self._account_to_section:
        return df

    return df.with_columns(
        pl.when(pl.col(target_col).is_null())
        .then(
            pl.col("account").replace_strict(
                self._account_to_section,
                default=None,
            )
        )
        .otherwise(pl.col(target_col))
        .alias(target_col)
    )