SPB Git forge

spb/wp8_uqo

Public
3commits 1branches 1releases
4.2 MBsize
maindefault branch
2 h agolast push
Python 56.2% TeX 43.7%
1.6 KB · 52 lines python
Raw Blame History
1"""Feature engineering for prediction market analysis."""23from __future__ import annotations45import numpy as np6import pandas as pd789def compute_log_returns(prices: pd.Series) -> pd.Series:10    return np.log(prices / prices.shift(1))111213def compute_realized_volatility(returns: pd.Series, window: int = 5) -> pd.Series:14    return (returns ** 2).rolling(window).sum().apply(np.sqrt)151617def compute_probability_changes(probs: pd.DataFrame) -> pd.DataFrame:18    return probs.diff()192021def compute_roll_spread(prices: pd.Series, window: int = 20) -> pd.Series:22    """Roll (1984) bid-ask spread estimator."""23    dp = prices.diff()2425    def _roll_cov(x: np.ndarray) -> float:26        if len(x) < 3:27            return np.nan28        return np.cov(x[:-1], x[1:])[0, 1]2930    cov = dp.rolling(window).apply(_roll_cov, raw=True)31    return 2 * np.sqrt(np.maximum(-cov, 0))323334def compute_amihud_illiquidity(returns: pd.Series, volume: pd.Series) -> pd.Series:35    return (returns.abs() / volume).replace([np.inf, -np.inf], np.nan)363738def compute_abnormal_volume(volume: pd.Series, window: int = 20) -> pd.Series:39    return volume / volume.rolling(window).mean()404142def engineer_features(prices_df: pd.DataFrame) -> pd.DataFrame:43    """Compute features for a panel of prices."""44    features = pd.DataFrame(index=prices_df.index)45    for col in prices_df.columns:46        s = prices_df[col]47        features[f"{col}_return"] = s.diff()48        features[f"{col}_log_return"] = compute_log_returns(s)49        features[f"{col}_rv5"] = compute_realized_volatility(s.diff(), 5)50        features[f"{col}_roll_spread"] = compute_roll_spread(s)51    return features52