Configuration Reference#

The configuration file is Config/backtest_engine_parameters.xlsx, created by running kaxanuk.backtest_engine init excel. Open it in any spreadsheet editor and edit column B only. Column A contains the parameter names (do not modify) and column C contains descriptions.

Backtest Settings#

Parameter

Example value

Description

portfolio_name

my_portfolio

Filename of your portfolio without extension. Must exist in the portfolio directory.

benchmark_file_name

SPY

Ticker used as benchmark. A market data file for this ticker must exist in the data directory.

start_date

2020-01-02

Backtest start date (YYYY-MM-DD). Use auto to derive from the first date in the portfolio file.

end_date

2024-12-31

Backtest end date (YYYY-MM-DD). Use auto to derive from the last date in the portfolio file.

initial_capital

1000000

Starting capital in currency units.

cash_reserve_percentage

0.01

Fraction of portfolio value reserved as cash on each rebalance. Range: 0.0–0.50.

commission_cents

0.05

Per-share commission in dollars. Range: 0.0–0.10. Example: 0.01 means $0.01 per share.

File Paths and Formats#

Parameter

Example value

Description

input_market_data_directory

Input/Data

Absolute or relative path to the directory containing market data files.

input_portfolio_directory

Input/Portfolios

Absolute or relative path to the directory containing portfolio files.

backtest_results_output_directory

Output

Path where backtest results and reports are saved.

market_data_input_format

csv

Format of market data files: csv or parquet.

portfolio_input_format

csv

Format of portfolio files: csv or excel.

Column Name Mappings#

These values must exactly match the column headers in your market data files.

Parameter

Example value

Purpose

commission_price_column

vwap

Column used to calculate the share count for commission fees (typically unadjusted VWAP).

trade_execution_price_column

vwap_adjusted

Column used as the trade execution price for buying/selling shares.

mark_to_market_price_column

close_adjusted

Column used for daily portfolio valuation between rebalancing dates.

date_column

date

Column containing trading dates.

System Settings#

Parameter

Example value

Description

logger_level

error

Logging verbosity. Valid values: debug, info, warning, error, critical.

Complete Example#

After editing, your Excel file (column A | column B) should look like this:

portfolio_name                     | my_portfolio
benchmark_file_name                | SPY
start_date                         | 2020-01-02
end_date                           | 2024-12-31
initial_capital                    | 100000
cash_reserve_percentage            | 0.05
commission_cents                   | 0.01
input_market_data_directory        | Input/Data
input_portfolio_directory          | Input/Portfolios
backtest_results_output_directory  | Output
market_data_input_format           | csv
portfolio_input_format             | csv
commission_price_column            | vwap
trade_execution_price_column       | vwap_adjusted
mark_to_market_price_column        | close_adjusted
date_column                        | date
logger_level                       | info

Programmatic Configuration#

When using BatchConfigParser.parse_dict() the dict keys follow the same parameter names, with column mappings prefixed by user_column_:

{
    "global_defaults": {
        "start_date": "2020-01-02",
        "end_date": "2024-12-31",
        "commission_cents": 0.01,
        "cash_reserve_percentage": 0.05,
        "user_column_commission_price": "vwap",
        "user_column_trade_execution_price": "vwap_adjusted",
        "user_column_mark_to_market_price": "close_adjusted",
        "user_column_date": "date",
        ...
    }
}

API Reference#

The following classes back the configuration system. Their docstrings are the authoritative reference for all parameters and validation rules.

class Configuration(initial_capital: Scalar | int | float | Decimal, start_date: date | Literal['auto'], end_date: date | Literal['auto'], cash_reserve_percentage: Scalar | float | Decimal, commission_cents: Scalar | float | Decimal, market_data_input_format: str, portfolio_name: str, portfolio_input_format: str, benchmark_file_name: str, input_market_data_directory: str, input_portfolio_directory: str, backtest_results_output_directory: str, user_column_commission_price: str, user_column_trade_execution_price: str, user_column_mark_to_market_price: str, user_column_date: str)

Bases: object

Central configuration entity for the backtest engine.

