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checks.
|
| 3 |
+
No LLM. Pure Python. Catches 100% of mechanical failures.
|
| 4 |
+
Mandatory and unbypassable β no agent can override this gate.
|
| 5 |
+
"""
|
| 6 |
+
import re
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from ..schemas import LintResult
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# Load operators catalog
|
| 12 |
+
def _load_operators(path: Path = Path("data/operators.csv")) -> set[str]:
|
| 13 |
+
"""Load valid operator names from operators.csv."""
|
| 14 |
+
if not path.exists():
|
| 15 |
+
# Fallback: common BRAIN operators
|
| 16 |
+
return {
|
| 17 |
+
"rank", "zscore", "group_rank", "group_zscore", "quantile",
|
| 18 |
+
"ts_rank", "ts_zscore", "ts_mean", "ts_std", "ts_sum",
|
| 19 |
+
"ts_min", "ts_max", "ts_argmax", "ts_argmin", "ts_skewness",
|
| 20 |
+
"ts_kurtosis", "ts_covariance", "ts_correlation", "ts_regression",
|
| 21 |
+
"ts_decay_linear", "ts_decay_exp_window", "ts_delta", "ts_delay",
|
| 22 |
+
"ts_product", "ts_moment", "ts_entropy", "ts_av_diff",
|
| 23 |
+
"ts_hump", "ts_scale", "ts_step",
|
| 24 |
+
"abs", "log", "sign", "power", "sqrt", "max", "min",
|
| 25 |
+
"if_else", "less", "greater", "equal",
|
| 26 |
+
"winsorize", "pasteurize", "truncate",
|
| 27 |
+
"vec_avg", "vec_sum", "vec_norm", "vec_count",
|
| 28 |
+
"trade_when", "ts_backfill", "filter", "mask",
|
| 29 |
+
"tail", "group_mean", "group_sum", "group_median",
|
| 30 |
+
"group_max", "group_min", "group_count", "group_neutralize",
|
| 31 |
+
"indneutralize", "market_neutralize",
|
| 32 |
+
"sigmoid", "tanh", "relu",
|
| 33 |
+
"correlation", "covariance", "regression_neut",
|
| 34 |
+
"fraction", "bucket",
|
| 35 |
+
}
|
| 36 |
+
ops = set()
|
| 37 |
+
with open(path) as f:
|
| 38 |
+
for line in f:
|
| 39 |
+
name = line.strip().split(",")[0].lower()
|
| 40 |
+
if name and name != "name":
|
| 41 |
+
ops.add(name)
|
| 42 |
+
return ops
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
ALLOWED_OPS: set[str] | None = None
|
| 46 |
+
|
| 47 |
+
# Look-ahead deny patterns β these ALWAYS indicate future data leakage
|
| 48 |
+
LOOKAHEAD_PATTERNS = [
|
| 49 |
+
r"ts_delay\([^,]+,\s*-\d", # negative delay = future data
|
| 50 |
+
r"\bfuture_", # any field named future_*
|
| 51 |
+
r"\bforward_return", # explicit forward returns
|
| 52 |
+
r"ts_backfill\([^,]+,\s*\d{3,}", # backfill > 99 days (suspicious)
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
# Unit-safety: top-level additive operands must be normalized
|
| 56 |
+
UNIT_SAFE_WRAPPERS = {"zscore", "rank", "quantile", "group_zscore", "group_rank", "group_neutralize", "indneutralize"}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def lint(expression: str, operators_path: Path = Path("data/operators.csv")) -> LintResult:
|
| 60 |
+
"""
|
| 61 |
+
Run all deterministic pre-flight checks on a BRAIN expression.
|
| 62 |
+
Returns LintResult with pass/fail + detailed errors.
|
| 63 |
+
"""
|
| 64 |
+
global ALLOWED_OPS
|
| 65 |
+
if ALLOWED_OPS is None:
|
| 66 |
+
ALLOWED_OPS = _load_operators(operators_path)
|
| 67 |
+
|
| 68 |
+
errors: list[str] = []
|
| 69 |
+
warnings: list[str] = []
|
| 70 |
+
|
| 71 |
+
# βββ CHECK 1: Empty or trivially short ββββββββββββββββββββββ
|
| 72 |
+
if not expression or len(expression.strip()) < 5:
|
| 73 |
+
errors.append("Expression is empty or trivially short")
|
| 74 |
+
return LintResult(passed=False, errors=errors, warnings=warnings)
|
| 75 |
+
|
| 76 |
+
# βββ CHECK 2: Operator validity βββββββββββββββββββββββββββββ
|
| 77 |
+
found_ops = re.findall(r"\b([a-z_]+)\s*\(", expression.lower())
|
| 78 |
+
for op in found_ops:
|
| 79 |
+
if op not in ALLOWED_OPS and op not in {"if", "and", "or", "not"}:
|
| 80 |
+
errors.append(f"Unknown operator: '{op}' β not in operators.csv")
|
| 81 |
+
|
| 82 |
+
# βββ CHECK 3: Look-ahead detection ββββββββββββββββββββββββββ
|
| 83 |
+
for pattern in LOOKAHEAD_PATTERNS:
|
| 84 |
+
match = re.search(pattern, expression, re.IGNORECASE)
|
| 85 |
+
if match:
|
| 86 |
+
errors.append(f"Look-ahead detected: '{match.group()}' (pattern: {pattern})")
|
| 87 |
+
|
| 88 |
+
# βββ CHECK 4: Balanced parentheses ββββββββββββββββββββββββββ
|
| 89 |
+
depth = 0
|
| 90 |
+
for ch in expression:
|
| 91 |
+
if ch == "(":
|
| 92 |
+
depth += 1
|
| 93 |
+
elif ch == ")":
|
| 94 |
+
depth -= 1
|
| 95 |
+
if depth < 0:
|
| 96 |
+
errors.append("Unbalanced parentheses: extra closing ')'")
|
| 97 |
+
break
|
| 98 |
+
if depth > 0:
|
| 99 |
+
errors.append(f"Unbalanced parentheses: {depth} unclosed '('")
|
| 100 |
+
|
| 101 |
+
# βββ CHECK 5: Unit-safety for additive expressions ββββββββββ
|
| 102 |
+
# Detect pattern: weight * func(...) + weight * func(...)
|
| 103 |
+
additive_parts = re.split(r"\s*\+\s*", expression.strip())
|
| 104 |
+
if len(additive_parts) > 1:
|
| 105 |
+
for part in additive_parts:
|
| 106 |
+
part_clean = part.strip()
|
| 107 |
+
# Check if the part is wrapped in a unit-safe function
|
| 108 |
+
first_func = re.match(r"[\d.\-]*\s*\*?\s*([a-z_]+)\s*\(", part_clean.lower())
|
| 109 |
+
if first_func:
|
| 110 |
+
func_name = first_func.group(1)
|
| 111 |
+
if func_name not in UNIT_SAFE_WRAPPERS:
|
| 112 |
+
warnings.append(
|
| 113 |
+
f"Additive operand not unit-safe (may cause 'Incompatible unit'): "
|
| 114 |
+
f"'{part_clean[:60]}...' β wrap in zscore/rank/quantile"
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
# βββ CHECK 6: Suspicious patterns (warnings, not errors) ββββ
|
| 118 |
+
# Very high decay
|
| 119 |
+
decay_match = re.search(r"ts_decay_linear\([^,]+,\s*(\d+)", expression)
|
| 120 |
+
if decay_match and int(decay_match.group(1)) > 20:
|
| 121 |
+
warnings.append(f"Decay of {decay_match.group(1)} days is unusually high β typical range 3-15")
|
| 122 |
+
|
| 123 |
+
# Very long lookback
|
| 124 |
+
for match in re.finditer(r"ts_\w+\([^,]+,\s*(\d+)", expression):
|
| 125 |
+
window = int(match.group(1))
|
| 126 |
+
if window > 252:
|
| 127 |
+
warnings.append(f"Window of {window} days exceeds 1 year β may have low coverage for newer stocks")
|
| 128 |
+
|
| 129 |
+
# βββ CHECK 7: Empty field references ββββββββββββββββββββββββ
|
| 130 |
+
# Look for common mistakes like ts_mean(, 5) or rank()
|
| 131 |
+
empty_args = re.findall(r"\b[a-z_]+\(\s*,", expression.lower())
|
| 132 |
+
if empty_args:
|
| 133 |
+
errors.append(f"Empty first argument detected: {empty_args}")
|
| 134 |
+
|
| 135 |
+
empty_func = re.findall(r"\b[a-z_]+\(\s*\)", expression.lower())
|
| 136 |
+
if empty_func:
|
| 137 |
+
errors.append(f"Function called with no arguments: {empty_func}")
|
| 138 |
+
|
| 139 |
+
return LintResult(
|
| 140 |
+
passed=len(errors) == 0,
|
| 141 |
+
errors=errors,
|
| 142 |
+
warnings=warnings,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def quick_dedup_hash(expression: str, neutralization: str, decay: int) -> str:
|
| 147 |
+
"""Generate a deterministic hash for dedup against factor store."""
|
| 148 |
+
import hashlib
|
| 149 |
+
key = f"{expression.strip()}|{neutralization}|{decay}"
|
| 150 |
+
return hashlib.sha256(key.encode()).hexdigest()[:16]
|