Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save quantra-go-algo/9d1243bdd26a9d9500b608c9cae51563 to your computer and use it in GitHub Desktop.

Select an option

Save quantra-go-algo/9d1243bdd26a9d9500b608c9cae51563 to your computer and use it in GitHub Desktop.
guardrailed-llm-agent — Step 3: Feature Engineering: Describing the Market's Mood (snippet 1)
feat = df.copy()
# 1. Daily log returns: the foundation of everything
feat['ret'] = np.log(feat['Close']).diff()
# 2. Realized annualized volatility (20-day rolling)
feat['vol'] = feat['ret'].rolling(VOL_WIN).std() * np.sqrt(252)
# 3. Trend score: rolling mean / rolling std
# Positive = uptrend, negative = downtrend, magnitude = consistency
rmean = feat['ret'].rolling(RET_WIN).mean()
rstd = feat['ret'].rolling(RET_WIN).std()
feat['trend'] = (rmean / (rstd + 1e-12)).clip(-5, 5)
# 4. Price z-score: how extended is price vs its own rolling mean?
# Positive = above average (potentially overbought), negative = below
ma = feat['Close'].rolling(ZSCORE_WIN).mean()
sd = feat['Close'].rolling(ZSCORE_WIN).std()
feat['z'] = ((feat['Close'] - ma) / (sd + 1e-12)).clip(-6, 6)
feat['mom63'] = feat['ret'].rolling(63).sum() # 63-day cumulative return (momentum)
feat['vol5'] = feat['ret'].rolling(5).std() * np.sqrt(252) # short-term vol (5-day)
feat['ma50'] = feat['Close'].rolling(50).mean() # 50-day moving average
feat = feat.dropna()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment