Core (wraquant.core)

Foundation infrastructure: configuration management, type definitions, custom exceptions, structured logging, decorators, and result dataclasses.

Quick Example

import wraquant as wq

# Configuration
cfg = wq.get_config()
print(f"Backend: {cfg.backend}")

# Type aliases for consistent function signatures
from wraquant.core.types import PriceSeries, ReturnSeries, OHLCVFrame

# Exceptions
from wraquant.core.exceptions import WQError, ValidationError

# Result dataclasses
from wraquant.core.results import GARCHResult, BacktestResult

API Reference

Core utilities: configuration, types, exceptions, logging, and decorators.

This module provides the foundational infrastructure that every other wraquant module depends on. It defines the configuration system, the type coercion layer, canonical exception hierarchy, reusable decorators, and structured result dataclasses.

Key components:

  • WQConfig / get_config – Global configuration singleton controlling the compute backend (pandas, polars, torch), default frequency, and logging verbosity.

  • coerce_series / coerce_array / coerce_returns / coerce_dataframe – Coerce-first type system that normalizes heterogeneous inputs (lists, numpy arrays, polars Series) into pandas types before computation.

  • WQError and subclasses (DataFetchError, ValidationError, ConfigError, OptimizationError) – Structured exception hierarchy for clear error handling across all modules.

  • @requires_extra – Decorator that gates functions behind optional dependency groups, raising MissingDependencyError with install instructions when the dependency is absent.

  • @cache_result / @validate_input – Utility decorators for memoization and input validation.

  • GARCHResult / BacktestResult / ForecastResult – Typed result dataclasses returned by modeling functions for consistent downstream consumption.

  • Frequency / AssetClass / Currency / ReturnType and other enums – Canonical enumerations used as parameters throughout the library.

Example

>>> from wraquant.core import get_config, coerce_series
>>> cfg = get_config()
>>> cfg.backend
<Backend.PANDAS: 'pandas'>
>>> import numpy as np
>>> s = coerce_series(np.array([1.0, 2.0, 3.0]), name="prices")

Use wraquant.core when you need to configure global settings, coerce raw inputs into standard types, or handle wraquant-specific exceptions. Most users interact with this module indirectly through higher-level modules like wraquant.stats or wraquant.risk.

coerce_array(data, name='data')[source]

Coerce any array-like input to a 1D float64 numpy array.

Accepts: pd.Series, pd.DataFrame (first column), np.ndarray, torch.Tensor, list, tuple, scalar.

Parameters:
  • data (Any) – Input data in any supported format.

  • name (str, default: 'data') – Name for error messages.

Return type:

ndarray[tuple[Any, ...], dtype[floating]]

Returns:

1D float64 numpy array.

Raises:

TypeError – If data cannot be converted.

Example

>>> import numpy as np
>>> from wraquant.core._coerce import coerce_array
>>> coerce_array([1.0, 2.0, 3.0])
array([1., 2., 3.])
>>> import pandas as pd
>>> coerce_array(pd.Series([10, 20, 30]))
array([10., 20., 30.])
coerce_series(data, name='data')[source]

Coerce any array-like input to a pd.Series.

Preserves index if input is already a pd.Series. If the input is a PriceSeries or ReturnSeries (from wraquant.frame), returns it directly to preserve financial metadata (frequency, currency, return_type).

Parameters:
  • data (Any) – Input data.

  • name (str, default: 'data') – Name for the resulting Series.

Return type:

Series

Returns:

pd.Series with float64 dtype.

Example

>>> import numpy as np
>>> from wraquant.core._coerce import coerce_series
>>> s = coerce_series([1.0, 2.0, 3.0], name="prices")
>>> s.name
'prices'
>>> len(s)
3
coerce_returns(data, is_prices=None, name='returns')[source]

Coerce input to return series.

Auto-detects whether input is prices or returns based on: - If all values > 0 and mean > 0.5: likely prices -> compute pct_change - Otherwise: likely returns -> pass through

