Skip to content

Pydantic Configuration Examples

Using the StrategyConfig Class

The StrategyConfig Pydantic model provides type-safe configuration with automatic validation.

Basic Usage

from trade_calc import StrategyConfig, compute_recommendation

# Load from default location (configs/strategy_config.toml)
config = StrategyConfig.from_toml()

# Use with strategy functions
result = compute_recommendation("AAPL", config)

Loading from Custom Path

from trade_calc.config import StrategyConfig

# Load from custom path
config = StrategyConfig.from_toml("/path/to/custom_config.toml")

Creating Config Programmatically

from trade_calc.config import (
    StrategyConfig,
    ThresholdsConfig,
    ExpirationConfig,
    VolatilityConfig,
    ScoringConfig,
)

# Create custom config in code
config = StrategyConfig(
    thresholds=ThresholdsConfig(
        min_avg_volume=2000000,
        min_iv_rv_ratio=1.5,
        max_ts_slope=-0.005,
    ),
    expiration=ExpirationConfig(
        min_days_to_expiration=60,
    ),
    volatility=VolatilityConfig(
        rolling_window=45,
        trading_periods_per_year=252,
        price_history_period="6mo",
    ),
    scoring=ScoringConfig(
        volume_weight=3.0,
        volume_max_points=25.0,
        iv_rv_weight=25.0,
        ts_slope_weight=1500.0,
        expected_move_weight=2.5,
    ),
)

# Use the custom config
result = compute_recommendation("TSLA", config)

Partial Configuration Override

from trade_calc import StrategyConfig

# Load default config
config = StrategyConfig.from_toml()

# Override specific values
config.thresholds.min_avg_volume = 3000000
config.thresholds.min_iv_rv_ratio = 1.4

# Use modified config
result = compute_recommendation("NVDA", config)

Validation Features

The Pydantic model automatically validates:

  • Positive values: Volume, ratios, weights must be > 0
  • Negative slope: Term structure slope must be < 0
  • Valid periods: Price history period must end with 'd', 'mo', or 'y'
from trade_calc.config import ThresholdsConfig
from pydantic import ValidationError

try:
    # This will raise ValidationError - negative volume
    config = ThresholdsConfig(min_avg_volume=-1000)
except ValidationError as e:
    print(e)
    # Input should be greater than 0

try:
    # This will raise ValidationError - positive slope
    config = ThresholdsConfig(max_ts_slope=0.001)
except ValidationError as e:
    print(e)
    # Input should be less than 0.0

Converting to Dictionary

from trade_calc import StrategyConfig

config = StrategyConfig.from_toml()

# Convert to nested dict
config_dict = config.to_dict()
print(config_dict)
# {
#     'thresholds': {'min_avg_volume': 1500000, ...},
#     'expiration': {'min_days_to_expiration': 45},
#     ...
# }

# Access individual sections
thresholds = config.thresholds.model_dump()

Type Safety

The Pydantic model provides full type hints and IDE autocomplete:

from trade_calc import StrategyConfig

config = StrategyConfig.from_toml()

# IDE will autocomplete and type-check these
volume: int = config.thresholds.min_avg_volume
ratio: float = config.thresholds.min_iv_rv_ratio
window: int = config.volatility.rolling_window

Benefits Over Dict-Based Config

  1. Type Safety: Automatic type checking and conversion
  2. Validation: Built-in validation rules (positive values, valid formats)
  3. IDE Support: Full autocomplete and type hints
  4. Documentation: Field descriptions in the model
  5. Error Messages: Clear validation error messages
  6. Immutability Options: Can make config immutable if needed

Migrating from Dict Config

If you have code using the old dict-based config:

# Old way (dict)
min_volume = config["thresholds"]["min_avg_volume"]

# New way (Pydantic)
min_volume = config.thresholds.min_avg_volume

The change is minimal and provides much better safety!