Source code for kaxanuk.attribution_analysis.output_handlers.excel_output_handler
"""
Excel output handler: writes the Excel report of an attribution result.
The workbook itself is built by
:func:`~kaxanuk.attribution_analysis.output_handlers.excel_report.write_excel_report`;
this handler carries where to write it and how to name it, so ``main()`` can
write it like any other output.
"""
import os
import typing
from pathlib import Path
from kaxanuk.attribution_analysis.entities.attribution_result import AttributionResult
from kaxanuk.attribution_analysis.entities.configuration import Configuration
from kaxanuk.attribution_analysis.output_handlers.excel_report import write_excel_report
from kaxanuk.attribution_analysis.output_handlers.output_handler_interface import OutputHandlerInterface
[docs]
class ExcelOutputHandler(OutputHandlerInterface):
"""
Writes the Excel report of a result to a directory.
The handler ``main()`` uses when it is given no output handlers (see
:meth:`from_configuration`).
Parameters
----------
output_directory : str or os.PathLike
Directory the workbook is written to; created when missing.
name : str, default "Portfolio"
Report name: the summary's title and the start of the file name.
benchmark_name : str or None, default None
Shown in the summary's info block when given.
Attributes
----------
output_directory : str or os.PathLike
name : str
benchmark_name : str or None
"""
def __init__(
self,
output_directory: str | os.PathLike[str],
*,
name: str = "Portfolio",
benchmark_name: str | None = None,
) -> None:
self.output_directory = output_directory
self.name = name
self.benchmark_name = benchmark_name
[docs]
@classmethod
def from_configuration(cls, configuration: Configuration) -> typing.Self:
"""
The handler of a file-based run: its ``output_directory``, named after its portfolio file.
Parameters
----------
configuration : Configuration
Supplies ``output_directory``, ``portfolio_file_name`` (the report
name) and ``benchmark_file_name`` (the benchmark shown).
Returns
-------
ExcelOutputHandler
The handler ``main()`` uses by default.
"""
return cls(
configuration.output_directory,
name=configuration.portfolio_file_name,
benchmark_name=configuration.benchmark_file_name,
)
[docs]
def output_result(self, *, result: AttributionResult) -> Path:
"""
Write the Excel report of `result` and return the workbook's path.
Parameters
----------
result : AttributionResult
The run's result; only read.
Returns
-------
Path
``{name}_{UTC %Y%m%d%H%M%S}_attribution_results.xlsx`` in
``output_directory`` (see
:func:`~kaxanuk.attribution_analysis.output_handlers.excel_report.write_excel_report`).
Raises
------
OSError
If the directory or the workbook cannot be written.
"""
return write_excel_report(
result,
self.output_directory,
name=self.name,
benchmark_name=self.benchmark_name,
)