Parameters:
  • data (Any) – Price series, return series, or any array-like.

  • is_prices (bool | None, default: None) – Force interpretation. None = auto-detect.

  • name (str, default: 'returns') – Name for error messages.

Return type:

ndarray[tuple[Any, ...], dtype[floating]]

Returns:

1D float64 array of returns.

Example

>>> import numpy as np
>>> from wraquant.core._coerce import coerce_returns
>>> prices = [100, 102, 101, 103]
>>> returns = coerce_returns(prices, is_prices=True)
>>> len(returns)
3
coerce_dataframe(data, name='data')[source]

Coerce input to pd.DataFrame.

Parameters:
  • data (Any) – DataFrame, dict, ndarray, or Series.

  • name (str, default: 'data') – Name for error messages.

Return type:

DataFrame

Returns:

pd.DataFrame with float64 dtypes.

Raises:

TypeError – If data cannot be converted to a DataFrame.

Example

>>> import numpy as np
>>> from wraquant.core._coerce import coerce_dataframe
>>> df = coerce_dataframe({"a": [1, 2], "b": [3, 4]})
>>> df.shape
(2, 2)
class WQConfig[source]

Bases: BaseSettings

Global wraquant configuration.

Settings can be overridden via environment variables prefixed with WQ_.

Example

