from __future__ import annotations

import numpy as np
import pandas as pd


def add_volume_features(group: pd.DataFrame) -> pd.DataFrame:
    result = group.copy()
    volume = result["volume"].astype(float)
    close = result["adjusted_close"].fillna(result["close"])
    for window in (5, 20):
        average = volume.rolling(window, min_periods=window).mean()
        result[f"volume_average_{window}d"] = average
        result[f"volume_ratio_{window}d"] = volume / average.replace(0, np.nan)
    mean20 = volume.rolling(20, min_periods=20).mean()
    std20 = volume.rolling(20, min_periods=20).std(ddof=0)
    result["volume_zscore_20d"] = (volume - mean20) / std20.replace(0, np.nan)
    result["volume_trend_5d"] = mean20.pct_change(5, fill_method=None)
    direction = np.sign(close.diff()).fillna(0)
    result["obv"] = (direction * volume).cumsum()
    result["obv_slope_5d"] = result["obv"].diff(5) / 5
    result["price_volume_confirmation"] = np.sign(close.pct_change(fill_method=None)) * result["volume_zscore_20d"]
    return result

