joshriang
← Back to portfolio

Quant research & trading·Python·Published

Strategy DSL

I got tired of editing Python every time I wanted to try a variation on a signal, so this is a small expression language that compiles to a strategy callable. The grammar is a recursive-descent parser with precedence climbing over assignment and when statements, where an action is long, short, flat or scale(expr), and expressions support +, -, *, /, unary minus, function calls and parenthesised groups. The stdlib has sma, ema, std, mean, zscore, rank, ts_rank, returns and delta plus OHLCV field accessors, which is enough to express 12-1 momentum, z-score mean reversion and a multi-factor composite without touching Python. The compiler walks the AST and emits a closure that takes a prices DataFrame and returns a weights Series clipped to [-1, 1], so a compiled strategy is a drop-in for any engine that expects weights. The CLI compiles a .dsl file, optionally backtests it against yfinance and writes the weights to CSV. Tests cover tokenizing, operator precedence, when-clause semantics and a realistic momentum program end to end.

Date
2026
Main stack
Python
Code
github ↗
01
02
  • Precedence climbing in a recursive-descent parser is about forty lines and removes the entire class of bugs that comes from hand-rolling expression evaluation with string splitting.
  • Clipping compiled weights to [-1, 1] at the compiler boundary means the language cannot express leverage, which is a deliberate restriction: it keeps a typo in a .dsl file from becoming a 10x position.
  • Compiling to a closure over the AST rather than to a string of Python keeps the strategy inspectable and avoids an eval path that would make the DSL a code-execution surface.
03

Scale 0–100: how much this project relied on each skill.