>>> import wraquant as wq
>>> cfg = wq.get_config()
>>> cfg.backend
<Backend.PANDAS: 'pandas'>
>>> cfg.backend = Backend.POLARS
Parameters:
model_config: ClassVar[dict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_exit_on_error': True, 'cli_flag_prefix_char': '-', 'cli_hide_none_type': False, 'cli_ignore_unknown_args': False, 'cli_implicit_flags': False, 'cli_kebab_case': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_shortcuts': None, 'cli_use_class_docs_for_groups': False, 'enable_decoding': True, 'env_file': '.env', 'env_file_encoding': 'utf-8', 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_nested_max_split': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': 'WQ_', 'env_prefix_target': 'variable', 'extra': 'ignore', 'json_file': None, 'json_file_encoding': None, 'nested_model_default_partial_update': False, 'protected_namespaces': ('model_validate', 'model_dump', 'settings_customise_sources'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_config_section': None, 'yaml_file': None, 'yaml_file_encoding': None}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

backend: Backend
cache_enabled: bool
cache_dir: Path
cache_ttl_seconds: int
float_precision: int
log_level: str
max_retries: int
risk_free_rate: float
trading_days_per_year: int
base_currency: str
get_config()[source]

Get the global wraquant configuration singleton.

Return type:

WQConfig

Returns:

The global WQConfig instance.

Example

>>> from wraquant.core import get_config
>>> cfg = get_config()
>>> cfg.backend
<Backend.PANDAS: 'pandas'>
exception WQError[source]

Bases: Exception

Base exception for all wraquant errors.

exception MissingDependencyError[source]

Bases: WQError, ImportError

Raised when an optional dependency is not installed.

Parameters:
  • package (str) – Name of the missing package.

  • extra_group (str | None, default: None) – The PDM extra group that provides it.

__init__(package, extra_group=None)[source]
Parameters:
  • package (str)

  • extra_group (str | None, default: None)

Return type:

None

exception DataFetchError[source]

Bases: WQError

Raised when data fetching from a provider fails.

Parameters:
  • provider (str)

  • symbol (str)

  • reason (str, default: '')

__init__(provider, symbol, reason='')[source]
Parameters:
  • provider (str)

  • symbol (str)

  • reason (str, default: '')

Return type:

None

exception ValidationError[source]

Bases: WQError, ValueError

Raised when input data fails validation.

exception ConfigError[source]

Bases: WQError

Raised when there is a configuration error.

exception OptimizationError[source]

Bases: WQError

Raised when an optimization problem fails to solve.

Parameters:
  • solver (str)

  • reason (str, default: '')

__init__(solver, reason='')[source]
Parameters:
  • solver (str)

  • reason (str, default: '')

Return type:

None

class AssetClass[source]

Bases: StrEnum

Financial asset classes.

EQUITY = 'equity'
FIXED_INCOME = 'fixed_income'
COMMODITY = 'commodity'
FX = 'fx'
CRYPTO = 'crypto'
DERIVATIVE = 'derivative'
INDEX = 'index'
ETF = 'etf'
FUND = 'fund'
REAL_ESTATE = 'real_estate'
ALTERNATIVE = 'alternative'
__new__(value)
class Currency[source]

Bases: StrEnum

Major world currencies (ISO 4217).

USD = 'USD'
EUR = 'EUR'
GBP = 'GBP'
JPY = 'JPY'
CHF = 'CHF'
AUD = 'AUD'
CAD = 'CAD'
NZD = 'NZD'
SEK = 'SEK'
NOK = 'NOK'
DKK = 'DKK'
SGD = 'SGD'
HKD = 'HKD'
CNY = 'CNY'
CNH = 'CNH'
INR = 'INR'
KRW = 'KRW'
BRL = 'BRL'
MXN = 'MXN'
ZAR = 'ZAR'
TRY = 'TRY'
PLN = 'PLN'
CZK = 'CZK'
HUF = 'HUF'
THB = 'THB'
TWD = 'TWD'
RUB = 'RUB'
__new__(value)
class Frequency[source]

Bases: StrEnum

Time series frequency.

TICK = 'tick'
SECOND = '1s'
MINUTE = '1min'
FIVE_MIN = '5min'
FIFTEEN_MIN = '15min'
THIRTY_MIN = '30min'
HOURLY = '1h'
FOUR_HOUR = '4h'
DAILY = '1d'
WEEKLY = '1w'
MONTHLY = '1mo'
QUARTERLY = '1q'
YEARLY = '1y'
__new__(value)
class OptionType[source]

Bases: StrEnum

Option contract type.

CALL = 'call'
PUT = 'put'
__new__(value)
class OrderSide[source]

Bases: StrEnum

Trade order direction.

BUY = 'buy'
SELL = 'sell'
__new__(value)
class ReturnType[source]

Bases: StrEnum

Type of return calculation.

SIMPLE = 'simple'
LOG = 'log'
EXCESS = 'excess'
__new__(value)
requires_extra(group)[source]

Decorator that raises MissingDependencyError if an optional group is missing.

Parameters:

group (str) – The PDM optional dependency group name (e.g., ‘market-data’).

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

Returns:

Decorated function that checks for the dependency before execution.

Example

>>> @requires_extra('market-data')
... def fetch_yahoo(symbol: str) -> pd.DataFrame:
...     import yfinance
...     return yfinance.download(symbol)
cache_result(ttl=3600)[source]

Simple in-memory cache with TTL for expensive computations.

Parameters:

ttl (int, default: 3600) – Time-to-live in seconds. Defaults to 1 hour.

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

Returns:

Decorated function with caching behavior.

validate_input(func)[source]

Decorator that validates function inputs using type hints.

Currently a pass-through that documents the intent for pydantic validation integration in the future.

Parameters:

func (TypeVar(F, bound= Callable[..., Any]))

Return type:

TypeVar(F, bound= Callable[..., Any])

class GARCHResult[source]

Bases: object

Result from GARCH-family model fitting.

params

Fitted parameters dict (omega, alpha, beta, …).

conditional_volatility

Time series of conditional std dev.

standardized_residuals

Residuals / conditional vol.

aic

Akaike Information Criterion.

bic

Bayesian Information Criterion.

log_likelihood

Maximized log-likelihood.

persistence

Sum of alpha + beta parameters.

half_life

Periods for shock to decay 50%.

unconditional_variance

Long-run variance.

model

Underlying fitted model object.

model_name

Name of the GARCH model variant.

Parameters:
params: dict[str, float]
conditional_volatility: Series
standardized_residuals: ndarray
aic: float
bic: float
log_likelihood: float
persistence: float
half_life: float
unconditional_variance: float
model: Any = None
ljung_box: dict | None = None
model_name: str = ''
__getitem__(key)[source]

Support dict-like access for backward compatibility.

Parameters:

key (str)

Return type:

Any

__contains__(key)[source]

Support 'key' in result for backward compatibility.

Parameters:

key (object)

Return type:

bool

get(key, default=None)[source]

Support result.get('key') for backward compatibility.

Parameters:
  • key (str)

  • default (Any, default: None)

Return type:

Any

to_var(alpha=0.05)[source]

Compute GARCH-based Value at Risk.

Uses the fitted conditional volatility to estimate VaR via wraquant.risk.var.garch_var.

Parameters:

alpha (float, default: 0.05) – Significance level (default 0.05 = 95% VaR).

Return type:

dict

Returns:

Dict with VaR results from risk.var.garch_var.

plot()[source]

Plot conditional volatility using viz module.

Return type:

Any

Returns:

Plotly figure object.

summary()[source]

Human-readable summary of GARCH fit.

Return type:

str

Returns:

Multi-line string with key diagnostics.

__init__(params, conditional_volatility, standardized_residuals, aic, bic, log_likelihood, persistence, half_life, unconditional_variance, model=None, ljung_box=None, model_name='')
Parameters:
Return type:

None

class BacktestResult[source]

Bases: object

Result from a backtest run.

returns

Portfolio return series.

equity_curve

Cumulative equity curve (aliased as portfolio_value).

metrics

Dict of performance metrics (Sharpe, max_dd, etc.).

trades

Trade count (int) or list of trade records.

signals

Signal series used.

positions

Position weights over time (if available).

Parameters:
returns: Series
equity_curve: Series
metrics: dict[str, float]
trades: int | list[dict] = 0
signals: Series | None = None
positions: DataFrame | None = None
property portfolio_value: Series

Alias for equity_curve (backward compatibility).

__getitem__(key)[source]

Support dict-like access for backward compatibility.

Parameters:

key (str)

Return type:

Any

__contains__(key)[source]

Support 'key' in result for backward compatibility.

Parameters:

key (object)

Return type:

bool

get(key, default=None)[source]

Support result.get('key') for backward compatibility.

Parameters:
  • key (str)

  • default (Any, default: None)

Return type:

Any

property sharpe: float
property max_drawdown: float
to_tearsheet(**kwargs)[source]

Generate a comprehensive tearsheet.

Delegates to wraquant.backtest.tearsheet.comprehensive_tearsheet.

Parameters:

**kwargs (Any) – Forwarded to comprehensive_tearsheet.

Return type:

dict

Returns:

Dict with full tearsheet analysis.

plot()[source]

Plot the equity curve using viz module.

Return type:

Any

Returns:

Plotly figure object.

summary()[source]

Human-readable summary of backtest results.

Return type:

str

Returns:

Multi-line string with key performance metrics.

__init__(returns, equity_curve, metrics, trades=0, signals=None, positions=None)
Parameters:
Return type:

None

class ForecastResult[source]

Bases: object

Result from time series forecasting.

forecast

Point forecast values.

confidence_lower

Lower confidence bound.

confidence_upper

Upper confidence bound.

method

Forecasting method used.

fitted_values

In-sample fitted values.

residuals

In-sample residuals.

metrics

Fit metrics (AIC, BIC, RMSE).

Parameters:
forecast: Series | ndarray
confidence_lower: ndarray | None = None
confidence_upper: ndarray | None = None
method: str = ''
fitted_values: ndarray | None = None
residuals: ndarray | None = None
metrics: dict[str, float]
model: Any = None
__getitem__(key)[source]

Support dict-like access for backward compatibility.

Parameters:

key (str)

Return type:

Any

__contains__(key)[source]

Support 'key' in result for backward compatibility.

Parameters:

key (object)

Return type:

bool

get(key, default=None)[source]

Support result.get('key') for backward compatibility.

Parameters:
  • key (str)

  • default (Any, default: None)

Return type:

Any

plot()[source]

Plot forecast with confidence bounds using viz module.

Return type:

Any

Returns:

Plotly figure object.

summary()[source]

Human-readable summary of forecast.

Return type:

str

Returns:

Multi-line string with method and fit metrics.

__init__(forecast, confidence_lower=None, confidence_upper=None, method='', fitted_values=None, residuals=None, metrics=<factory>, model=None)
Parameters:
Return type:

None

Configuration

Global configuration for wraquant.

Uses pydantic-settings for environment variable support and validation. Configuration is a singleton accessible via get_config().

class WQConfig[source]

Bases: BaseSettings

Global wraquant configuration.

Settings can be overridden via environment variables prefixed with WQ_.

Example

>>> import wraquant as wq
>>> cfg = wq.get_config()
>>> cfg.backend
<Backend.PANDAS: 'pandas'>
>>> cfg.backend = Backend.POLARS
Parameters:
model_config: ClassVar[dict] = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_exit_on_error': True, 'cli_flag_prefix_char': '-', 'cli_hide_none_type': False, 'cli_ignore_unknown_args': False, 'cli_implicit_flags': False, 'cli_kebab_case': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_shortcuts': None, 'cli_use_class_docs_for_groups': False, 'enable_decoding': True, 'env_file': '.env', 'env_file_encoding': 'utf-8', 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_nested_max_split': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': 'WQ_', 'env_prefix_target': 'variable', 'extra': 'ignore', 'json_file': None, 'json_file_encoding': None, 'nested_model_default_partial_update': False, 'protected_namespaces': ('model_validate', 'model_dump', 'settings_customise_sources'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_config_section': None, 'yaml_file': None, 'yaml_file_encoding': None}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

backend: Backend
cache_enabled: bool
cache_dir: Path
cache_ttl_seconds: int
float_precision: int
log_level: str
max_retries: int
risk_free_rate: float
trading_days_per_year: int
base_currency: str
get_config()[source]

Get the global wraquant configuration singleton.

Return type:

WQConfig

Returns:

The global WQConfig instance.

Example

>>> from wraquant.core import get_config
>>> cfg = get_config()
>>> cfg.backend
<Backend.PANDAS: 'pandas'>
reset_config()[source]

Reset the global configuration to defaults.

Return type:

None

Types

Type definitions, enums, and type aliases for wraquant.

Provides strongly-typed enumerations for financial concepts and type aliases used throughout the package.

DateLike

Anything that can be interpreted as a date.

alias of str | date | datetime | Timestamp | datetime64

ArrayLike

Numeric array-like input accepted by most functions.

alias of ndarray[tuple[Any, …], dtype[floating]] | Series | Sequence[float] | list[float]

PriceSeries

A pandas Series of prices indexed by datetime.

Parameters:
ReturnSeries

A pandas Series of returns indexed by datetime.

Parameters:
PriceFrame

A DataFrame of prices with datetime index and asset columns.

Parameters:
ReturnFrame

A DataFrame of returns with datetime index and asset columns.

Parameters:
OHLCVFrame

A DataFrame with open/high/low/close/volume columns and datetime index.

Parameters:
WeightsArray

Portfolio weight vector.

alias of ndarray[tuple[Any, …], dtype[floating]] | Series | Sequence[float]

CovarianceMatrix

Covariance matrix (2D).

alias of ndarray[tuple[Any, …], dtype[floating]] | DataFrame

class Frequency[source]

Bases: StrEnum

Time series frequency.

TICK = 'tick'
SECOND = '1s'
MINUTE = '1min'
FIVE_MIN = '5min'
FIFTEEN_MIN = '15min'
THIRTY_MIN = '30min'
HOURLY = '1h'
FOUR_HOUR = '4h'
DAILY = '1d'
WEEKLY = '1w'
MONTHLY = '1mo'
QUARTERLY = '1q'
YEARLY = '1y'
__new__(value)
class AssetClass[source]

Bases: StrEnum

Financial asset classes.

EQUITY = 'equity'
FIXED_INCOME = 'fixed_income'
COMMODITY = 'commodity'
FX = 'fx'
CRYPTO = 'crypto'
DERIVATIVE = 'derivative'
INDEX = 'index'
ETF = 'etf'
FUND = 'fund'
REAL_ESTATE = 'real_estate'
ALTERNATIVE = 'alternative'
__new__(value)
class Currency[source]

Bases: StrEnum

Major world currencies (ISO 4217).

USD = 'USD'
EUR = 'EUR'
GBP = 'GBP'
JPY = 'JPY'
CHF = 'CHF'
AUD = 'AUD'
CAD = 'CAD'
NZD = 'NZD'
SEK = 'SEK'
NOK = 'NOK'
DKK = 'DKK'
SGD = 'SGD'
HKD = 'HKD'
CNY = 'CNY'
CNH = 'CNH'
INR = 'INR'
KRW = 'KRW'
BRL = 'BRL'
MXN = 'MXN'
ZAR = 'ZAR'
TRY = 'TRY'
PLN = 'PLN'
CZK = 'CZK'
HUF = 'HUF'
THB = 'THB'
TWD = 'TWD'
RUB = 'RUB'
__new__(value)
class ReturnType[source]

Bases: StrEnum

Type of return calculation.

SIMPLE = 'simple'
LOG = 'log'
EXCESS = 'excess'
__new__(value)
class OptionType[source]

Bases: StrEnum

Option contract type.

CALL = 'call'
PUT = 'put'
__new__(value)
class OptionStyle[source]

Bases: StrEnum

Option exercise style.

EUROPEAN = 'european'
AMERICAN = 'american'
BERMUDAN = 'bermudan'
ASIAN = 'asian'
__new__(value)
class OrderSide[source]

Bases: StrEnum

Trade order direction.

BUY = 'buy'
SELL = 'sell'
__new__(value)
class RegimeState[source]

Bases: StrEnum

Market regime states.

BULL = 'bull'
BEAR = 'bear'
SIDEWAYS = 'sideways'
HIGH_VOL = 'high_vol'
LOW_VOL = 'low_vol'
CRISIS = 'crisis'
__new__(value)
class RiskMeasure[source]

Bases: StrEnum

Risk measure types.

VAR = 'var'
CVAR = 'cvar'
VOLATILITY = 'volatility'
MAX_DRAWDOWN = 'max_drawdown'
SEMI_DEVIATION = 'semi_deviation'
ENTROPIC = 'entropic'
__new__(value)
class VolModel[source]

Bases: StrEnum

Volatility model types.

__new__(value)
GARCH = 'garch'
EGARCH = 'egarch'
GJR_GARCH = 'gjr_garch'
TARCH = 'tarch'
EWMA = 'ewma'
REALIZED = 'realized'
IMPLIED = 'implied'
HESTON = 'heston'
SABR = 'sabr'

Exceptions

Custom exception hierarchy for wraquant.

exception WQError[source]

Bases: Exception

Base exception for all wraquant errors.

exception MissingDependencyError[source]

Bases: WQError, ImportError

Raised when an optional dependency is not installed.

Parameters:
  • package (str) – Name of the missing package.

  • extra_group (str | None, default: None) – The PDM extra group that provides it.

__init__(package, extra_group=None)[source]
Parameters:
  • package (str)

  • extra_group (str | None, default: None)

Return type:

None

exception DataFetchError[source]

Bases: WQError

Raised when data fetching from a provider fails.

Parameters:
  • provider (str)

  • symbol (str)

  • reason (str, default: '')

__init__(provider, symbol, reason='')[source]
Parameters:
  • provider (str)

  • symbol (str)

  • reason (str, default: '')

Return type:

None

exception ValidationError[source]

Bases: WQError, ValueError

Raised when input data fails validation.

exception ConfigError[source]

Bases: WQError

Raised when there is a configuration error.

exception OptimizationError[source]

Bases: WQError

Raised when an optimization problem fails to solve.

Parameters:
  • solver (str)

  • reason (str, default: '')

__init__(solver, reason='')[source]
Parameters:
  • solver (str)

  • reason (str, default: '')

Return type:

None

exception BacktestError[source]

Bases: WQError

Raised when a backtesting operation fails.

exception PricingError[source]

Bases: WQError

Raised when a pricing calculation fails.

Logging

Structured logging setup for wraquant.

Uses structlog for structured logging with loguru as the output handler.

configure_logging(level='WARNING')[source]

Configure structlog for wraquant.

Parameters:

level (str, default: 'WARNING') – Log level string (DEBUG, INFO, WARNING, ERROR, CRITICAL).

Return type:

None

get_logger(name=None)[source]

Get a structlog logger instance.

Parameters:

name (str | None, default: None) – Logger name, typically __name__.

Return type:

BoundLogger

Returns:

A bound structlog logger.

Example

>>> from wraquant.core.logging import get_logger
>>> log = get_logger(__name__)
>>> log.info("fetching data", symbol="AAPL")

Decorators

Decorators for optional dependency gating, caching, and validation.

requires_extra(group)[source]

Decorator that raises MissingDependencyError if an optional group is missing.

Parameters:

group (str) – The PDM optional dependency group name (e.g., ‘market-data’).

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

Returns:

Decorated function that checks for the dependency before execution.

Example

>>> @requires_extra('market-data')
... def fetch_yahoo(symbol: str) -> pd.DataFrame:
...     import yfinance
...     return yfinance.download(symbol)
cache_result(ttl=3600)[source]

Simple in-memory cache with TTL for expensive computations.

Parameters:

ttl (int, default: 3600) – Time-to-live in seconds. Defaults to 1 hour.

Return type:

Callable[[TypeVar(F, bound= Callable[..., Any])], TypeVar(F, bound= Callable[..., Any])]

Returns:

Decorated function with caching behavior.

validate_input(func)[source]

Decorator that validates function inputs using type hints.

Currently a pass-through that documents the intent for pydantic validation integration in the future.

Parameters:

func (TypeVar(F, bound= Callable[..., Any]))

Return type:

TypeVar(F, bound= Callable[..., Any])

Results

Standardized result containers for wraquant.

Dataclasses that provide consistent, IDE-friendly access to results from GARCH fitting, backtesting, forecasting, and other operations. Each result type carries chaining methods that lazily import downstream modules, enabling composable workflows:

garch_result.to_var(alpha=0.05) # -> risk/var garch_result.plot() # -> viz backtest_result.to_tearsheet() # -> backtest/tearsheet forecast_result.plot() # -> viz

class GARCHResult[source]

Bases: object

Result from GARCH-family model fitting.

params

Fitted parameters dict (omega, alpha, beta, …).

conditional_volatility

Time series of conditional std dev.

standardized_residuals

Residuals / conditional vol.

aic

Akaike Information Criterion.

bic

Bayesian Information Criterion.

log_likelihood

Maximized log-likelihood.

persistence

Sum of alpha + beta parameters.

half_life

Periods for shock to decay 50%.

unconditional_variance

Long-run variance.

model

Underlying fitted model object.

model_name

Name of the GARCH model variant.

Parameters:
params: dict[str, float]
conditional_volatility: Series
standardized_residuals: ndarray
aic: float
bic: float
log_likelihood: float
persistence: float
half_life: float
unconditional_variance: float
model: Any = None
ljung_box: dict | None = None
model_name: str = ''
__getitem__(key)[source]

Support dict-like access for backward compatibility.

Parameters:

key (str)

Return type:

Any

__contains__(key)[source]

Support 'key' in result for backward compatibility.

Parameters:

key (object)

Return type:

bool

get(key, default=None)[source]

Support result.get('key') for backward compatibility.

Parameters:
  • key (str)

  • default (Any, default: None)

Return type:

Any

to_var(alpha=0.05)[source]

Compute GARCH-based Value at Risk.

Uses the fitted conditional volatility to estimate VaR via wraquant.risk.var.garch_var.

Parameters:

alpha (float, default: 0.05) – Significance level (default 0.05 = 95% VaR).

Return type:

dict

Returns:

Dict with VaR results from risk.var.garch_var.

plot()[source]

Plot conditional volatility using viz module.

Return type:

Any

Returns:

Plotly figure object.

summary()[source]

Human-readable summary of GARCH fit.

Return type:

str

Returns:

Multi-line string with key diagnostics.

__init__(params, conditional_volatility, standardized_residuals, aic, bic, log_likelihood, persistence, half_life, unconditional_variance, model=None, ljung_box=None, model_name='')
Parameters:
Return type:

None

class BacktestResult[source]

Bases: object

Result from a backtest run.

returns

Portfolio return series.

equity_curve

Cumulative equity curve (aliased as portfolio_value).

metrics

Dict of performance metrics (Sharpe, max_dd, etc.).

trades

Trade count (int) or list of trade records.

signals

Signal series used.

positions

Position weights over time (if available).

Parameters:
returns: Series
equity_curve: Series
metrics: dict[str, float]
trades: int | list[dict] = 0
signals: Series | None = None
positions: DataFrame | None = None
property portfolio_value: Series

Alias for equity_curve (backward compatibility).

__getitem__(key)[source]

Support dict-like access for backward compatibility.

Parameters:

key (str)

Return type:

Any

__contains__(key)[source]

Support 'key' in result for backward compatibility.

Parameters:

key (object)

Return type:

bool

get(key, default=None)[source]

Support result.get('key') for backward compatibility.

Parameters:
  • key (str)

  • default (Any, default: None)

Return type:

Any

property sharpe: float
property max_drawdown: float
to_tearsheet(**kwargs)[source]

Generate a comprehensive tearsheet.

Delegates to wraquant.backtest.tearsheet.comprehensive_tearsheet.

Parameters:

**kwargs (Any) – Forwarded to comprehensive_tearsheet.

Return type:

dict

Returns:

Dict with full tearsheet analysis.

plot()[source]

Plot the equity curve using viz module.

Return type:

Any

Returns:

Plotly figure object.

summary()[source]

Human-readable summary of backtest results.

Return type:

str

Returns:

Multi-line string with key performance metrics.

__init__(returns, equity_curve, metrics, trades=0, signals=None, positions=None)
Parameters:
Return type:

None

class ForecastResult[source]

Bases: object

Result from time series forecasting.

forecast

Point forecast values.

confidence_lower

Lower confidence bound.

confidence_upper

Upper confidence bound.

method

Forecasting method used.

fitted_values

In-sample fitted values.

residuals

In-sample residuals.

metrics

Fit metrics (AIC, BIC, RMSE).

Parameters:
forecast: Series | ndarray
confidence_lower: ndarray | None = None
confidence_upper: ndarray | None = None
method: str = ''
fitted_values: ndarray | None = None
residuals: ndarray | None = None
metrics: dict[str, float]
model: Any = None
__getitem__(key)[source]

Support dict-like access for backward compatibility.

Parameters:

key (str)

Return type:

Any

__contains__(key)[source]

Support 'key' in result for backward compatibility.

Parameters:

key (object)

Return type:

bool

get(key, default=None)[source]

Support result.get('key') for backward compatibility.

Parameters:
  • key (str)

  • default (Any, default: None)

Return type:

Any

plot()[source]

Plot forecast with confidence bounds using viz module.

Return type:

Any

Returns:

Plotly figure object.

summary()[source]

Human-readable summary of forecast.

Return type:

str

Returns:

Multi-line string with method and fit metrics.

__init__(forecast, confidence_lower=None, confidence_upper=None, method='', fitted_values=None, residuals=None, metrics=<factory>, model=None)
Parameters:
Return type:

None