"""
Excel report of an attribution run.
:func:`write_excel_report` writes an :class:`AttributionResult` to one workbook,
in the style of the KaxaNuk Backtest Engine's Excel report so that a backtest
and its attribution read alike, and laid out the way professional attribution
reports are (headline figures first, active risk next to active return, a row
per calendar year, a bridge from benchmark to portfolio, the methodology
disclosed):
- ``summary``: the headline figures (portfolio, benchmark and active return,
tracking error, information ratio, maximum drawdown), the window and the
methods; key findings in plain English, generated from the numbers; the
headline tables, including attribution by calendar year and the factors
grouped into style and industry; four native Excel charts (the bridge from
benchmark to portfolio return, the cumulative portfolio and benchmark return,
the cumulative effects over time, the contribution per factor); and a table
of contents.
- ``checks``: the run's parameters, how the numbers were computed and every
diagnostic it logged (``AttributionResult.diagnostics``).
- ``how_to_read``: what each effect and term means, and what each sheet holds.
- One data sheet per result table, as an Excel table with filters:
Brinson-Fachler ``per_period``, ``cumulative`` and ``by_year``; the factor
model's tables; the active factor model's and the ``implementation`` table
when present. Brinson-Fachler ``details`` are not written: dates x groups can
exceed Excel's 1,048,576 rows.
- ``chart_data`` (hidden): the values the bridge and the factor charts draw.
It reads the result only and recomputes no attribution number: the summary
shows values of the result tables (the last row of a cumulative table, a row of
a by-year table, a share of ``cumulative_shares``, a statistic). The report adds
only presentation sums, each labelled: the factor groups' subtotals, selection
plus interaction, the bridge's residual, and the implementation block (engine and
holdings returns compounded, costs summed). Nothing but the workbook is written:
the charts are native, not images. Every word comes from
:mod:`~kaxanuk.attribution_analysis.output_handlers.excel_report_text`.
"""
import dataclasses
import datetime
import importlib
import logging
import math
import os
import re
from collections.abc import Mapping, Sequence
from pathlib import Path
import openpyxl
import openpyxl.cell
import openpyxl.chart
import openpyxl.chart.axis
import openpyxl.chart.label
import openpyxl.chart.marker
import openpyxl.formatting.rule
import openpyxl.styles
import openpyxl.utils
import openpyxl.worksheet.hyperlink
import openpyxl.worksheet.table
import openpyxl.worksheet.worksheet
import pandas as pd
import pyarrow as pa
from kaxanuk.attribution_analysis.entities.attribution_options import (
AGGREGATE_FACTOR_COLUMNS,
COMPONENT_COLUMNS,
INDUSTRY_FACTORS,
STYLE_FACTORS,
LinkingMethod,
)
from kaxanuk.attribution_analysis.entities.attribution_result import (
AttributionResult,
Diagnostic,
DiagnosticCode,
DiagnosticLevel,
)
from kaxanuk.attribution_analysis.output_handlers import excel_report_text as text
logger = logging.getLogger(__name__)
FILE_NAME_SUFFIX = "attribution_results"
"""The workbook is ``{name}_{UTC %Y%m%d%H%M%S}_attribution_results.xlsx``."""
# Colours and fonts of the Backtest Engine's report.
BORDER_COLOR = "D3D3D3"
HEADER_FILL_COLOR = "e84328"
INFO_FILL_COLOR = "F2F2F2"
SHEET_TITLE_COLOR = "2E4B75"
SUBTITLE_COLOR = "4A4A4A"
TITLE_COLOR = "3266D0"
# Gains and losses in the Okabe-Ito palette, which reads with any colour vision; always next to a sign.
GAIN_COLOR = "0072B2"
LOSS_COLOR = "D55E00"
ACCENT_COLOR = "E69F00"
NEUTRAL_COLOR = "595959"
GAIN_FILL_COLOR = "DCEAF6"
LOSS_FILL_COLOR = "F9E0D0"
LINE_STYLES = ((GAIN_COLOR, "solid"), (LOSS_COLOR, "dash"), (ACCENT_COLOR, "sysDot"))
"""Colour and dash of the first, second and third line of a line chart: told apart without colour too."""
# Number formats, declared per value rather than guessed from a label.
CHART_PERCENT_FORMAT = "0.0%"
CHART_SIGNED_FORMAT = "+0.00%;-0.00%;0.00%"
DAILY_PERCENT_FORMAT = "0.000%"
DAILY_SIGNED_FORMAT = "+0.000%;-0.000%;0.000%"
DATE_FORMAT = "yyyy-mm-dd"
INTEGER_FORMAT = "0"
PERCENT_FORMAT = "0.00%"
RATIO_FORMAT = "0.0000"
SHORT_RATIO_FORMAT = "0.00"
SIGNED_PERCENT_FORMAT = "+0.00%;-0.00%;0.00%"
TIMESTAMP_FORMAT = "yyyy-mm-dd hh:mm:ss"
STATISTIC_FORMATS = {
"Total Return": PERCENT_FORMAT,
"Annualized Return": PERCENT_FORMAT,
"Annualized Vol": PERCENT_FORMAT,
"Sharpe Ratio": RATIO_FORMAT,
"Max Drawdown": PERCENT_FORMAT,
"Skewness": RATIO_FORMAT,
"Kurtosis": RATIO_FORMAT,
"Cornish-Fisher VaR (5%)": PERCENT_FORMAT,
"Historic CVaR (5%)": PERCENT_FORMAT,
}
"""Number format of each ``summary_stats`` key; a key not listed is written with ``RATIO_FORMAT``."""
RELATIVE_FORMATS = {
"Active Return": SIGNED_PERCENT_FORMAT,
"Annualized Active Return": SIGNED_PERCENT_FORMAT,
"Tracking Error": PERCENT_FORMAT,
"Information Ratio": RATIO_FORMAT,
"Beta": RATIO_FORMAT,
"Hit Rate": PERCENT_FORMAT,
}
"""Number format of each ``relative_stats`` key; a key not listed is written with ``RATIO_FORMAT``."""
UNSIGNED_COLUMNS = frozenset({"portfolio_returns", "benchmark_returns", "engine_returns", "holdings_returns"})
"""Data-sheet columns that are returns rather than effects, written without a forced sign."""
_SUMMARY_COLUMN_WIDTHS = (34, 14, 14, 14, 14, 14, 14, 3)
"""Widths of summary columns A to H: A holds labels, B to G values; the charts start at column I."""
_SUMMARY_LAST_COLUMN = 7
_CHART_COLUMN = 9
_CHART_HEIGHT_ROWS = 21
_DATA_SHEET_LAST_TITLE_COLUMN = 4
_IMPLEMENTATION_COSTS = ("commissions", "slippage", "financing", "execution")
_LISTED_NAMES = 10
"""Longest list of names written out in a parameter (segments, factor files); the rest are counted."""
_MAXIMUM_FILE_ATTEMPTS = 100
_MINIMUM_YEARS_FOR_EXTREMES = 2
"""A best and a worst year need two years."""
_SHARE_MAXIMUM = 2.0
"""Above this size (200%) a share is not meaningful."""
_SHARE_MINIMUM_RETURN = 0.01
"""Below this size of the cumulative return (1%) shares are not meaningful."""
_SHOWN_AS_ZERO = 5e-5
"""Below this size a value reads 0.00%: it is written as 0 in a sentence, and neither coloured nor drawn."""
_TABLE_GAP = 2
"""Blank rows between two blocks of a sheet."""
_INVALID_FILE_NAME_CHARACTERS = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
_BORDER_SIDE = openpyxl.styles.Side(border_style="thin", color=BORDER_COLOR)
_BORDER = openpyxl.styles.Border(left=_BORDER_SIDE, right=_BORDER_SIDE, top=_BORDER_SIDE, bottom=_BORDER_SIDE)
_BOLD_FONT = openpyxl.styles.Font(bold=True)
_CENTER = openpyxl.styles.Alignment(horizontal="center")
_DESCRIPTION_FONT = openpyxl.styles.Font(italic=True, color=SUBTITLE_COLOR)
_HEADER_FILL = openpyxl.styles.PatternFill(
start_color=HEADER_FILL_COLOR, end_color=HEADER_FILL_COLOR, fill_type="solid"
)
_HEADER_FONT = openpyxl.styles.Font(bold=True, color="FFFFFF")
_HYPOTHETICAL_FONT = openpyxl.styles.Font(bold=True, italic=True, color=LOSS_COLOR)
_INFO_FILL = openpyxl.styles.PatternFill(start_color=INFO_FILL_COLOR, end_color=INFO_FILL_COLOR, fill_type="solid")
_KPI_FONT = openpyxl.styles.Font(bold=True, size=14, color=SHEET_TITLE_COLOR)
_LEFT = openpyxl.styles.Alignment(horizontal="left")
_LINK_FONT = openpyxl.styles.Font(color=GAIN_COLOR, underline="single")
_RIGHT = openpyxl.styles.Alignment(horizontal="right")
_SHEET_TITLE_FONT = openpyxl.styles.Font(bold=True, size=14, color=SHEET_TITLE_COLOR)
_SUBTITLE_FONT = openpyxl.styles.Font(bold=True, size=11, color=SUBTITLE_COLOR)
_TITLE_FONT = openpyxl.styles.Font(bold=True, size=16, color=TITLE_COLOR)
_WRAP = openpyxl.styles.Alignment(horizontal="left", vertical="top", wrap_text=True)
_DATA_CELL_STYLES = {
DATE_FORMAT: ("date", _LEFT),
DAILY_PERCENT_FORMAT: ("daily_percent", _RIGHT),
DAILY_SIGNED_FORMAT: ("daily_signed", _RIGHT),
INTEGER_FORMAT: ("integer", _LEFT),
PERCENT_FORMAT: ("percent", _RIGHT),
SIGNED_PERCENT_FORMAT: ("signed_percent", _RIGHT),
None: ("text", _LEFT),
}
"""Data cells by number format (``None`` for text): the key of their named style's name, and their alignment.
A named style is set on a cell in one step: data sheets hold most of the report's cells, and setting
border, alignment and number format one by one would hash each of them for every cell."""
_SIGNED_FORMATS = frozenset({SIGNED_PERCENT_FORMAT, DAILY_SIGNED_FORMAT})
@dataclasses.dataclass(frozen=True, slots=True)
class _Row:
"""One row of a summary table: a label, its values and each value's number format (``None`` for text)."""
label: str
values: tuple[object, ...]
formats: tuple[str | None, ...]
bold: bool = False
@dataclasses.dataclass(frozen=True, slots=True)
class _FactorRow:
"""A factor's cumulative contribution (last row of ``cumulative_contributions``) and its share."""
factor: str
label: str
group: str
contribution: float
share: float | None
@dataclasses.dataclass(frozen=True, slots=True)
class _Headline:
"""The values the summary shows, read once so the tables, charts and sentences cite the same numbers."""
brinson_fachler: dict[str, float] | None
brinson_fachler_years: tuple[dict[str, float], ...]
factor_totals: dict[str, float] | None
factor_years: tuple[dict[str, float], ...]
factor_shares: dict[str, float]
shares_meaningful: bool
factors: tuple[_FactorRow, ...]
active_totals: dict[str, float] | None
implementation: dict[str, float] | None
@dataclasses.dataclass(frozen=True, slots=True)
class _DataSheet:
"""A data sheet: the text key of its name, title and description, its table, and whether its values are daily."""
key: str
table: pa.Table
daily: bool
@dataclasses.dataclass(frozen=True, slots=True)
class _BridgeStep:
"""A bar of the bridge chart: its label, its value, and whether it is a total, a gain or a loss."""
label: str
value: float
kind: str
@dataclasses.dataclass(frozen=True, slots=True)
class _ChartRanges:
"""Rows of the ``chart_data`` sheet the bridge and the factor charts read (``None`` when absent)."""
bridge: tuple[int, int] | None
factors: tuple[int, int] | None
[docs]
def write_excel_report(
result: AttributionResult,
output_directory: str | os.PathLike[str],
*,
name: str = "Portfolio",
benchmark_name: str | None = None,
) -> Path:
"""
Write the attribution result to an Excel workbook and return its path.
The workbook is ``{name}_{UTC %Y%m%d%H%M%S}_attribution_results.xlsx`` in
`output_directory`, which is created when missing. An existing file is
never overwritten: a second report in the same second gets ``_2`` before the
extension, and so on. Nothing else is written, and a workbook that fails
while being saved is removed.
Parameters
----------
result : AttributionResult
What :func:`~kaxanuk.attribution_analysis.run_attribution`, ``main`` or
:func:`~kaxanuk.attribution_analysis.run_attribution_from_backtest`
returned. It is only read.
output_directory : str or os.PathLike
Directory the workbook is written to.
name : str, default "Portfolio"
Report name: the summary's title and the start of the file name
(characters a file name cannot hold become ``_``).
benchmark_name : str or None, default None
Shown in the summary's info block when given.
Returns
-------
Path
The workbook written.
Raises
------
FileExistsError
If 100 report files of the same name and second already exist.
OSError
If the directory or the file cannot be written.
"""
generated_at = datetime.datetime.now(tz=datetime.UTC)
workbook = _build_workbook(result, name, benchmark_name, generated_at.replace(tzinfo=None, microsecond=0))
directory = Path(output_directory)
directory.mkdir(parents=True, exist_ok=True)
stem = f"{_file_name(name)}_{generated_at.strftime('%Y%m%d%H%M%S')}_{FILE_NAME_SUFFIX}"
path = _save_as_new_file(workbook, directory, stem)
logger.info("Excel report saved to: %s", path)
return path
def _build_workbook(
result: AttributionResult,
name: str,
benchmark_name: str | None,
generated_at: datetime.datetime,
) -> openpyxl.Workbook:
"""
The whole report as an in-memory workbook.
Parameters
----------
result : AttributionResult
The run to report.
name : str
Report name (summary title).
benchmark_name : str or None
Shown in the info block when given.
generated_at : datetime.datetime
Naive UTC time of the report.
Returns
-------
openpyxl.Workbook
``summary``, ``checks``, ``how_to_read``, the data sheets, then the
hidden ``chart_data``.
"""
workbook = openpyxl.Workbook()
for number_format, (key, alignment) in _DATA_CELL_STYLES.items():
style = openpyxl.styles.NamedStyle(name=text.STYLE_NAMES[key], border=_BORDER, alignment=alignment)
if number_format is not None:
style.number_format = number_format
workbook.add_named_style(style)
summary = workbook.active
summary.title = text.SHEET_NAMES["summary"]
checks = workbook.create_sheet(text.SHEET_NAMES["checks"])
how_to_read = workbook.create_sheet(text.SHEET_NAMES["how_to_read"])
data_sheets = _data_sheets(result)
data_worksheets = {}
for data_sheet in data_sheets:
worksheet = workbook.create_sheet(text.SHEET_NAMES[data_sheet.key])
_write_data_sheet(worksheet, data_sheet)
data_worksheets[data_sheet.key] = worksheet
headline = _headline(result)
bridge = _bridge_steps(headline.brinson_fachler)
chart_ranges = _ChartRanges(bridge=None, factors=None)
chart_data = None
if bridge or headline.factors:
chart_data = workbook.create_sheet(text.SHEET_NAMES["chart_data"])
chart_ranges = _write_chart_data(chart_data, bridge, headline.factors)
chart_data.sheet_state = "hidden"
sheet_keys = ["summary", "checks", "how_to_read", *(sheet.key for sheet in data_sheets)]
_write_summary(summary, result, headline, name, benchmark_name, generated_at, sheet_keys)
_add_summary_charts(summary, result, headline, data_worksheets, chart_data, chart_ranges)
_write_checks(checks, result, name)
_write_how_to_read(how_to_read, sheet_keys)
data_titles = {worksheet.title for worksheet in data_worksheets.values()}
for worksheet in workbook.worksheets:
if worksheet is not summary and worksheet is not chart_data:
_back_link(worksheet)
_print_setup(worksheet, name, data_sheet=worksheet.title in data_titles)
workbook.properties.title = text.DOCUMENT_TITLE.format(name=name)
workbook.properties.subject = text.DOCUMENT_SUBJECT
workbook.properties.creator = text.DOCUMENT_CREATOR.format(
version=importlib.import_module("kaxanuk.attribution_analysis").__version__
)
workbook.properties.created = generated_at
return workbook
# --- Reading the result ---------------------------------------------------------
def _last_row(table: pa.Table) -> dict[str, float] | None:
"""The last row of a cumulative table without its date (``None`` for an empty table)."""
if table.num_rows == 0:
return None
row = table.slice(table.num_rows - 1).to_pylist()[0]
return {key: value for key, value in row.items() if key != "date"}
def _factor_columns(table: pa.Table) -> list[str]:
"""The factor columns of a factor-model table: neither the date, a return component nor an aggregate file."""
return [
column for column in table.column_names
if column not in {"date", "year"} and column not in COMPONENT_COLUMNS and column not in AGGREGATE_FACTOR_COLUMNS
]
def _component_columns(table: pa.Table) -> list[str]:
"""The return-component columns (``f_carry``, ``f_dividends``) of a factor-model table, in that order."""
return [column for column in COMPONENT_COLUMNS if column in table.column_names]
def _factor_label(factor: str) -> str:
"""A factor's display name: ``FACTOR_LABELS``, else the file name without its ``f_`` prefix."""
if factor in text.FACTOR_LABELS:
return text.FACTOR_LABELS[factor]
if factor in text.COLUMN_LABELS:
return text.COLUMN_LABELS[factor]
bare = factor.removeprefix("f_")
return bare[:1].upper() + bare[1:]
def _factor_group(factor: str) -> str:
"""``style``, ``industry`` or ``other``, as the library's own factor charts group factors."""
if factor in STYLE_FACTORS:
return "style"
if factor in INDUSTRY_FACTORS:
return "industry"
return "other"
def _shares_meaningful(total: float | None, shares: Mapping[str, float]) -> bool:
"""Whether shares of `total` read sensibly: the total is at least 1% in size and no share exceeds 200%."""
if not shares or total is None or not math.isfinite(total) or abs(total) < _SHARE_MINIMUM_RETURN:
return False
return all(_is_finite(share) and abs(share) <= _SHARE_MAXIMUM for share in shares.values())
def _headline(result: AttributionResult) -> _Headline:
"""
The values the summary shows.
Parameters
----------
result : AttributionResult
The run to report.
Returns
-------
_Headline
Last rows of the cumulative tables, the rows of the by-year tables,
the factor shares and whether they are meaningful, the factors by
group and contribution (largest first), and the implementation block.
"""
bf = result.brinson_fachler
brinson_fachler = None if bf is None else _last_row(bf.cumulative)
brinson_fachler_years = () if bf is None or bf.by_year is None else tuple(bf.by_year.to_pylist())
factor_model = result.factor_model
factor_totals = None
factor_years: tuple[dict[str, float], ...] = ()
factor_shares: dict[str, float] = {}
factors: list[_FactorRow] = []
active_totals = None
shares_meaningful = False
if factor_model is not None:
factor_totals = _last_row(factor_model.cumulative_totals)
factor_years = () if factor_model.by_year is None else tuple(factor_model.by_year.to_pylist())
factor_shares = dict(factor_model.cumulative_shares)
shares_meaningful = _shares_meaningful(
None if factor_totals is None else factor_totals["portfolio_returns"], factor_shares
)
last_contributions = _last_row(factor_model.cumulative_contributions) or {}
group_order = list(text.FACTOR_GROUPS)
factors = sorted(
(
_FactorRow(
factor=factor,
label=_factor_label(factor),
group=_factor_group(factor),
contribution=float(last_contributions.get(factor) or 0.0),
share=factor_shares.get(factor),
)
for factor in _factor_columns(factor_model.cumulative_contributions)
),
key=lambda row: (group_order.index(row.group), -row.contribution),
)
if factor_model.active is not None:
active_totals = _last_row(factor_model.active.cumulative_totals)
return _Headline(
brinson_fachler=brinson_fachler,
brinson_fachler_years=brinson_fachler_years,
factor_totals=factor_totals,
factor_years=factor_years,
factor_shares=factor_shares,
shares_meaningful=shares_meaningful,
factors=tuple(factors),
active_totals=active_totals,
implementation=_implementation_totals(result.implementation),
)
def _implementation_totals(implementation: pa.Table | None) -> dict[str, float] | None:
"""
Engine and holdings returns compounded and each cost summed over the implementation table's dates.
Parameters
----------
implementation : pa.Table or None
``AttributionResult.implementation``.
Returns
-------
dict[str, float] or None
``engine_returns``, ``holdings_returns`` (compounded) and the four
cost columns (summed); ``None`` without an implementation table or rows.
"""
if implementation is None or implementation.num_rows == 0:
return None
def finite(column: str) -> list[float]:
"""The column's finite values."""
return [value for value in implementation.column(column).to_pylist() if _is_finite(value)]
totals = {
column: math.prod(1.0 + value for value in finite(column)) - 1.0
for column in ("engine_returns", "holdings_returns")
}
totals.update({column: math.fsum(finite(column)) for column in _IMPLEMENTATION_COSTS})
return totals
def _is_finite(value: object) -> bool:
"""Whether `value` is a finite number (not ``None``, NaN or infinite)."""
return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)
def _data_sheets(result: AttributionResult) -> list[_DataSheet]:
"""The data sheets of `result`, in workbook order."""
sheets = []
bf = result.brinson_fachler
if bf is not None:
sheets += [
_DataSheet("bf_per_period", bf.per_period, daily=True),
_DataSheet("bf_cumulative", bf.cumulative, daily=False),
]
if bf.by_year is not None:
sheets.append(_DataSheet("bf_by_year", bf.by_year, daily=False))
factor_model = result.factor_model
if factor_model is not None:
shares = factor_model.cumulative_shares
shares_table = pa.table({
"factor": pa.array([_factor_label(key) for key in shares], type=pa.string()),
"share": pa.array(list(shares.values()), type=pa.float64()),
})
sheets += [
_DataSheet("factor_contributions", factor_model.contributions, daily=True),
_DataSheet("factor_cumulative", factor_model.cumulative_contributions, daily=False),
_DataSheet("factor_totals", factor_model.cumulative_totals, daily=False),
]
if factor_model.by_year is not None:
sheets.append(_DataSheet("factor_by_year", factor_model.by_year, daily=False))
sheets += [
_DataSheet("factor_daily_shares", factor_model.daily_shares, daily=False),
_DataSheet("factor_shares", shares_table, daily=False),
]
if factor_model.active is not None:
sheets += [
_DataSheet("active_returns", factor_model.active.returns, daily=True),
_DataSheet("active_contributions", factor_model.active.contributions, daily=True),
_DataSheet("active_cumulative", factor_model.active.cumulative_contributions, daily=False),
_DataSheet("active_totals", factor_model.active.cumulative_totals, daily=False),
]
if result.implementation is not None:
sheets.append(_DataSheet("implementation", result.implementation, daily=True))
return sheets
def _is_expected(diagnostic: Diagnostic, result: AttributionResult) -> bool:
"""Whether every run of this kind logs `diagnostic`: the factor model leaving out the window's first date."""
return (
diagnostic.code is DiagnosticCode.FACTOR_DATES_WITHOUT_PORTFOLIO_RETURN
and diagnostic.count == 1
and diagnostic.first_date == result.start_date
)
def _segments(result: AttributionResult) -> list[str]:
"""The Brinson-Fachler segments of the run, from its per-date details (sorted)."""
if result.brinson_fachler is None:
return []
names: set[str] = set()
for detail in result.brinson_fachler.details.values():
if "asset" in detail.column_names:
names.update(str(name) for name in detail.column("asset").to_pylist())
return sorted(names)
# --- Key findings ---------------------------------------------------------------
def _key_findings(result: AttributionResult, headline: _Headline) -> list[str]:
"""
Plain-English sentences on the numbers the summary shows, in a fixed order.
Each sentence is written only when the numbers it cites are in the result,
and cites them as the summary's figures and tables show them. The first is
the bottom line.
Parameters
----------
result : AttributionResult
The run to report.
headline : _Headline
The values of the summary's tables.
Returns
-------
list[str]
The bottom line; the window; the active risk; the Brinson-Fachler
split, its largest effect and selection with interaction; the best and
worst year; the factor split, components and the best and worst
factors; the active factor split; the implementation costs; the
diagnostics.
"""
findings = [_bottom_line(result)]
if result.portfolio_returns.num_rows:
findings.append(_sentence(
"window", start=result.start_date, end=result.end_date, dates=result.portfolio_returns.num_rows
))
findings += _risk_findings(result)
findings += _effect_findings(result, headline)
findings += _year_findings(headline)
findings += _factor_findings(headline)
findings += _active_findings(headline)
if headline.implementation is not None:
findings.append(_sentence(
"implementation",
engine=headline.implementation["engine_returns"],
holdings=headline.implementation["holdings_returns"],
**{cost: headline.implementation[cost] for cost in _IMPLEMENTATION_COSTS},
))
findings.append(_diagnostics_finding(result))
return findings
def _sentence(key: str, **values: object) -> str:
"""
The finding `key` filled with `values`.
A number that its format would show as zero is passed as 0.0, so a
sentence never reads "-0.00%".
Parameters
----------
key : str
Key of the template in ``FINDINGS`` of the text module.
**values : object
The template's fields.
Returns
-------
str
The sentence.
"""
tidy = {
name: 0.0 if isinstance(value, float) and abs(value) < _SHOWN_AS_ZERO else value
for name, value in values.items()
}
return text.FINDINGS[key].format(**tidy)
def _bottom_line(result: AttributionResult) -> str:
"""The portfolio against its benchmark (or alone), total and annualized."""
total = result.summary_stats.get("Total Return")
annualized = result.summary_stats.get("Annualized Return")
if not (_is_finite(total) and _is_finite(annualized)):
return text.FINDINGS["no_statistics"]
benchmark = result.benchmark_stats.get("Total Return")
active = result.relative_stats.get("Active Return")
annualized_active = result.relative_stats.get("Annualized Active Return")
if _is_finite(benchmark) and _is_finite(active) and _is_finite(annualized_active):
return _sentence(
"headline", portfolio=total, benchmark=benchmark, active=active, annualized=annualized_active
)
return _sentence("headline_without_benchmark", portfolio=total, annualized=annualized)
def _risk_findings(result: AttributionResult) -> list[str]:
"""Tracking error, information ratio and hit rate, when all are defined."""
statistics = {key: result.relative_stats.get(key) for key in ("Tracking Error", "Information Ratio", "Hit Rate")}
if not all(_is_finite(value) for value in statistics.values()):
return []
return [_sentence(
"risk",
tracking_error=statistics["Tracking Error"],
information_ratio=statistics["Information Ratio"],
hit_rate=statistics["Hit Rate"],
)]
def _effect_findings(result: AttributionResult, headline: _Headline) -> list[str]:
"""The Brinson-Fachler split, its largest effect and selection counted with interaction."""
bf = headline.brinson_fachler
if result.brinson_fachler is None or bf is None:
return []
effects = {effect: bf[effect] for effect in text.EFFECT_NAMES}
linked = result.brinson_fachler.linking is not LinkingMethod.NONE
findings = [_sentence("effects_linked" if linked else "effects_summed", active=bf["alpha"], **effects)]
largest = max(effects, key=lambda effect: abs(effects[effect]))
if abs(effects[largest]) >= _SHOWN_AS_ZERO:
findings.append(_sentence("largest_effect", effect=text.EFFECT_NAMES[largest]))
if abs(effects["interaction"]) >= _SHOWN_AS_ZERO:
findings.append(_sentence("selection_with_interaction", value=effects["selection"] + effects["interaction"]))
return findings
def _year_findings(headline: _Headline) -> list[str]:
"""The best and worst calendar year by Brinson-Fachler active return, when there are two years or more."""
years = headline.brinson_fachler_years
if len(years) < _MINIMUM_YEARS_FOR_EXTREMES:
return []
best = max(years, key=lambda row: row["alpha"])
worst = min(years, key=lambda row: row["alpha"])
return [_sentence(
"best_and_worst_year",
best=best["year"],
best_value=best["alpha"],
worst=worst["year"],
worst_value=worst["alpha"],
)]
def _factor_findings(headline: _Headline) -> list[str]:
"""Factors against the idiosyncratic residual, each return component, and the best and worst factors."""
totals = headline.factor_totals
if totals is None:
return []
shares = headline.factor_shares
if headline.shares_meaningful:
findings = [_sentence(
"factor_split",
portfolio=totals["portfolio_returns"],
factors=totals["factor_returns"],
factor_share=_factor_share(shares),
idiosyncratic=totals["idiosyncratic_returns"],
idiosyncratic_share=shares.get("idio_returns", 0.0),
)]
else:
findings = [_sentence(
"factor_split_without_shares",
portfolio=totals["portfolio_returns"],
factors=totals["factor_returns"],
idiosyncratic=totals["idiosyncratic_returns"],
)]
for component, total_column in COMPONENT_COLUMNS.items():
if total_column not in totals:
continue
if headline.shares_meaningful:
findings.append(_sentence(
"component",
component=text.COLUMN_LABELS[component],
value=totals[total_column],
share=shares.get(component, 0.0),
))
else:
findings.append(_sentence(
"component_without_share", component=text.COLUMN_LABELS[component], value=totals[total_column]
))
if abs(totals["factor_returns"]) >= abs(totals["idiosyncratic_returns"]):
findings.append(text.FINDINGS["larger_part_factors"])
else:
findings.append(text.FINDINGS["larger_part_idiosyncratic"])
ranked = sorted(headline.factors, key=lambda row: row.contribution, reverse=True)
best = ranked[0] if ranked and ranked[0].contribution >= _SHOWN_AS_ZERO else None
worst = ranked[-1] if ranked and ranked[-1].contribution <= -_SHOWN_AS_ZERO else None
if best is not None and worst is not None:
findings.append(_sentence(
"best_and_worst_factor",
best=best.label,
best_value=best.contribution,
worst=worst.label,
worst_value=worst.contribution,
))
elif best is not None:
findings.append(_sentence("best_factor_only", best=best.label, best_value=best.contribution))
elif worst is not None:
findings.append(_sentence("worst_factor_only", worst=worst.label, worst_value=worst.contribution))
return findings
def _factor_share(shares: Mapping[str, float]) -> float:
"""The factors' share of the cumulative portfolio return: every share but the components' and the residual's."""
return math.fsum(
share for key, share in shares.items() if key not in COMPONENT_COLUMNS and key != "idio_returns"
)
def _active_findings(headline: _Headline) -> list[str]:
"""The active return split into factors, components and the residual."""
active = headline.active_totals
if active is None:
return []
findings = [_sentence(
"active_factor_split",
factors=active["factor_returns"],
active=active["active_returns"],
idiosyncratic=active["idiosyncratic_returns"],
)]
findings += [
_sentence("active_component", component=text.COLUMN_LABELS[component], value=active[total_column])
for component, total_column in COMPONENT_COLUMNS.items()
if total_column in active
]
return findings
def _diagnostics_finding(result: AttributionResult) -> str:
"""How many warnings, expected warnings and notes the run logged."""
diagnostics = result.diagnostics
if not diagnostics:
return text.FINDINGS["no_diagnostics"]
expected = sum(_is_expected(diagnostic, result) for diagnostic in diagnostics)
warnings = sum(
diagnostic.level is DiagnosticLevel.WARNING and not _is_expected(diagnostic, result)
for diagnostic in diagnostics
)
return _sentence(
"diagnostics", warnings=warnings, expected=expected, notes=len(diagnostics) - warnings - expected
)
# --- Summary sheet --------------------------------------------------------------
def _write_summary(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
result: AttributionResult,
headline: _Headline,
name: str,
benchmark_name: str | None,
generated_at: datetime.datetime,
sheet_keys: Sequence[str],
) -> None:
"""
Title, headline figures, info block, key findings, tables and contents.
Parameters
----------
worksheet : Worksheet
The ``summary`` sheet.
result : AttributionResult
The run to report.
headline : _Headline
The values the tables and the findings show.
name : str
Report name, the title.
benchmark_name : str or None
Shown in the info block when given.
generated_at : datetime.datetime
Naive UTC time of the report.
sheet_keys : Sequence[str]
Keys of the workbook's visible sheets, in order, for the contents.
"""
worksheet.sheet_view.showGridLines = False
for index, width in enumerate(_SUMMARY_COLUMN_WIDTHS, start=1):
worksheet.column_dimensions[openpyxl.utils.get_column_letter(index)].width = width
worksheet.merge_cells(start_row=1, start_column=1, end_row=1, end_column=_SUMMARY_LAST_COLUMN)
worksheet["A1"] = name
worksheet["A1"].font = _TITLE_FONT
worksheet["A1"].alignment = _CENTER
if result.implementation is not None:
worksheet["A2"] = text.SUMMARY["hypothetical"]
worksheet["A2"].font = _HYPOTHETICAL_FONT
else:
worksheet["A2"] = text.SUMMARY["subtitle"]
worksheet["A2"].font = _DESCRIPTION_FONT
signed_cells: list[str] = []
_write_kpis(worksheet, 3, result, signed_cells)
info = [
(text.INFO_LABELS["start_date"], result.start_date, DATE_FORMAT),
(text.INFO_LABELS["end_date"], result.end_date, DATE_FORMAT),
(text.INFO_LABELS["return_dates"], result.portfolio_returns.num_rows, INTEGER_FORMAT),
(text.INFO_LABELS["methods"], text.LIST_SEPARATOR.join(_methods(result)), None),
]
if benchmark_name is not None:
info.append((text.INFO_LABELS["benchmark"], benchmark_name, None))
info.append((text.INFO_LABELS["generated"], generated_at, TIMESTAMP_FORMAT))
row = 6
for label, value, number_format in info:
label_cell = worksheet.cell(row=row, column=1, value=label)
label_cell.font = _SUBTITLE_FONT
label_cell.fill = _INFO_FILL
label_cell.border = _BORDER
worksheet.merge_cells(start_row=row, start_column=2, end_row=row, end_column=_SUMMARY_LAST_COLUMN)
value_cell = worksheet.cell(row=row, column=2, value=value)
value_cell.border = _BORDER
value_cell.alignment = _LEFT
if number_format is not None:
value_cell.number_format = number_format
row += 1
row += 1
_header_row(worksheet, row, [text.SUMMARY["key_findings"]], merge_to=_SUMMARY_LAST_COLUMN)
findings_width = sum(_SUMMARY_COLUMN_WIDTHS[:_SUMMARY_LAST_COLUMN])
for index, finding in enumerate(_key_findings(result, headline)):
row += 1
worksheet.merge_cells(start_row=row, start_column=1, end_row=row, end_column=_SUMMARY_LAST_COLUMN)
cell = worksheet.cell(row=row, column=1, value=finding)
cell.alignment = _WRAP
if index == 0:
cell.font = _BOLD_FONT
worksheet.row_dimensions[row].height = _wrapped_height(finding, findings_width)
row = _write_performance(worksheet, row + _TABLE_GAP, result, signed_cells)
if headline.brinson_fachler is not None and result.brinson_fachler is not None:
row = _write_brinson_fachler(
worksheet, row + _TABLE_GAP, headline.brinson_fachler, result.brinson_fachler.linking, signed_cells
)
if headline.brinson_fachler_years:
row = _write_brinson_fachler_years(worksheet, row + _TABLE_GAP, headline, signed_cells)
if headline.factor_totals is not None:
row = _write_factor_totals(worksheet, row + _TABLE_GAP, headline, signed_cells)
if headline.factor_years:
row = _write_factor_years(worksheet, row + _TABLE_GAP, headline, signed_cells)
row = _write_factor_contributions(worksheet, row + _TABLE_GAP, headline, result, signed_cells)
if headline.active_totals is not None:
row = _write_active_totals(worksheet, row + _TABLE_GAP, headline.active_totals, signed_cells)
if headline.implementation is not None:
row = _write_implementation(worksheet, row + _TABLE_GAP, headline.implementation, signed_cells)
_write_contents(worksheet, row + _TABLE_GAP, sheet_keys)
_colour_by_sign(worksheet, signed_cells)
def _write_kpis(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
result: AttributionResult,
signed_cells: list[str],
) -> None:
"""The headline figures across the top: a label row and a value row (``n/a`` without a benchmark)."""
figures = (
("portfolio_return", result.summary_stats.get("Total Return"), PERCENT_FORMAT),
("benchmark_return", result.benchmark_stats.get("Total Return"), PERCENT_FORMAT),
("active_return", result.relative_stats.get("Active Return"), SIGNED_PERCENT_FORMAT),
("tracking_error", result.relative_stats.get("Tracking Error"), PERCENT_FORMAT),
("information_ratio", result.relative_stats.get("Information Ratio"), SHORT_RATIO_FORMAT),
("max_drawdown", result.summary_stats.get("Max Drawdown"), PERCENT_FORMAT),
)
for column, (key, value, number_format) in enumerate(figures, start=1):
label = worksheet.cell(row=row, column=column, value=text.KPI_LABELS[key])
label.font = _SUBTITLE_FONT
label.fill = _INFO_FILL
label.alignment = _CENTER
label.border = _BORDER
cell = worksheet.cell(row=row + 1, column=column)
cell.font = _KPI_FONT
cell.alignment = _CENTER
cell.border = _BORDER
if _is_finite(value):
cell.value = value
cell.number_format = number_format
if number_format in _SIGNED_FORMATS:
signed_cells.append(cell.coordinate)
else:
cell.value = text.NOT_AVAILABLE
worksheet.row_dimensions[row + 1].height = 22
def _methods(result: AttributionResult) -> list[str]:
"""Names of the methods that ran, plus the implementation table when present."""
methods = []
if result.brinson_fachler is not None:
methods.append(text.METHOD_NAMES["brinson_fachler"])
if result.factor_model is not None:
methods.append(text.METHOD_NAMES["factor_model"])
if result.factor_model.active is not None:
methods.append(text.METHOD_NAMES["active_factor_model"])
if result.implementation is not None:
methods.append(text.METHOD_NAMES["implementation"])
return methods
def _write_performance(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
result: AttributionResult,
signed_cells: list[str],
) -> int:
"""
The portfolio's and the benchmark's statistics side by side, then the relative ones.
The relative statistics describe the portfolio against the benchmark, so
their benchmark cell stays empty, as in the Backtest Engine's report.
Returns
-------
int
The last row written.
"""
rows = [
_Row(
text.STATISTIC_LABELS.get(key, key),
(value, result.benchmark_stats.get(key)),
(STATISTIC_FORMATS.get(key, RATIO_FORMAT),) * 2,
)
for key, value in result.summary_stats.items()
]
rows += [
_Row(
text.RELATIVE_LABELS.get(key, key),
(value, None),
(RELATIVE_FORMATS.get(key, RATIO_FORMAT), None),
)
for key, value in result.relative_stats.items()
]
headers = [text.SUMMARY["metric"], text.SUMMARY["portfolio"]]
if result.benchmark_stats:
headers.append(text.SUMMARY["benchmark"])
else:
rows = [
dataclasses.replace(table_row, values=table_row.values[:1], formats=table_row.formats[:1])
for table_row in rows
]
return _write_table(worksheet, row, text.SUMMARY["performance"], headers, rows, signed_cells)
def _write_brinson_fachler(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
values: Mapping[str, float],
linking: LinkingMethod,
signed_cells: list[str],
) -> int:
"""The last row of the cumulative Brinson-Fachler table, with selection plus interaction; returns its last row."""
rows = [
_Row(text.COLUMN_LABELS["portfolio_returns"], (values["portfolio_returns"],), (PERCENT_FORMAT,)),
_Row(text.COLUMN_LABELS["benchmark_returns"], (values["benchmark_returns"],), (PERCENT_FORMAT,)),
_Row(text.COLUMN_LABELS["alpha"], (values["alpha"],), (SIGNED_PERCENT_FORMAT,), bold=True),
]
rows += [
_Row(text.COLUMN_LABELS[effect], (values[effect],), (SIGNED_PERCENT_FORMAT,)) for effect in text.EFFECT_NAMES
]
rows.append(_Row(
text.SUMMARY["selection_with_interaction"],
(values["selection"] + values["interaction"],),
(SIGNED_PERCENT_FORMAT,),
))
notes = [text.SUMMARY["interaction_note"]]
if linking is LinkingMethod.NONE:
notes.append(text.SUMMARY["not_linked_note"])
return _write_table(
worksheet,
row,
text.SUMMARY["brinson_fachler"],
[text.SUMMARY["effect"], text.SUMMARY["value"]],
rows,
signed_cells,
notes=notes,
)
def _write_brinson_fachler_years(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
headline: _Headline,
signed_cells: list[str],
) -> int:
"""One row per calendar year, then the whole window; returns the table's last row."""
columns = ("portfolio_returns", "benchmark_returns", "alpha", *text.EFFECT_NAMES)
formats = (PERCENT_FORMAT, PERCENT_FORMAT, *(SIGNED_PERCENT_FORMAT,) * 4)
rows = [
_Row(str(year_row["year"]), tuple(year_row[column] for column in columns), formats)
for year_row in headline.brinson_fachler_years
]
whole = headline.brinson_fachler or {}
rows.append(_Row(text.SUMMARY["whole_window"], tuple(whole[column] for column in columns), formats, bold=True))
return _write_table(
worksheet,
row,
text.SUMMARY["by_year_brinson_fachler"],
[text.SUMMARY["year"], *(text.COLUMN_LABELS[column] for column in columns)],
rows,
signed_cells,
notes=[text.SUMMARY["years_note"]],
)
def _write_factor_totals(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
headline: _Headline,
signed_cells: list[str],
) -> int:
"""Portfolio return, all factors, components and the residual, with their shares; returns its last row."""
totals = headline.factor_totals or {}
shares = headline.factor_shares
def share(value: float | None) -> object:
"""The share, or ``n/m`` when shares are not meaningful."""
return value if headline.shares_meaningful else text.NOT_MEANINGFUL
rows = [
_Row(text.COLUMN_LABELS["portfolio_returns"], (totals["portfolio_returns"], None), (PERCENT_FORMAT, None)),
_Row(
text.COLUMN_LABELS["factor_returns"],
(totals["factor_returns"], share(_factor_share(shares))),
(SIGNED_PERCENT_FORMAT, PERCENT_FORMAT),
bold=True,
),
]
rows += [
_Row(
text.COLUMN_LABELS[component],
(totals[total_column], share(shares.get(component))),
(SIGNED_PERCENT_FORMAT, PERCENT_FORMAT),
)
for component, total_column in COMPONENT_COLUMNS.items()
if total_column in totals
]
rows.append(_Row(
text.COLUMN_LABELS["idiosyncratic_returns"],
(totals["idiosyncratic_returns"], share(shares.get("idio_returns"))),
(SIGNED_PERCENT_FORMAT, PERCENT_FORMAT),
))
notes = [] if headline.shares_meaningful else [text.SUMMARY["shares_not_meaningful_note"]]
return _write_table(
worksheet,
row,
text.SUMMARY["factor_model"],
[text.SUMMARY["component"], text.SUMMARY["value"], text.SUMMARY["share"]],
rows,
signed_cells,
notes=notes,
)
def _write_factor_years(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
headline: _Headline,
signed_cells: list[str],
) -> int:
"""The factor model per calendar year, then the whole window; returns the table's last row."""
totals = headline.factor_totals or {}
columns = [
"portfolio_returns",
"factor_returns",
*(total for total in COMPONENT_COLUMNS.values() if total in totals),
"idiosyncratic_returns",
]
formats = (PERCENT_FORMAT, *(SIGNED_PERCENT_FORMAT,) * (len(columns) - 1))
rows = [
_Row(str(year_row["year"]), tuple(year_row.get(column) for column in columns), formats)
for year_row in headline.factor_years
]
rows.append(_Row(text.SUMMARY["whole_window"], tuple(totals[column] for column in columns), formats, bold=True))
return _write_table(
worksheet,
row,
text.SUMMARY["by_year_factor_model"],
[text.SUMMARY["year"], *(text.COLUMN_LABELS[column] for column in columns)],
rows,
signed_cells,
notes=[text.SUMMARY["years_note"]],
)
def _write_factor_contributions(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
headline: _Headline,
result: AttributionResult,
signed_cells: list[str],
) -> int:
"""
The cumulative contribution and share of each factor, by group (style, industry, other), largest first.
Each group opens with its subtotal (the sum of its factors' contributions
and shares).
Returns
-------
int
The table's last row.
"""
rows = []
for group, group_label in text.FACTOR_GROUPS.items():
members = [factor for factor in headline.factors if factor.group == group]
if not members:
continue
subtotal_share = math.fsum(member.share or 0.0 for member in members)
rows.append(_Row(
group_label,
(
math.fsum(member.contribution for member in members),
subtotal_share if headline.shares_meaningful else text.NOT_MEANINGFUL,
),
(SIGNED_PERCENT_FORMAT, PERCENT_FORMAT),
bold=True,
))
rows += [
_Row(
f" {member.label}",
(
member.contribution,
member.share if headline.shares_meaningful and member.share is not None else text.NOT_MEANINGFUL,
),
(SIGNED_PERCENT_FORMAT, PERCENT_FORMAT),
)
for member in members
]
notes = []
if not headline.shares_meaningful:
notes.append(text.SUMMARY["shares_not_meaningful_note"])
if result.factor_model is not None and result.factor_model.linking is LinkingMethod.NONE:
notes.append(text.SUMMARY["unlinked_contributions_note"])
return _write_table(
worksheet,
row,
text.SUMMARY["contributions"],
[text.SUMMARY["factor"], text.SUMMARY["contribution"], text.SUMMARY["share"]],
rows,
signed_cells,
notes=notes,
)
def _write_active_totals(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
totals: Mapping[str, float],
signed_cells: list[str],
) -> int:
"""The last row of the active factor model's cumulative totals; returns its last row."""
columns = [
"portfolio_returns",
"benchmark_returns",
"active_returns",
"factor_returns",
*(total for total in COMPONENT_COLUMNS.values() if total in totals),
"idiosyncratic_returns",
]
rows = [
_Row(
text.COLUMN_LABELS[column],
(totals[column],),
(PERCENT_FORMAT if column in UNSIGNED_COLUMNS else SIGNED_PERCENT_FORMAT,),
bold=column == "active_returns",
)
for column in columns
]
return _write_table(
worksheet,
row,
text.SUMMARY["active_factor_model"],
[text.SUMMARY["component"], text.SUMMARY["value"]],
rows,
signed_cells,
)
def _write_implementation(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
totals: Mapping[str, float],
signed_cells: list[str],
) -> int:
"""Engine and holdings returns compounded and the costs summed; returns the table's last row."""
rows = [
_Row(text.SUMMARY["engine_compounded"], (totals["engine_returns"],), (PERCENT_FORMAT,)),
_Row(text.SUMMARY["holdings_compounded"], (totals["holdings_returns"],), (PERCENT_FORMAT,)),
]
rows += [
_Row(text.SUMMARY["cost_sum"].format(cost=text.COLUMN_LABELS[cost]), (totals[cost],), (SIGNED_PERCENT_FORMAT,))
for cost in _IMPLEMENTATION_COSTS
]
return _write_table(
worksheet,
row,
text.SUMMARY["implementation"],
[text.SUMMARY["metric"], text.SUMMARY["value"]],
rows,
signed_cells,
)
def _write_contents(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
sheet_keys: Sequence[str],
) -> None:
"""A linked list of the workbook's sheets (but the summary) with what each holds."""
worksheet.cell(row=row, column=1, value=text.SUMMARY["contents"]).font = _SUBTITLE_FONT
_header_row(worksheet, row + 1, [text.SUMMARY["sheet"], text.SUMMARY["holds"]], merge_to=_SUMMARY_LAST_COLUMN)
current = row + 1
for key in sheet_keys:
if key == "summary":
continue
current += 1
_link_cell(worksheet.cell(row=current, column=1), text.SHEET_NAMES[key])
worksheet.merge_cells(start_row=current, start_column=2, end_row=current, end_column=_SUMMARY_LAST_COLUMN)
description = worksheet.cell(row=current, column=2, value=text.SHEET_DESCRIPTIONS[key])
description.border = _BORDER
description.alignment = _WRAP
worksheet.row_dimensions[current].height = _wrapped_height(
text.SHEET_DESCRIPTIONS[key], sum(_SUMMARY_COLUMN_WIDTHS[1:_SUMMARY_LAST_COLUMN])
)
def _write_table(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
title: str,
headers: Sequence[str],
rows: Sequence[_Row],
signed_cells: list[str],
*,
notes: Sequence[str] = (),
) -> int:
"""
A titled table: the title, a header row, one row per `rows`, then the notes.
Cells with a signed format are added to `signed_cells`, to be coloured by sign.
Returns
-------
int
The last row written.
"""
worksheet.cell(row=row, column=1, value=title).font = _SUBTITLE_FONT
_header_row(worksheet, row + 1, headers)
current = row + 1
for table_row in rows:
current += 1
label = worksheet.cell(row=current, column=1, value=table_row.label)
label.border = _BORDER
label.alignment = _LEFT
if table_row.bold:
label.font = _BOLD_FONT
for offset, (value, number_format) in enumerate(zip(table_row.values, table_row.formats, strict=True), start=2):
cell = worksheet.cell(row=current, column=offset, value=_excel_value(value))
cell.border = _BORDER
cell.alignment = _RIGHT
if table_row.bold:
cell.font = _BOLD_FONT
if number_format is not None and _is_finite(cell.value):
cell.number_format = number_format
if number_format in _SIGNED_FORMATS:
signed_cells.append(cell.coordinate)
for note in notes:
current += 1
note_cell = worksheet.cell(row=current, column=1, value=note)
note_cell.font = _DESCRIPTION_FONT
return current
def _colour_by_sign(worksheet: openpyxl.worksheet.worksheet.Worksheet, cells: Sequence[str]) -> None:
"""Fill gains blue and losses vermilion (both light) on `cells`; values that read 0.00% stay unfilled."""
if not cells:
return
ranges = " ".join(cells)
worksheet.conditional_formatting.add(ranges, openpyxl.formatting.rule.CellIsRule(
operator="greaterThanOrEqual",
formula=[f"{_SHOWN_AS_ZERO:.5f}"],
fill=openpyxl.styles.PatternFill(start_color=GAIN_FILL_COLOR, end_color=GAIN_FILL_COLOR, fill_type="solid"),
))
worksheet.conditional_formatting.add(ranges, openpyxl.formatting.rule.CellIsRule(
operator="lessThanOrEqual",
formula=[f"{-_SHOWN_AS_ZERO:.5f}"],
fill=openpyxl.styles.PatternFill(start_color=LOSS_FILL_COLOR, end_color=LOSS_FILL_COLOR, fill_type="solid"),
))
# --- Charts ---------------------------------------------------------------------------
def _bridge_steps(values: Mapping[str, float] | None) -> list[_BridgeStep]:
"""
The bars of the bridge from the benchmark's cumulative return to the portfolio's.
The residual bar (what allocation, selection and interaction leave of the
return difference) is drawn only when it would not read 0.00%.
Parameters
----------
values : Mapping[str, float] or None
The last row of the cumulative Brinson-Fachler table.
Returns
-------
list[_BridgeStep]
Benchmark, the effects, the residual when visible, portfolio; empty
without Brinson-Fachler.
"""
if values is None:
return []
effects = [(text.EFFECT_NAMES[effect], values[effect]) for effect in text.EFFECT_NAMES]
residual = values["portfolio_returns"] - values["benchmark_returns"] - math.fsum(value for _, value in effects)
if abs(residual) >= _SHOWN_AS_ZERO:
effects.append((text.CHARTS["bridge_residual"], residual))
steps = [_BridgeStep(text.CHARTS["bridge_benchmark"], values["benchmark_returns"], "total")]
steps += [_BridgeStep(label, value, "gain" if value >= 0.0 else "loss") for label, value in effects]
steps.append(_BridgeStep(text.CHARTS["bridge_portfolio"], values["portfolio_returns"], "total"))
return steps
def _write_chart_data(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
bridge: Sequence[_BridgeStep],
factors: Sequence[_FactorRow],
) -> _ChartRanges:
"""
The values the bridge and the factor charts draw, on the hidden ``chart_data`` sheet.
A bridge bar spans from the running total before it to the one after it
(from 0 for a total). Excel stacks positive and negative values apart, so
each bar is split at zero into an invisible base and a visible part above
zero, and the same below zero: a bar that crosses zero draws right.
Returns
-------
_ChartRanges
The first and last data rows of each block.
"""
_sheet_title(worksheet, "chart_data")
bridge_rows = None
if bridge:
for column, header in enumerate(text.CHART_DATA_HEADERS, start=1):
worksheet.cell(row=3, column=column, value=header)
running = 0.0
for row, step in enumerate(bridge, start=4):
if step.kind == "total":
low, high = min(0.0, step.value), max(0.0, step.value)
running = step.value
label = text.CHARTS["bridge_total_label"].format(label=step.label, value=step.value)
else:
low, high = sorted((running, running + step.value))
running += step.value
label = text.CHARTS["bridge_effect_label"].format(label=step.label, value=step.value)
above = (max(low, 0.0), max(high, 0.0))
below = (min(high, 0.0), min(low, 0.0))
visible_above = above[1] - above[0]
visible_below = below[1] - below[0]
parts = {"total": [0.0] * 2, "gain": [0.0] * 2, "loss": [0.0] * 2}
parts[step.kind] = [visible_above, visible_below]
values = [label, step.value, above[0], below[0], *parts["gain"], *parts["loss"], *parts["total"]]
for column, value in enumerate(values, start=1):
worksheet.cell(row=row, column=column, value=value)
bridge_rows = (4, 3 + len(bridge))
factor_rows = None
if factors:
first_column = len(text.CHART_DATA_HEADERS) + 2
for offset, header in enumerate(text.CHART_FACTOR_HEADERS):
worksheet.cell(row=3, column=first_column + offset, value=header)
ranked = sorted(factors, key=lambda factor: factor.contribution, reverse=True)
for row, factor in enumerate(ranked, start=4):
worksheet.cell(row=row, column=first_column, value=factor.label)
worksheet.cell(row=row, column=first_column + 1, value=factor.contribution)
factor_rows = (4, 3 + len(ranked))
return _ChartRanges(bridge=bridge_rows, factors=factor_rows)
def _add_summary_charts(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
result: AttributionResult,
headline: _Headline,
data_worksheets: Mapping[str, openpyxl.worksheet.worksheet.Worksheet],
chart_data: openpyxl.worksheet.worksheet.Worksheet | None,
ranges: _ChartRanges,
) -> None:
"""The summary's charts, stacked to the right of the tables from row 3."""
charts = []
if chart_data is not None and ranges.bridge is not None:
charts.append(_bridge_chart(chart_data, *ranges.bridge))
returns = _returns_chart_source(result, data_worksheets)
if returns is not None:
charts.append(_line_chart(*returns, title=text.CHARTS["returns_title"]))
if "bf_cumulative" in data_worksheets and result.brinson_fachler is not None:
cumulative = result.brinson_fachler.cumulative
if cumulative.num_rows:
charts.append(_line_chart(
data_worksheets["bf_cumulative"],
cumulative,
list(text.EFFECT_NAMES),
title=text.CHARTS["effects_title"],
))
if chart_data is not None and ranges.factors is not None:
ranked = sorted((factor.contribution for factor in headline.factors), reverse=True)
charts.append(_factor_chart(chart_data, *ranges.factors, ranked))
column = openpyxl.utils.get_column_letter(_CHART_COLUMN)
for index, chart in enumerate(charts):
worksheet.add_chart(chart, f"{column}{3 + index * _CHART_HEIGHT_ROWS}")
def _returns_chart_source(
result: AttributionResult,
data_worksheets: Mapping[str, openpyxl.worksheet.worksheet.Worksheet],
) -> tuple[openpyxl.worksheet.worksheet.Worksheet, pa.Table, list[str]] | None:
"""The data sheet, table and columns of the cumulative return chart, the first one with rows."""
candidates = []
if result.brinson_fachler is not None:
candidates.append((
"bf_cumulative",
result.brinson_fachler.cumulative,
["portfolio_returns", "benchmark_returns", "alpha"],
))
if result.factor_model is not None and result.factor_model.active is not None:
candidates.append((
"active_totals",
result.factor_model.active.cumulative_totals,
["portfolio_returns", "benchmark_returns", "active_returns"],
))
if result.factor_model is not None:
candidates.append(("factor_totals", result.factor_model.cumulative_totals, ["portfolio_returns"]))
for key, table, columns in candidates:
if key in data_worksheets and table.num_rows:
return data_worksheets[key], table, columns
return None
def _line_chart(
data_worksheet: openpyxl.worksheet.worksheet.Worksheet,
table: pa.Table,
columns: Sequence[str],
*,
title: str,
) -> openpyxl.chart.LineChart:
"""A line chart over dates of `columns` of a data sheet; each line differs in colour and dash."""
chart = openpyxl.chart.LineChart()
chart.title = title
chart.height = 9
chart.width = 18
chart.y_axis.title = text.CHARTS["return_axis"]
chart.y_axis.number_format = CHART_PERCENT_FORMAT
chart.y_axis.crossAx = 500
chart.x_axis = openpyxl.chart.axis.DateAxis(crossAx=100)
chart.x_axis.axPos = "b"
chart.x_axis.number_format = DATE_FORMAT
chart.x_axis.title = text.CHARTS["date_axis"]
last_row = 3 + table.num_rows
for name, (color, dash) in zip(columns, LINE_STYLES, strict=False):
column = table.column_names.index(name) + 1
chart.add_data(
openpyxl.chart.Reference(data_worksheet, min_col=column, min_row=3, max_row=last_row),
titles_from_data=True,
)
series = chart.series[-1]
series.marker.symbol = "none"
series.smooth = False
series.graphicalProperties.line.solidFill = color
series.graphicalProperties.line.dashStyle = dash
series.graphicalProperties.line.width = 22000
chart.set_categories(openpyxl.chart.Reference(data_worksheet, min_col=1, min_row=4, max_row=last_row))
_show_axes(chart)
return chart
def _bridge_chart(
chart_data: openpyxl.worksheet.worksheet.Worksheet,
first_row: int,
last_row: int,
) -> openpyxl.chart.BarChart:
"""The bridge from benchmark to portfolio return: stacked columns over invisible bases."""
chart = openpyxl.chart.BarChart()
chart.type = "col"
chart.grouping = "stacked"
chart.overlap = 100
chart.gapWidth = 60
chart.title = text.CHARTS["bridge_title"]
chart.height = 9
chart.width = 18
chart.legend = None
series_columns = openpyxl.chart.Reference(
chart_data, min_col=3, max_col=len(text.CHART_DATA_HEADERS), min_row=3, max_row=last_row
)
chart.add_data(series_columns, titles_from_data=True)
chart.set_categories(openpyxl.chart.Reference(chart_data, min_col=1, min_row=first_row, max_row=last_row))
fills = (None, None, GAIN_COLOR, GAIN_COLOR, LOSS_COLOR, LOSS_COLOR, NEUTRAL_COLOR, NEUTRAL_COLOR)
for series, fill in zip(chart.series, fills, strict=True):
if fill is None:
series.graphicalProperties.noFill = True
series.graphicalProperties.line.noFill = True
else:
series.graphicalProperties.solidFill = fill
series.graphicalProperties.line.solidFill = fill
chart.y_axis.title = text.CHARTS["return_axis"]
chart.y_axis.number_format = CHART_PERCENT_FORMAT
_show_axes(chart)
return chart
def _factor_chart(
chart_data: openpyxl.worksheet.worksheet.Worksheet,
first_row: int,
last_row: int,
contributions: Sequence[float],
) -> openpyxl.chart.BarChart:
"""Horizontal bars of the factors' contributions, largest at the top, gains blue and losses vermilion, labelled."""
first_column = len(text.CHART_DATA_HEADERS) + 2
chart = openpyxl.chart.BarChart()
chart.type = "bar"
chart.title = text.CHARTS["factors_title"]
chart.height = max(9, 0.6 * len(contributions))
chart.width = 18
chart.legend = None
chart.add_data(
openpyxl.chart.Reference(chart_data, min_col=first_column + 1, min_row=first_row, max_row=last_row),
titles_from_data=False,
)
chart.set_categories(
openpyxl.chart.Reference(chart_data, min_col=first_column, min_row=first_row, max_row=last_row)
)
series = chart.series[0]
series.invertIfNegative = False
for index, contribution in enumerate(contributions):
point = openpyxl.chart.marker.DataPoint(idx=index)
color = GAIN_COLOR if contribution >= 0.0 else LOSS_COLOR
point.graphicalProperties.solidFill = color
point.graphicalProperties.line.solidFill = color
series.dPt.append(point)
series.dLbls = openpyxl.chart.label.DataLabelList()
series.dLbls.showVal = True
series.dLbls.showSerName = False
series.dLbls.showCatName = False
series.dLbls.showLegendKey = False
series.dLbls.numFmt = CHART_SIGNED_FORMAT
chart.x_axis.title = text.CHARTS["factor_axis"]
chart.x_axis.axPos = "l"
chart.x_axis.scaling.orientation = "maxMin"
chart.y_axis.title = text.CHARTS["return_axis"]
chart.y_axis.axPos = "b"
chart.y_axis.number_format = CHART_PERCENT_FORMAT
chart.y_axis.crosses = "max"
_show_axes(chart)
return chart
def _show_axes(chart: openpyxl.chart.LineChart | openpyxl.chart.BarChart) -> None:
"""Keep both axes visible: openpyxl leaves them unset, which recent Excel versions read as hidden."""
chart.x_axis.delete = False
chart.y_axis.delete = False
# --- Checks and how-to-read sheets ------------------------------------------------
def _write_checks(worksheet: openpyxl.worksheet.worksheet.Worksheet, result: AttributionResult, name: str) -> None:
"""
The run's parameters, how the numbers were computed, then one row per diagnostic.
Parameters
----------
worksheet : Worksheet
The ``checks`` sheet.
result : AttributionResult
The run to report.
name : str
Report name.
"""
_sheet_title(worksheet, "checks")
for column, width in zip("ABCDEF", (26, 16, 90, 10, 14, 40), strict=True):
worksheet.column_dimensions[column].width = width
row = _write_label_values(
worksheet,
4,
text.CHECKS["parameters"],
(text.CHECKS["parameter"], text.CHECKS["value"]),
_parameters(result, name),
)
row = _write_label_values(
worksheet,
row + _TABLE_GAP + 1,
text.CHECKS["methodology"],
(text.CHECKS["item"], text.CHECKS["description"]),
[(label, description, None) for label, description in _methodology(result)],
)
row += _TABLE_GAP + 1
worksheet.cell(row=row, column=1, value=text.CHECKS["diagnostics"]).font = _SUBTITLE_FONT
headers = [
text.CHECKS["area"],
text.CHECKS["level"],
text.CHECKS["what_happened"],
text.CHECKS["count"],
text.CHECKS["first_date"],
text.CHECKS["code"],
]
_header_row(worksheet, row + 1, headers)
row += 1
if not result.diagnostics:
worksheet.cell(row=row + 1, column=1, value=text.CHECKS["no_diagnostics"])
for diagnostic in result.diagnostics:
row += 1
expected = _is_expected(diagnostic, result)
what_happened = _diagnostic_text(diagnostic, expected=expected)
values = (
text.DIAGNOSTIC_AREAS.get(diagnostic.code.value, text.UNKNOWN_AREA),
text.LEVEL_NAMES["expected" if expected else diagnostic.level.value],
what_happened,
diagnostic.count,
diagnostic.first_date,
diagnostic.code.value,
)
for column, value in enumerate(values, start=1):
cell = worksheet.cell(row=row, column=column, value=value)
cell.border = _BORDER
cell.alignment = _WRAP
worksheet.cell(row=row, column=4).number_format = INTEGER_FORMAT
worksheet.cell(row=row, column=5).number_format = DATE_FORMAT
worksheet.row_dimensions[row].height = _wrapped_height(what_happened, 90)
def _write_label_values(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
title: str,
headers: tuple[str, str],
items: Sequence[tuple[str, object, str | None]],
) -> int:
"""A titled two-column block (label in A, value across B:C); returns its last row."""
worksheet.cell(row=row, column=1, value=title).font = _SUBTITLE_FONT
_header_row(worksheet, row + 1, list(headers), merge_to=3)
current = row + 1
for label, value, number_format in items:
current += 1
label_cell = worksheet.cell(row=current, column=1, value=label)
label_cell.border = _BORDER
label_cell.fill = _INFO_FILL
label_cell.alignment = _WRAP
worksheet.merge_cells(start_row=current, start_column=2, end_row=current, end_column=3)
value_cell = worksheet.cell(row=current, column=2, value=value)
value_cell.border = _BORDER
value_cell.alignment = _WRAP
if number_format is not None:
value_cell.number_format = number_format
if isinstance(value, str):
worksheet.row_dimensions[current].height = _wrapped_height(value, 106)
return current
def _parameters(result: AttributionResult, name: str) -> list[tuple[str, object, str | None]]:
"""The checks sheet's parameter rows: label, value and number format (``None`` for text)."""
labels = text.PARAMETER_LABELS
parameters: list[tuple[str, object, str | None]] = [
(labels["report"], name, None),
(labels["start_date"], result.start_date, DATE_FORMAT),
(labels["end_date"], result.end_date, DATE_FORMAT),
(labels["return_dates"], result.portfolio_returns.num_rows, INTEGER_FORMAT),
(labels["methods"], text.LIST_SEPARATOR.join(_methods(result)), None),
]
if result.brinson_fachler is not None:
parameters += [
(labels["brinson_fachler_formula"], text.FORMULA_NAMES[result.brinson_fachler.formula.value], None),
(labels["brinson_fachler_linking"], text.LINKING_NAMES[result.brinson_fachler.linking.value], None),
(labels["segments"], _name_list(_segments(result)), None),
]
factor_model = result.factor_model
if factor_model is not None:
parameters += [
(labels["factor_model_linking"], text.LINKING_NAMES[factor_model.linking.value], None),
(labels["factor_files"], _name_list(_factor_columns(factor_model.contributions)), None),
(labels["component_files"], _name_list(_component_columns(factor_model.contributions)), None),
(labels["active_factor_model"], text.YES if factor_model.active is not None else text.NO, None),
]
parameters.append((labels["implementation"], text.YES if result.implementation is not None else text.NO, None))
return parameters
def _methodology(result: AttributionResult) -> list[tuple[str, str]]:
"""How the numbers were computed, item by item, as the CFA Institute's draft guide lists the disclosures."""
labels = text.METHODOLOGY_LABELS
notes = text.METHODOLOGY
backtest = result.implementation is not None
linking = (
result.brinson_fachler.linking if result.brinson_fachler is not None
else result.factor_model.linking if result.factor_model is not None
else LinkingMethod.NONE
)
items = [
(labels["basis"], notes["basis_backtest" if backtest else "basis_holdings"]),
(labels["costs"], notes["costs_backtest" if backtest else "costs_gross"]),
(labels["periods"], notes[f"periods_{linking.value}"]),
]
if result.brinson_fachler is not None:
items += [
(labels["excess"], notes["excess"]),
(labels["interaction"], notes["interaction"]),
(
labels["residual"],
notes["residual_none" if result.brinson_fachler.linking is LinkingMethod.NONE else "residual_linked"],
),
]
has_active = result.factor_model is not None and result.factor_model.active is not None
if result.brinson_fachler is not None or has_active:
items.append((labels["benchmark"], notes["benchmark"]))
if result.factor_model is not None:
items.append((labels["factor_model"], notes["factor_model"]))
items.append((labels["annualization"], notes["annualization"]))
return items
def _name_list(names: Sequence[str]) -> str:
"""A count of names and the first ``_LISTED_NAMES`` of them, or ``NONE_TEXT``."""
if not names:
return text.NONE_TEXT
shown = text.LIST_SEPARATOR.join(names[:_LISTED_NAMES])
if len(names) > _LISTED_NAMES:
shown = text.MORE_ITEMS.format(shown=shown, more=len(names) - _LISTED_NAMES)
return text.FILE_LIST.format(count=len(names), names=shown)
def _diagnostic_text(diagnostic: Diagnostic, *, expected: bool = False) -> str:
"""
What a diagnostic reports, in the report's words.
The code's template is filled from the diagnostic's fields; the logged
line is the fallback for a code without a template, or a template whose
fields the diagnostic does not have.
Parameters
----------
diagnostic : Diagnostic
One of ``AttributionResult.diagnostics``.
expected : bool, default False
Whether every run of this kind logs it: its expected-case text is used.
Returns
-------
str
One sentence or two.
"""
templates = text.EXPECTED_DIAGNOSTIC_TEXTS if expected else text.DIAGNOSTIC_TEXTS
template = templates.get(diagnostic.code.value)
if template is None:
return diagnostic.message
fields: dict[str, object] = {
"count": diagnostic.count,
"total": diagnostic.total,
"first_date": diagnostic.first_date.isoformat() if diagnostic.first_date is not None else text.UNKNOWN_DATE,
}
for key, value in diagnostic.details.items():
if key == "side":
fields[key] = text.SIDE_NAMES.get(str(value), str(value))
elif key == "linking_method":
fields[key] = text.LINKING_NAMES.get(str(value), str(value))
elif isinstance(value, datetime.date):
fields[key] = value.isoformat()
else:
fields[key] = value
try:
return template.format(**fields)
except (KeyError, TypeError, ValueError):
return diagnostic.message
def _write_how_to_read(worksheet: openpyxl.worksheet.worksheet.Worksheet, sheet_keys: Sequence[str]) -> None:
"""
The definitions, then what each sheet of this workbook holds, each sheet linked.
Parameters
----------
worksheet : Worksheet
The ``how_to_read`` sheet.
sheet_keys : Sequence[str]
Keys of the workbook's visible sheets, in order.
"""
_sheet_title(worksheet, "how_to_read")
worksheet.column_dimensions["A"].width = 26
worksheet.column_dimensions["B"].width = 100
row = 4
worksheet.cell(row=row, column=1, value=text.HOW_TO_READ["terms"]).font = _SUBTITLE_FONT
_header_row(worksheet, row + 1, [text.HOW_TO_READ["term"], text.HOW_TO_READ["meaning"]])
row += 1
for term, meaning in text.DEFINITIONS:
row += 1
term_cell = worksheet.cell(row=row, column=1, value=term)
term_cell.font = _BOLD_FONT
_definition_row(worksheet, row, term_cell, meaning)
row += _TABLE_GAP + 1
worksheet.cell(row=row, column=1, value=text.HOW_TO_READ["sheets"]).font = _SUBTITLE_FONT
_header_row(worksheet, row + 1, [text.HOW_TO_READ["sheet"], text.HOW_TO_READ["contents"]])
row += 1
for key in sheet_keys:
row += 1
sheet_cell = worksheet.cell(row=row, column=1)
_link_cell(sheet_cell, text.SHEET_NAMES[key])
_definition_row(worksheet, row, sheet_cell, text.SHEET_DESCRIPTIONS[key])
def _definition_row(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
term_cell: openpyxl.cell.cell.Cell,
meaning: str,
) -> None:
"""A term (already written) and its wrapped meaning."""
term_cell.border = _BORDER
term_cell.alignment = _WRAP
meaning_cell = worksheet.cell(row=row, column=2, value=meaning)
meaning_cell.border = _BORDER
meaning_cell.alignment = _WRAP
worksheet.row_dimensions[row].height = _wrapped_height(meaning, 100)
# --- Data sheets ----------------------------------------------------------------
def _write_data_sheet(worksheet: openpyxl.worksheet.worksheet.Worksheet, data_sheet: _DataSheet) -> None:
"""
A result table: title at A1, description at A2, headers on row 3, one row per table row from row 4.
The rows form an Excel table, with filters. Date columns are real Excel
dates; returns get a plain percentage format and effects a signed one
(three decimals for daily values); null, NaN and infinite values are left
empty.
Parameters
----------
worksheet : Worksheet
The data sheet.
data_sheet : _DataSheet
Its table and whether its values are daily.
"""
_sheet_title(worksheet, data_sheet.key)
table = data_sheet.table
headers = _unique([_header_label(column) for column in table.column_names])
_header_row(worksheet, 3, headers)
for column_index, column in enumerate(table.column_names, start=1):
number_format = _column_format(column, table.schema.field(column).type, daily=data_sheet.daily)
style_name = text.STYLE_NAMES[_DATA_CELL_STYLES[number_format][0]]
for row_index, value in enumerate(table.column(column).to_pylist(), start=4):
worksheet.cell(row=row_index, column=column_index, value=_excel_value(value)).style = style_name
width = max(12, min(len(headers[column_index - 1]) + 4, 28))
worksheet.column_dimensions[openpyxl.utils.get_column_letter(column_index)].width = width
worksheet.freeze_panes = "B4"
if table.num_rows and table.num_columns:
last_cell = f"{openpyxl.utils.get_column_letter(table.num_columns)}{3 + table.num_rows}"
excel_table = openpyxl.worksheet.table.Table(displayName=f"Data_{data_sheet.key}", ref=f"A3:{last_cell}")
excel_table.tableStyleInfo = openpyxl.worksheet.table.TableStyleInfo(
name="TableStyleLight1", showRowStripes=True
)
worksheet.add_table(excel_table)
def _header_label(column: str) -> str:
"""A data-sheet column's header: the known label, a factor's display name, or the column name."""
if column in text.COLUMN_LABELS:
return text.COLUMN_LABELS[column]
if column.startswith("f_"):
return _factor_label(column)
return column
def _unique(headers: Sequence[str]) -> list[str]:
"""`headers` made unique, as an Excel table needs: a repeated header gets `` (2)``, `` (3)``..."""
seen: dict[str, int] = {}
unique = []
for header in headers:
seen[header] = seen.get(header, 0) + 1
unique.append(header if seen[header] == 1 else f"{header} ({seen[header]})")
return unique
def _column_format(column: str, data_type: pa.DataType, *, daily: bool) -> str | None:
"""The number format of a data-sheet column: dates, years, returns, effects, or text (``None``)."""
if pa.types.is_timestamp(data_type) or pa.types.is_date(data_type):
return DATE_FORMAT
if column == "year":
return INTEGER_FORMAT
if pa.types.is_floating(data_type) or pa.types.is_integer(data_type) or pa.types.is_decimal(data_type):
if column in UNSIGNED_COLUMNS:
return DAILY_PERCENT_FORMAT if daily else PERCENT_FORMAT
return DAILY_SIGNED_FORMAT if daily else SIGNED_PERCENT_FORMAT
return None
def _sheet_title(worksheet: openpyxl.worksheet.worksheet.Worksheet, key: str) -> None:
"""The sheet's title at A1 (merged to D1) and its description at A2."""
worksheet.merge_cells(start_row=1, start_column=1, end_row=1, end_column=_DATA_SHEET_LAST_TITLE_COLUMN)
worksheet["A1"] = text.SHEET_TITLES[key]
worksheet["A1"].font = _SHEET_TITLE_FONT
worksheet["A1"].alignment = _CENTER
worksheet["A2"] = text.SHEET_DESCRIPTIONS[key]
worksheet["A2"].font = _DESCRIPTION_FONT
def _back_link(worksheet: openpyxl.worksheet.worksheet.Worksheet) -> None:
"""A link back to the summary, to the right of the sheet's title."""
_link_cell(
worksheet.cell(row=1, column=_DATA_SHEET_LAST_TITLE_COLUMN + 2),
text.SHEET_NAMES["summary"],
label=text.BACK_TO_SUMMARY,
)
def _link_cell(cell: openpyxl.cell.cell.Cell, sheet_name: str, *, label: str | None = None) -> None:
"""`cell` as a link to cell A1 of the sheet `sheet_name`, showing `label` (the sheet name by default)."""
cell.value = sheet_name if label is None else label
# A link inside the workbook: a location, not a file target.
cell.hyperlink = openpyxl.worksheet.hyperlink.Hyperlink(ref=cell.coordinate, location=f"'{sheet_name}'!A1")
cell.font = _LINK_FONT
cell.border = _BORDER
def _print_setup(worksheet: openpyxl.worksheet.worksheet.Worksheet, name: str, *, data_sheet: bool) -> None:
"""Landscape, one page wide, the report name and page number in the footer; data sheets repeat their headers."""
worksheet.page_setup.orientation = "landscape"
worksheet.page_setup.fitToWidth = 1
worksheet.page_setup.fitToHeight = 0
worksheet.sheet_properties.pageSetUpPr.fitToPage = True
worksheet.oddFooter.left.text = name
worksheet.oddFooter.right.text = text.FOOTER_PAGE
if data_sheet:
worksheet.print_title_rows = "3:3"
def _header_row(
worksheet: openpyxl.worksheet.worksheet.Worksheet,
row: int,
headers: Sequence[str],
*,
merge_to: int | None = None,
) -> None:
"""Bold white headers on the report's red fill; the last header can span up to column `merge_to`."""
for column, header in enumerate(headers, start=1):
cell = worksheet.cell(row=row, column=column, value=header)
cell.font = _HEADER_FONT
cell.fill = _HEADER_FILL
cell.alignment = _CENTER
cell.border = _BORDER
if merge_to is not None and merge_to > len(headers):
worksheet.merge_cells(start_row=row, start_column=len(headers), end_row=row, end_column=merge_to)
# --- Values and files -------------------------------------------------------------
def _excel_value(value: object) -> object:
"""
`value` as Excel can store it.
Null, NaN and infinite numbers become empty cells; timestamps become naive
datetimes (Excel has no time zones); anything that is not a number, date or
text becomes its text.
"""
if value is None or isinstance(value, (bool, str, int)):
return value
if isinstance(value, float):
return value if math.isfinite(value) else None
if isinstance(value, datetime.datetime):
if pd.isna(value):
return None
as_datetime = value.to_pydatetime() if isinstance(value, pd.Timestamp) else value
return as_datetime.replace(tzinfo=None)
if isinstance(value, datetime.date):
return value
number = _as_float(value)
if number is not None:
return number if math.isfinite(number) else None
return str(value)
def _as_float(value: object) -> float | None:
"""`value` as a float when it is a number (e.g. ``decimal.Decimal`` or a numpy scalar), else ``None``."""
try:
return float(value) # type: ignore[arg-type]
except (TypeError, ValueError):
return None
def _wrapped_height(content: str, width: float) -> float:
"""Row height in points for `content` wrapped in a column (or merged columns) `width` characters wide."""
lines = max(1, math.ceil(len(content) / max(width, 1.0)))
return 15.0 * lines
def _file_name(name: str) -> str:
"""`name` without the characters a file name cannot hold (``Portfolio`` when nothing is left)."""
cleaned = _INVALID_FILE_NAME_CHARACTERS.sub("_", name).strip().rstrip(".")
return cleaned or "Portfolio"
def _save_as_new_file(workbook: openpyxl.Workbook, directory: Path, stem: str) -> Path:
"""
Save `workbook` as ``{stem}.xlsx`` in `directory`, or ``{stem}_2.xlsx``... when that file exists.
The file is created exclusively, so a report never overwrites another, and
removed again when saving fails.
Raises
------
FileExistsError
If ``_MAXIMUM_FILE_ATTEMPTS`` names are taken.
"""
for attempt in range(1, _MAXIMUM_FILE_ATTEMPTS + 1):
suffix = "" if attempt == 1 else f"_{attempt}"
path = directory / f"{stem}{suffix}.xlsx"
try:
handle = path.open("xb")
except FileExistsError:
continue
try:
with handle:
workbook.save(handle)
except BaseException:
path.unlink(missing_ok=True)
raise
return path
message = f"{_MAXIMUM_FILE_ATTEMPTS} reports named {stem}*.xlsx already exist in {directory}"
raise FileExistsError(message)