Variables:
  • initial_capital (pa.Scalar | int | float | decimal.Decimal) – Starting capital for the backtest. Converted to PyArrow decimal128 during post-init validation.

  • start_date (DateConfig) – Backtest start date as datetime.date or "auto" to derive from portfolio data.

  • end_date (DateConfig) – Backtest end date as datetime.date or "auto".

  • cash_reserve_percentage (pa.Scalar | float | decimal.Decimal) – Fraction of capital held as cash (0.0 to 0.5). Converted to PyArrow decimal128 during post-init validation.

  • commission_cents (pa.Scalar | float | decimal.Decimal) – Per-share commission in cents (0.0 to 0.1). Converted to PyArrow decimal128 during post-init validation.

  • market_data_input_format (str) – Market data file format (e.g. "csv", "parquet").

  • portfolio_name (str) – Name of the portfolio file (without extension).

  • portfolio_input_format (str) – Portfolio file format (e.g. "csv", "excel").

  • benchmark_file_name (str) – Benchmark ticker symbol (e.g. "SPY").

  • input_market_data_directory (str) – Path to the directory containing market data files.

  • input_portfolio_directory (str) – Path to the directory containing portfolio files.

  • backtest_results_output_directory (str) – Path to the directory for backtest output.

  • user_column_commission_price (str) – User’s CSV/Parquet column name for the commission price (typically unadjusted VWAP).

  • user_column_trade_execution_price (str) – User’s CSV/Parquet column name for the trade execution price (typically split/dividend-adjusted VWAP).

  • user_column_mark_to_market_price (str) – User’s CSV/Parquet column name for the mark-to-market price (typically split/dividend-adjusted close).

  • user_column_date (str) – User’s CSV/Parquet column name for date.

Notes

User column names are stored as explicit attributes matching StandardField. These map directly to StandardField enum values.

Both start_date and end_date support two modes:

  • Explicit date: A datetime.date object specifying the exact date.

  • Auto mode: The string "auto" to derive dates from portfolio data.

When "auto" is specified, dates are resolved during the data pipeline execution based on the first and last rebalancing dates in the portfolio.

backtest_results_output_directory: str
benchmark_file_name: str
cash_reserve_percentage: Scalar | float | Decimal
commission_cents: Scalar | float | Decimal
end_date: date | Literal['auto']
get_numeric_user_columns() list[str]

Get user column names for numeric fields (excludes date).

Returns:

User column names for numeric fields (commission price, trade execution price, mark-to-market price).

Return type:

list[str]

get_user_column(standard_field: StandardField) str

Get the user’s column name for a given StandardField.

Parameters:

standard_field (StandardField) – The StandardField enum member to look up.

Returns:

The user’s column name string.

Return type:

str

Raises:

ConfigurationError – If standard_field is not a recognised mapping.

get_user_columns_dict() dict[str, str]

Get mapping from standard field names to user column names.

Returns:

Dictionary mapping StandardField.value to user column name.

Return type:

dict[str, str]

get_user_columns_tuple() tuple[str, ...]

Get all user column names as a tuple, ordered by STANDARD_FIELDS_ORDER.

Returns:

User column names in standard field order.

Return type:

tuple[str, …]

has_auto_dates() bool

Check if either start_date or end_date is set to “auto”.

Returns:

True if at least one date is configured as “auto”, False if both dates are explicit datetime.date values.

Return type:

bool

Examples

>>> config = Configuration(..., start_date="auto", end_date=date(2024, 12, 31))
>>> config.has_auto_dates()
True
>>> config = Configuration(..., start_date=date(2024, 1, 1), end_date=date(2024, 12, 31))
>>> config.has_auto_dates()
False
initial_capital: Scalar | int | float | Decimal
input_market_data_directory: str
input_portfolio_directory: str
is_end_date_auto() bool

Check if end_date is set to “auto”.

is_start_date_auto() bool

Check if start_date is set to “auto”.

market_data_input_format: str
portfolio_input_format: str
portfolio_name: str
start_date: date | Literal['auto']
user_column_commission_price: str
user_column_date: str
user_column_mark_to_market_price: str
user_column_trade_execution_price: str
with_overrides(*, commission_cents: float | None = None, cash_reserve_percentage: float | None = None, start_date: date | Literal['auto'] | None = None, end_date: date | Literal['auto'] | None = None, initial_capital: int | float | Decimal | None = None) Configuration

Create a new Configuration with specified field overrides.

This method provides a clean API for creating configuration variations without directly using dataclasses.replace(). Only the specified fields are modified; all other fields retain their original values.

Parameters:
  • commission_cents (float | None, optional) – Override for commission rate per share in cents. Must be in range [0.0, 0.1].

  • cash_reserve_percentage (float | None, optional) – Override for cash reserve percentage. Must be in range [0.0, 0.5].

  • start_date (DateConfig | None, optional) – Override for backtest start date. Can be datetime.date or “auto”.

  • end_date (DateConfig | None, optional) – Override for backtest end date. Can be datetime.date or “auto”.

  • initial_capital (int | float | Decimal | None, optional) – Override for initial capital amount.

Returns:

New Configuration instance with the specified overrides applied.

Return type:

Configuration

Raises:

ConfigurationError – If any override value fails validation.

Examples

Create a commission variation:

>>> config_low_comm = base_config.with_overrides(commission_cents=0.01)

Create a date range variation:

>>> config_2022 = base_config.with_overrides(
...     start_date=datetime.date(2022, 1, 1),
...     end_date=datetime.date(2022, 12, 31),
... )

Combine multiple overrides:

>>> config_var = base_config.with_overrides(
...     commission_cents=0.02,
...     cash_reserve_percentage=0.10,
... )

Notes

