"""
Dataclass encapsulating the user's selected configuration.
Configuration instances are typically built by config handlers (e.g.
`kaxanuk.attribution_analysis.config_handlers.excel_configurator`) from
user-supplied settings, and consumed by the attribution engine to locate
input files and select processing options.
"""
import dataclasses
import datetime
from typing import Literal
from kaxanuk.attribution_analysis.entities.attribution_options import (
AttributionSettings,
BrinsonFachlerFormula,
FactorReturnType,
LinkingMethod,
)
from kaxanuk.attribution_analysis.exceptions import ConfigurationError
# Type alias for date configuration: either an explicit date or "auto" to derive from portfolio
type DateConfig = datetime.date | Literal["auto"]
[docs]
@dataclasses.dataclass(frozen=True, slots=True)
class Configuration:
"""
Immutable, validated configuration for a single attribution analysis run.
All fields are validated in `__post_init__`, which raises
:class:`~kaxanuk.attribution_analysis.exceptions.ConfigurationError`
on the first invalid field found. `start_date` and `end_date` are
additionally normalized from :class:`datetime.datetime` to
:class:`datetime.date` if needed.
Parameters
----------
input_directory : str
Base directory containing market data input files.
weights_portfolio_directory : str
Directory containing portfolio weights files.
weights_benchmark_directory : str
Directory containing benchmark weights files.
benchmark_returns_directory : str
Directory containing benchmark returns files.
investable_assets_directory : str
Directory containing investable assets market data files.
factor_returns_by_factor_directory : str
Directory containing per-factor returns files, one file per
factor.
portfolio_file_name : str
File name (without extension) of the portfolio weights file, in
`weights_portfolio_directory`.
benchmark_file_name : str
File name (without extension) of the benchmark weights file, in
`weights_benchmark_directory`.
benchmark_return_file_name : str
File name (without extension) of the benchmark returns file, in
`benchmark_returns_directory`.
user_column_date : str
Name of the date column as it appears in the user's input files.
user_column_price : str
Name of the price column as it appears in the user's input files.
market_data_input_format : {"csv", "parquet"}
File format of the market data input files.
portfolio_input_format : {"csv", "excel"}
File format of the portfolio/benchmark weights input files.
start_date : datetime.date or datetime.datetime or {"auto"}
Start date of the analysis period, or ``"auto"`` to derive it
from the portfolio data. ``datetime.datetime`` values are
normalized to ``datetime.date`` after validation.
end_date : datetime.date or datetime.datetime or {"auto"}
End date of the analysis period, or ``"auto"`` to derive it from
the portfolio data. ``datetime.datetime`` values are normalized
to ``datetime.date`` after validation.
brinson_fachler_method : bool
Whether to run the Brinson-Fachler attribution method.
factor_model_method : bool
Whether to run the factor model attribution method.
brinson_fachler_formula : {"textbook", "legacy"}, default "textbook"
Brinson-Fachler variant. ``"legacy"`` reproduces the previous asset-level numbers (0.3.x and earlier)
and is deprecated. Normalized to :class:`BrinsonFachlerFormula`.
segment_map_file_name : str or None, default None
File name (without extension) of a ``ticker,segment`` CSV in
`input_directory`. ``None`` makes every ticker its own segment.
cash_ticker : str, default "CASH"
Ticker that holds cash with the textbook formula: implied cash fills
weights that sum below 1, it needs no price file and its return is 0
(a price file for it is ignored, with a warning). With the legacy
formula or the factor model alone it is an ordinary ticker.
factor_return_type : {"simple", "log"}, default "simple"
Compounding convention of the per-factor return files. Normalized to
:class:`FactorReturnType`.
linking_method : {"carino", "grap", "none"}, default "carino"
How per-period effects are combined over time (see
:class:`LinkingMethod`). Legacy Brinson-Fachler always uses "none".
risk_free_rate : float, default 0.0
Annual risk-free rate as a decimal for the Sharpe ratio. Set from
Python only (no row in the Excel parameters file), e.g.
``dataclasses.replace(configuration, risk_free_rate=0.03)``.
active_factor_model : bool, default False
Also decompose the active return (portfolio minus the benchmark built
from the benchmark weights file) by factor. Set from Python only (no
row in the Excel parameters file). Needs `factor_model_method`; every
weighted benchmark constituent needs a price file.
output_directory : str, default "Output"
Directory :func:`~kaxanuk.attribution_analysis.performance_attribution.main`
writes the Excel report to (created when missing; relative paths are
relative to the working directory). ``run_attribution`` never writes.
Optional row of the Excel parameters file.
Raises
------
ConfigurationError
If any field fails validation (see `__post_init__`).
"""
# Routes
input_directory: str
weights_portfolio_directory: str
weights_benchmark_directory: str
benchmark_returns_directory: str
investable_assets_directory: str
factor_returns_by_factor_directory: str
# File names
portfolio_file_name: str
benchmark_file_name: str
benchmark_return_file_name: str
# Column mappings
user_column_date: str
user_column_price: str
# Input format
market_data_input_format: str
portfolio_input_format: str
# Date range
start_date: DateConfig
end_date: DateConfig
# Methods
brinson_fachler_method: bool
factor_model_method: bool
# Attribution options (optional: defaults keep existing configurations valid)
brinson_fachler_formula: BrinsonFachlerFormula | str = BrinsonFachlerFormula.TEXTBOOK
segment_map_file_name: str | None = None
cash_ticker: str = "CASH"
factor_return_type: FactorReturnType | str = FactorReturnType.SIMPLE
linking_method: LinkingMethod | str = LinkingMethod.CARINO
risk_free_rate: float = 0.0
active_factor_model: bool = False
# Output (optional)
output_directory: str = "Output"
def __post_init__(self) -> None:
"""
Validate and normalize all configuration fields.
Raises
------
ConfigurationError
If any route, file name, or column mapping field isn't a
str; if `market_data_input_format` isn't ``"csv"`` or
``"parquet"``; if `portfolio_input_format` isn't ``"csv"`` or
``"excel"``; if `start_date` or `end_date` is neither
``"auto"`` nor a ``datetime.date``/``datetime.datetime``; if
`segment_map_file_name` is neither ``None`` nor a non-empty str;
or if the method flags and options fail
:class:`AttributionSettings` validation (a flag that isn't a
bool, an invalid formula, factor return type or linking method,
an empty `cash_ticker`, an invalid `risk_free_rate`, or an
`active_factor_model` that isn't a bool or is on without
`factor_model_method`); or if `output_directory` is not a
non-empty str.
"""
# Routes validation
if not isinstance(self.input_directory, str):
raise ConfigurationError(
"Incorrect format for input_directory, expecting a str"
)
if not isinstance(self.weights_portfolio_directory, str):
raise ConfigurationError(
"Incorrect format for weights_portfolio_directory, expecting a str"
)
if not isinstance(self.weights_benchmark_directory, str):
raise ConfigurationError(
"Incorrect format for weights_benchmark_directory, expecting a str"
)
if not isinstance(self.benchmark_returns_directory, str):
raise ConfigurationError(
"Incorrect format for benchmark_returns_directory, expecting a str"
)
if not isinstance(self.investable_assets_directory, str):
raise ConfigurationError(
"Incorrect format for investable_assets_directory, expecting a str"
)
if not isinstance(self.factor_returns_by_factor_directory, str):
raise ConfigurationError(
"Incorrect format for factor_returns_by_factor_directory, expecting a str"
)
# Column mappings validation
if not isinstance(self.user_column_date, str):
raise ConfigurationError(
"Incorrect format for user_column_date, expecting a str"
)
if not isinstance(self.user_column_price, str):
raise ConfigurationError(
"Incorrect format for user_column_price, expecting a str"
)
# Input format validation
if self.market_data_input_format not in ("csv", "parquet"):
raise ConfigurationError(
"Incorrect value for market_data_input_format, expecting 'csv' or 'parquet'"
)
if self.portfolio_input_format not in ("csv", "excel"):
raise ConfigurationError(
"Incorrect value for portfolio_input_format, expecting 'csv' or 'excel'"
)
# Date range validation and normalization
if self.start_date != "auto":
if not isinstance(self.start_date, (datetime.date, datetime.datetime)):
raise ConfigurationError(
"Incorrect Configuration.start_date type; "
"expecting datetime.date, datetime.datetime, or 'auto'"
)
if isinstance(self.start_date, datetime.datetime):
object.__setattr__(self, 'start_date', self.start_date.date())
if self.end_date != "auto":
if not isinstance(self.end_date, (datetime.date, datetime.datetime)):
raise ConfigurationError(
"Incorrect Configuration.end_date type; "
"expecting datetime.date, datetime.datetime, or 'auto'"
)
if isinstance(self.end_date, datetime.datetime):
object.__setattr__(self, 'end_date', self.end_date.date())
# File names validation
if not isinstance(self.portfolio_file_name, str):
raise ConfigurationError(
"Incorrect format for portfolio_file_name, expecting a str"
)
if not isinstance(self.benchmark_file_name, str):
raise ConfigurationError(
"Incorrect format for benchmark_file_name, expecting a str"
)
if not isinstance(self.benchmark_return_file_name, str):
raise ConfigurationError(
"Incorrect format for benchmark_return_file_name, expecting a str"
)
# Method flags and options: validated and normalized by AttributionSettings (same messages).
settings = AttributionSettings(
brinson_fachler_method=self.brinson_fachler_method,
factor_model_method=self.factor_model_method,
brinson_fachler_formula=self.brinson_fachler_formula,
factor_return_type=self.factor_return_type,
linking_method=self.linking_method,
cash_ticker=self.cash_ticker,
risk_free_rate=self.risk_free_rate,
active_factor_model=self.active_factor_model,
)
object.__setattr__(self, 'brinson_fachler_formula', settings.brinson_fachler_formula)
object.__setattr__(self, 'factor_return_type', settings.factor_return_type)
object.__setattr__(self, 'linking_method', settings.linking_method)
object.__setattr__(self, 'cash_ticker', settings.cash_ticker)
object.__setattr__(self, 'risk_free_rate', settings.risk_free_rate)
if self.segment_map_file_name is not None and (
not isinstance(self.segment_map_file_name, str)
or not self.segment_map_file_name.strip()
):
raise ConfigurationError(
"Incorrect format for segment_map_file_name, expecting a non-empty str or None"
)
if self.segment_map_file_name is not None:
object.__setattr__(self, 'segment_map_file_name', self.segment_map_file_name.strip())
if not isinstance(self.output_directory, str) or not self.output_directory.strip():
raise ConfigurationError(
"Incorrect format for output_directory, expecting a non-empty str"
)
object.__setattr__(self, 'output_directory', self.output_directory.strip())
[docs]
def attribution_settings(self) -> AttributionSettings:
"""
The method options of this configuration as :class:`AttributionSettings`.
Returns
-------
AttributionSettings
Same flags, formula, factor return type, linking, cash ticker and risk-free rate.
"""
return AttributionSettings(
brinson_fachler_method=self.brinson_fachler_method,
factor_model_method=self.factor_model_method,
brinson_fachler_formula=self.brinson_fachler_formula,
factor_return_type=self.factor_return_type,
linking_method=self.linking_method,
cash_ticker=self.cash_ticker,
risk_free_rate=self.risk_free_rate,
active_factor_model=self.active_factor_model,
)
def __getitem__(self, item: str) -> object:
"""
Access a configuration field by name, dict-style.
Parameters
----------
item : str
Name of the field to retrieve (must match one of the
dataclass's field names).
Returns
-------
object
The value of the requested field.
Raises
------
AttributeError
If `item` doesn't match any field name.
"""
return getattr(self, item)