192 lines
6.9 KiB
Python
192 lines
6.9 KiB
Python
"""Configuration objects for strategy and Thai market assumptions."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import asdict, dataclass, field
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
|
|
DEFAULT_FOCUS_WEIGHTS = {
|
|
"rs": 25, "market_alignment": 20, "structure": 15, "higher_low": 10,
|
|
"atr_distance": 10, "volume_behavior": 5, "tightness": 5,
|
|
"sector_strength": 5, "weekly": 5,
|
|
}
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ThaiMarketRules:
|
|
default_board_lot: int = 100
|
|
high_price_board_lot: int = 50
|
|
high_price_threshold: float = 500.0
|
|
high_price_months: int = 6
|
|
minimum_quantity: int = 1
|
|
etf_tick: float = 0.01
|
|
|
|
def tick_size(self, price: float, *, etf: bool = False) -> float:
|
|
if etf:
|
|
return self.etf_tick
|
|
if price < 2:
|
|
return 0.01
|
|
if price < 5:
|
|
return 0.02
|
|
if price < 10:
|
|
return 0.05
|
|
if price < 25:
|
|
return 0.10
|
|
if price < 100:
|
|
return 0.25
|
|
if price < 200:
|
|
return 0.50
|
|
if price < 400:
|
|
return 1.00
|
|
return 2.00
|
|
|
|
def board_lot(self, price: float, *, high_price_eligible: bool = False) -> int:
|
|
return self.high_price_board_lot if high_price_eligible and price >= self.high_price_threshold else self.default_board_lot
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class TradingCosts:
|
|
"""Research cost assumptions; rates are fractions of traded notional."""
|
|
|
|
commission_rate: float = 0.0015
|
|
fees_rate: float = 0.0
|
|
sell_tax_rate: float = 0.0
|
|
slippage_bps: float = 5.0
|
|
|
|
def __post_init__(self) -> None:
|
|
for name in ("commission_rate", "fees_rate", "sell_tax_rate", "slippage_bps"):
|
|
if getattr(self, name) < 0:
|
|
raise ValueError(f"{name} must be non-negative")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class RegimeHeat:
|
|
correction: float = 0.0
|
|
repair: float = 0.005
|
|
early_uptrend: float = 0.01
|
|
confirmed_uptrend: float = 0.02
|
|
uptrend_pullback: float = 0.02
|
|
overbought: float = 0.0
|
|
breakdown: float = 0.0
|
|
|
|
def for_regime(self, regime: str) -> float:
|
|
return {
|
|
"CORRECTION": self.correction, "REPAIR": self.repair,
|
|
"EARLY_UPTREND": self.early_uptrend, "CONFIRMED_UPTREND": self.confirmed_uptrend,
|
|
"UPTREND_PULLBACK": self.uptrend_pullback, "OVERBOUGHT": self.overbought,
|
|
"BREAKDOWN": self.breakdown,
|
|
}.get(regime.upper(), 0.0)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class StrategyConfig:
|
|
initial_equity: float = 1_000_000.0
|
|
weakness_risk_pct: float = 0.0025
|
|
confirmation_risk_pct: float = 0.005
|
|
max_position_pct: float = 0.20
|
|
max_extension_atr: float = 1.0
|
|
min_mco_z_for_entry: float = -2.0
|
|
min_rs_percentile: float = 70.0
|
|
min_value_turnover_thb: float = 20_000_000.0
|
|
min_price: float = 2.0
|
|
partial_r_multiple: float = 2.0
|
|
partial_fraction: float = 1 / 3
|
|
max_loss_pct: float = 0.08
|
|
exit_mode: str = "close_below_ema21_low"
|
|
enable_rs: bool = True
|
|
enable_market_regime: bool = True
|
|
enable_mco: bool = True
|
|
enable_mcsi: bool = True
|
|
enable_higher_low: bool = True
|
|
enable_weekly: bool = True
|
|
enable_atr_filter: bool = True
|
|
require_market_support: bool = True
|
|
volume_pullback_ratio: float = 1.0
|
|
tightness_lookback: int = 10
|
|
base_breakout_window: int = 20
|
|
heat: RegimeHeat = field(default_factory=RegimeHeat)
|
|
|
|
def __post_init__(self) -> None:
|
|
if self.initial_equity <= 0 or self.max_position_pct <= 0:
|
|
raise ValueError("equity and position cap must be positive")
|
|
if not 0 < self.partial_fraction < 1:
|
|
raise ValueError("partial_fraction must be between 0 and 1")
|
|
if self.base_breakout_window < 1:
|
|
raise ValueError("base_breakout_window must be positive")
|
|
if self.exit_mode not in {"close_below_ema21_low", "break_failed_reclaim"}:
|
|
raise ValueError("unsupported exit_mode")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class RelativeStrengthWeights:
|
|
one_month: float = 0.20
|
|
three_month: float = 0.35
|
|
twelve_month: float = 0.30
|
|
high_52w: float = 0.15
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ResearchSettings:
|
|
slope_lookback: int = 5
|
|
atr_period: int = 14
|
|
adr_period: int = 20
|
|
mco_short_span: int = 19
|
|
mco_long_span: int = 39
|
|
mco_z_window: int = 252
|
|
pivot_left_bars: int = 3
|
|
pivot_right_bars: int = 3
|
|
pullback_volume_window: int = 5
|
|
tightness_window: int = 10
|
|
overbought_extension_atr: float = 1.5
|
|
mco_repair_sigma: float = 1.0
|
|
|
|
def __post_init__(self) -> None:
|
|
for name in ("slope_lookback", "atr_period", "adr_period", "mco_short_span",
|
|
"mco_long_span", "mco_z_window", "pivot_left_bars", "pivot_right_bars",
|
|
"pullback_volume_window", "tightness_window"):
|
|
if getattr(self, name) < 1:
|
|
raise ValueError(f"{name} must be positive")
|
|
if self.overbought_extension_atr <= 0 or self.mco_repair_sigma < 0:
|
|
raise ValueError("regime thresholds must be non-negative and extension must be positive")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class AppConfig:
|
|
strategy: StrategyConfig = field(default_factory=StrategyConfig)
|
|
market_rules: ThaiMarketRules = field(default_factory=ThaiMarketRules)
|
|
costs: TradingCosts = field(default_factory=TradingCosts)
|
|
rs_weights: RelativeStrengthWeights = field(default_factory=RelativeStrengthWeights)
|
|
research: ResearchSettings = field(default_factory=ResearchSettings)
|
|
focus_weights: dict[str, float] = field(default_factory=lambda: dict(DEFAULT_FOCUS_WEIGHTS))
|
|
|
|
def __post_init__(self) -> None:
|
|
unknown = set(self.focus_weights) - set(DEFAULT_FOCUS_WEIGHTS)
|
|
if unknown:
|
|
raise ValueError(f"unknown focus weight keys: {', '.join(sorted(unknown))}")
|
|
if not self.focus_weights or any(not math.isfinite(value) or value < 0 for value in self.focus_weights.values()):
|
|
raise ValueError("focus weights must be non-negative with at least one enabled component")
|
|
if sum(self.focus_weights.values()) <= 0:
|
|
raise ValueError("focus weights must sum to a positive value")
|
|
|
|
@classmethod
|
|
def load(cls, path: str | Path | None = None) -> "AppConfig":
|
|
if path is None:
|
|
return cls()
|
|
raw: dict[str, Any] = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
strategy_data = raw.get("strategy", {})
|
|
if "heat" in strategy_data:
|
|
strategy_data["heat"] = RegimeHeat(**strategy_data["heat"])
|
|
return cls(strategy=StrategyConfig(**strategy_data),
|
|
market_rules=ThaiMarketRules(**raw.get("market_rules", {})),
|
|
costs=TradingCosts(**raw.get("costs", {})),
|
|
rs_weights=RelativeStrengthWeights(**raw.get("rs_weights", {})),
|
|
research=ResearchSettings(**raw.get("research", {})),
|
|
focus_weights={**DEFAULT_FOCUS_WEIGHTS, **raw.get("focus_weights", {})})
|
|
|
|
def to_dict(self) -> dict[str, Any]:
|
|
return asdict(self)
|