This method is designed for use with BacktestVariationRunner to efficiently create multiple configuration variations from a single base configuration. The returned Configuration undergoes full validation through __post_init__.

class ExcelConfigurator(file_path: str, logger_format: str = '[%(levelname)s] %(message)s')

Bases: ConfiguratorInterface

Excel-based configuration loader.

Reads configuration from an Excel file with a ‘General’ sheet containing all configuration parameters including user’s CSV column name mappings.

get_configuration() Configuration

Return the loaded Configuration entity.

Return type:

The Configuration instance

get_dashboard_port() int

Return the dashboard port parsed from the Excel configuration.

Returns:

A valid port number (1-9999).

Return type:

int

get_logger_level() int

Return the logger level parsed from the Excel configuration.

Returns:

A logging level constant (e.g. logging.INFO).

Return type:

int

class BatchConfigParser

Bases: object

Static parser for batch backtest configuration.

All methods are static/classmethod — no instance state needed.

static expand_portfolio_directory(directory: str, portfolio_input_format: str = 'csv', existing_names: set[str] | None = None) list[PortfolioDefinition]

Scan a directory for portfolio files and create PortfolioDefinitions.

Auto-discovers all portfolio files in the given directory. The portfolio name is derived from the filename (without extension). Files whose stem matches an already-defined portfolio name are skipped to avoid duplicates.

Parameters:
  • directory (str) – Path to the directory containing portfolio files.

  • portfolio_input_format (str) – File format to scan for: “csv” or “excel”.

  • existing_names (set[str] | None) – Portfolio names already defined. Files matching these names are skipped.

Returns:

One PortfolioDefinition per discovered file.

Return type:

list[PortfolioDefinition]

static expand_variations(portfolio_def: PortfolioDefinition, sweeps: list[ParametricSweep]) list[VariationDict]

Expand per-portfolio variations and applicable parametric sweeps.

Combines the portfolio’s own variations list with any parametric sweeps that apply to this portfolio.

Parameters:
  • portfolio_def (PortfolioDefinition) – Portfolio definition with optional variations.

  • sweeps (list[ParametricSweep]) – Global parametric sweeps.

Returns:

List of variation dicts, each with “name” and override fields.

Return type:

list[VariationDict]

static normalize_inline_weights(inline_weights: dict[str, dict[str, float]] | dict[str, float], start_date: str | date | None) dict[str, dict[str, float]]

Normalize inline weights to dated format.

If weights are flat ({"AAPL": 0.5, "MSFT": 0.5}), converts to dated format using the provided start_date as the single date key.

Parameters:
  • inline_weights (dict) – Either flat or dated weight dictionary.

  • start_date (str | datetime.date | None) – Start date to use for flat weights.

Returns:

Dated weights: {"YYYY-MM-DD": {"TICKER": weight, ...}}.

Return type:

dict[str, dict[str, float]]

Raises:

BatchConfigError – If flat weights are provided but no start_date is available.

static parse_dict(raw: dict[str, YamlValue]) BatchConfig

Parse a raw dictionary into a BatchConfig.

Parameters:

raw (dict) – Dictionary with batch configuration keys.

Returns:

Parsed batch configuration.

Return type:

BatchConfig

Raises:

BatchConfigError – If required keys are missing or structure is invalid.

static parse_file(yaml_path: str | Path) BatchConfig

Parse a YAML file into a BatchConfig.

Parameters:

yaml_path (str | Path) – Path to the YAML configuration file.

Returns:

Validated batch configuration object.

Return type:

BatchConfig

Raises:

BatchConfigError – If the file cannot be read or contains invalid YAML.

static resolve_configuration(portfolio_def: PortfolioDefinition, defaults: GlobalDefaults, templates: dict[str, PortfolioTemplate]) Configuration

Build a Configuration from global defaults + template + portfolio overrides.

Merge order (later takes precedence): 1. Global defaults 2. Template overrides (if portfolio references a template) 3. Portfolio-level overrides

Parameters:
  • portfolio_def (PortfolioDefinition) – The portfolio definition to build a config for.

  • defaults (GlobalDefaults) – Global default values.

  • templates (dict[str, PortfolioTemplate]) – Available templates.

Returns:

Fully resolved Configuration entity.

Return type:

Configuration

Raises:

BatchConfigError – If required fields are missing after merging.

static resolve_template_weights(portfolio_def: PortfolioDefinition, templates: dict[str, PortfolioTemplate]) dict[str, dict[str, float]] | None

Resolve portfolio weights from template + weight_overrides.

Returns None if the portfolio doesn’t use a template or if the template has no tickers (file-based portfolio).

Parameters:
  • portfolio_def (PortfolioDefinition) – Portfolio definition.

  • templates (dict[str, PortfolioTemplate]) – Available templates.

Returns:

Dated weights dict ready for PortfolioEntity.from_dict(), or None if not template-based.

Return type:

dict[str, dict[str, float]] | None