Skip to content

Quant API

Money flow

money_flow

Smart-money and real/legal money-flow analytics.

DataFrame module-attribute

DataFrame: TypeAlias = pd.DataFrame | pl.DataFrame

_REQUIRED module-attribute

_REQUIRED = (
    "final_price",
    "close",
    "volume",
    "buy_I_Volume",
    "sell_I_Volume",
    "buy_I_Count",
    "sell_I_Count",
)

__all__ module-attribute

__all__ = ['compute_money_flow']

restore

restore(
    original: DataFrame, result: DataFrame
) -> DataFrame
Source code in src/iranquant/quant/_utils.py
def restore(original: DataFrame, result: pd.DataFrame) -> DataFrame:
    if isinstance(original, pl.DataFrame):
        return pl.from_pandas(result)
    return result

to_pandas

to_pandas(frame: DataFrame) -> pd.DataFrame
Source code in src/iranquant/quant/_utils.py
def to_pandas(frame: DataFrame) -> pd.DataFrame:
    if isinstance(frame, pl.DataFrame):
        return cast(pd.DataFrame, frame.to_pandas())
    if isinstance(frame, pd.DataFrame):
        return frame
    raise TypeError(f"Expected a pandas or polars DataFrame, got {type(frame)!r}")

compute_money_flow

compute_money_flow(
    frame: DataFrame, vol_window: int = 20
) -> DataFrame

Add smart-money, per-capita and real/legal flow columns.

Works with both Pandas and Polars inputs and returns a frame of the same type. All monetary per-capita values are expressed in Rials (*_m variants are in million Tomans).

The required input columns are final_price, close, volume, buy_I_Volume, sell_I_Volume, buy_I_Count and sell_I_Count (all present in :func:iranquant.full_history). Columns are computed as:

  • real_buy_per_capita = buy_I_Volume * final_price / max(buy_I_Count, 1)
  • real_sell_per_capita = sell_I_Volume * final_price / max(sell_I_Count, 1)
  • buyer_power_ratio = real_buy_per_capita / max(real_sell_per_capita, 1)
  • net_real_value = (buy_I_Volume - sell_I_Volume) * final_price
  • ownership_change_pct = ((buy_I_Volume - sell_I_Volume) / max(volume, 1)) * 100
  • close_vs_final_pct = ((close - final_price) / max(final_price, 1)) * 100
  • vol_ratio = volume / rolling_mean(volume, vol_window)

smart_money_entry is True when vol_ratio >= 1.8 and buyer_power_ratio >= 1.5 and net_real_value > 0 and close >= final_price. smart_money_exit mirrors it with buyer_power_ratio <= 0.67, net_real_value < 0 and close <= final_price.

Parameters:

Name Type Description Default
frame DataFrame

A history frame. Any extra columns (including date and jdate) are preserved unchanged.

required
vol_window int

Rolling window used for the volume-ratio baseline. Must be at least 1. Defaults to 20.

20

Returns:

Type Description
DataFrame

A frame of the same engine with all input columns plus:

DataFrame
  • real_buy_per_capita (float) — Rials per retail buy order.
DataFrame
  • real_buy_per_capita_m (float) — same, in million Tomans.
DataFrame
  • real_sell_per_capita (float) — Rials per retail sell order.
DataFrame
  • real_sell_per_capita_m (float) — same, in million Tomans.
DataFrame
  • buyer_power_ratio (float) — real buy/sell power ratio.
DataFrame
  • net_real_value (float) — net real money flow in Rials.
DataFrame
  • ownership_change_pct (float) — net real volume / total volume.
DataFrame
  • close_vs_final_pct (float) — last price vs closing price.
DataFrame
  • vol_ratio (float) — volume relative to its rolling mean.
DataFrame
  • smart_money_entry (bool) — smart-money accumulation signal.
DataFrame
  • smart_money_exit (bool) — smart-money distribution signal.

Raises:

Type Description
ValueError

If vol_window < 1.

KeyError

If any required input column is missing.

Examples:

>>> flow = compute_money_flow(iq.full_history("فولاد"))
>>> flow[["jdate", "buyer_power_ratio", "smart_money_entry"]].tail(3)

The Polars path preserves pl.DataFrame::

>>> import polars as pl
>>> flow = compute_money_flow(iq.full_history("فولاد", engine="polars"))
>>> flow.filter(pl.col("smart_money_entry")).height
Source code in src/iranquant/quant/money_flow.py
def compute_money_flow(frame: DataFrame, vol_window: int = 20) -> DataFrame:
    """Add smart-money, per-capita and real/legal flow columns.

    Works with both Pandas and Polars inputs and returns a frame of the same
    type.  All monetary per-capita values are expressed in Rials
    (``*_m`` variants are in million Tomans).

    The required input columns are ``final_price``, ``close``, ``volume``,
    ``buy_I_Volume``, ``sell_I_Volume``, ``buy_I_Count`` and ``sell_I_Count``
    (all present in :func:`iranquant.full_history`).  Columns are computed as:

    * ``real_buy_per_capita = buy_I_Volume * final_price / max(buy_I_Count, 1)``
    * ``real_sell_per_capita = sell_I_Volume * final_price / max(sell_I_Count, 1)``
    * ``buyer_power_ratio = real_buy_per_capita / max(real_sell_per_capita, 1)``
    * ``net_real_value = (buy_I_Volume - sell_I_Volume) * final_price``
    * ``ownership_change_pct = ((buy_I_Volume - sell_I_Volume) / max(volume, 1)) * 100``
    * ``close_vs_final_pct = ((close - final_price) / max(final_price, 1)) * 100``
    * ``vol_ratio = volume / rolling_mean(volume, vol_window)``

    ``smart_money_entry`` is ``True`` when ``vol_ratio >= 1.8`` **and**
    ``buyer_power_ratio >= 1.5`` **and** ``net_real_value > 0`` **and**
    ``close >= final_price``.  ``smart_money_exit`` mirrors it with
    ``buyer_power_ratio <= 0.67``, ``net_real_value < 0`` and
    ``close <= final_price``.

    Args:
        frame: A history frame.  Any extra columns (including ``date`` and
            ``jdate``) are preserved unchanged.
        vol_window: Rolling window used for the volume-ratio baseline.  Must be
            at least ``1``.  Defaults to ``20``.

    Returns:
        A frame of the same engine with all input columns plus:

        * ``real_buy_per_capita`` (``float``) — Rials per retail buy order.
        * ``real_buy_per_capita_m`` (``float``) — same, in million Tomans.
        * ``real_sell_per_capita`` (``float``) — Rials per retail sell order.
        * ``real_sell_per_capita_m`` (``float``) — same, in million Tomans.
        * ``buyer_power_ratio`` (``float``) — real buy/sell power ratio.
        * ``net_real_value`` (``float``) — net real money flow in Rials.
        * ``ownership_change_pct`` (``float``) — net real volume / total volume.
        * ``close_vs_final_pct`` (``float``) — last price vs closing price.
        * ``vol_ratio`` (``float``) — volume relative to its rolling mean.
        * ``smart_money_entry`` (``bool``) — smart-money accumulation signal.
        * ``smart_money_exit`` (``bool``) — smart-money distribution signal.

    Raises:
        ValueError: If ``vol_window < 1``.
        KeyError: If any required input column is missing.

    Examples:
        >>> flow = compute_money_flow(iq.full_history("فولاد"))
        >>> flow[["jdate", "buyer_power_ratio", "smart_money_entry"]].tail(3)

        The Polars path preserves ``pl.DataFrame``::

        >>> import polars as pl
        >>> flow = compute_money_flow(iq.full_history("فولاد", engine="polars"))
        >>> flow.filter(pl.col("smart_money_entry")).height
    """

    if vol_window < 1:
        raise ValueError("vol_window must be >= 1")

    source = to_pandas(frame)
    missing = [column for column in _REQUIRED if column not in source.columns]
    if missing:
        raise KeyError(f"Missing required columns: {', '.join(missing)}")

    out = source.copy()
    final_price = cast(pd.Series, out["final_price"].astype(float))
    close = cast(pd.Series, out["close"].astype(float))
    volume = cast(pd.Series, out["volume"].astype(float))
    buy_i_volume = cast(pd.Series, out["buy_I_Volume"].astype(float))
    sell_i_volume = cast(pd.Series, out["sell_I_Volume"].astype(float))
    buy_i_count = cast(pd.Series, out["buy_I_Count"].astype(float))
    sell_i_count = cast(pd.Series, out["sell_I_Count"].astype(float))

    real_buy = (buy_i_volume * final_price) / buy_i_count.clip(lower=1.0)
    real_sell = (sell_i_volume * final_price) / sell_i_count.clip(lower=1.0)
    buyer_power = real_buy / real_sell.clip(lower=1.0)

    net_real_value = (buy_i_volume - sell_i_volume) * final_price
    ownership_change = ((buy_i_volume - sell_i_volume) / volume.clip(lower=1.0)) * 100.0
    close_vs_final = ((close - final_price) / final_price.clip(lower=1.0)) * 100.0

    rolling_volume = volume.rolling(vol_window, min_periods=1).mean()
    vol_ratio = (volume / rolling_volume.clip(lower=1e-9)).fillna(0.0)

    out["real_buy_per_capita"] = real_buy
    out["real_buy_per_capita_m"] = real_buy / 1e7
    out["real_sell_per_capita"] = real_sell
    out["real_sell_per_capita_m"] = real_sell / 1e7
    out["buyer_power_ratio"] = buyer_power
    out["net_real_value"] = net_real_value
    out["ownership_change_pct"] = ownership_change
    out["close_vs_final_pct"] = close_vs_final
    out["vol_ratio"] = vol_ratio
    out["smart_money_entry"] = (
        (vol_ratio >= 1.8) & (buyer_power >= 1.5) & (net_real_value > 0) & (close >= final_price)
    )
    out["smart_money_exit"] = (
        (vol_ratio >= 1.8) & (buyer_power <= 0.67) & (net_real_value < 0) & (close <= final_price)
    )
    return restore(frame, out)

Momentum and swing legs

momentum

Swing-leg detection and multi-timeframe movement power.

DataFrame module-attribute

DataFrame: TypeAlias = pd.DataFrame | pl.DataFrame

LEG_COLUMNS module-attribute

LEG_COLUMNS = [
    "leg_id",
    "direction",
    "start_date",
    "end_date",
    "start_price",
    "end_price",
    "leg_return_pct",
    "leg_bars",
    "leg_velocity",
    "avg_volume",
    "leg_volume_expansion",
]

__all__ module-attribute

__all__ = [
    "LEG_COLUMNS",
    "compute_movement_power",
    "detect_swing_legs",
]

empty_like

empty_like(
    original: DataFrame, columns: list[str]
) -> DataFrame
Source code in src/iranquant/quant/_utils.py
def empty_like(original: DataFrame, columns: list[str]) -> DataFrame:
    if isinstance(original, pl.DataFrame):
        return pl.DataFrame({column: [] for column in columns})
    return pd.DataFrame(columns=columns)

restore

restore(
    original: DataFrame, result: DataFrame
) -> DataFrame
Source code in src/iranquant/quant/_utils.py
def restore(original: DataFrame, result: pd.DataFrame) -> DataFrame:
    if isinstance(original, pl.DataFrame):
        return pl.from_pandas(result)
    return result

to_pandas

to_pandas(frame: DataFrame) -> pd.DataFrame
Source code in src/iranquant/quant/_utils.py
def to_pandas(frame: DataFrame) -> pd.DataFrame:
    if isinstance(frame, pl.DataFrame):
        return cast(pd.DataFrame, frame.to_pandas())
    if isinstance(frame, pd.DataFrame):
        return frame
    raise TypeError(f"Expected a pandas or polars DataFrame, got {type(frame)!r}")

_zigzag

_zigzag(
    prices: ndarray, threshold: float
) -> list[tuple[int, float]]

Return alternating swing pivots using a percentage-reversal ZigZag.

Source code in src/iranquant/quant/momentum.py
def _zigzag(prices: np.ndarray, threshold: float) -> list[tuple[int, float]]:
    """Return alternating swing pivots using a percentage-reversal ZigZag."""

    length = len(prices)
    if length == 0:
        return []
    if length == 1:
        return [(0, float(prices[0]))]

    pivots: list[tuple[int, float]] = [(0, float(prices[0]))]
    direction = 0
    anchor_price = float(prices[0])
    extreme_index = 0
    extreme_price = float(prices[0])

    for index in range(1, length):
        price = float(prices[index])
        if direction == 0:
            if price >= anchor_price * (1.0 + threshold):
                direction = 1
                extreme_index, extreme_price = index, price
            elif price <= anchor_price * (1.0 - threshold):
                direction = -1
                extreme_index, extreme_price = index, price
        elif direction == 1:
            if price > extreme_price:
                extreme_index, extreme_price = index, price
            elif price <= extreme_price * (1.0 - threshold):
                pivots.append((extreme_index, extreme_price))
                direction = -1
                extreme_index, extreme_price = index, price
        else:
            if price < extreme_price:
                extreme_index, extreme_price = index, price
            elif price >= extreme_price * (1.0 + threshold):
                pivots.append((extreme_index, extreme_price))
                direction = 1
                extreme_index, extreme_price = index, price

    if direction == 0:
        if pivots[-1][0] != length - 1:
            pivots.append((length - 1, float(prices[-1])))
    else:
        if extreme_index != pivots[-1][0]:
            pivots.append((extreme_index, extreme_price))
        if pivots[-1][0] != length - 1:
            pivots.append((length - 1, float(prices[-1])))

    cleaned: list[tuple[int, float]] = []
    for index, price in pivots:
        if cleaned and index <= cleaned[-1][0]:
            continue
        cleaned.append((index, price))
    return cleaned

detect_swing_legs

detect_swing_legs(
    frame: DataFrame, reversal_pct: float = 5.0
) -> DataFrame

Detect ZigZag swing legs from the close column.

A percentage-reversal ZigZag is run over the closing prices. A leg is confirmed whenever price reverses by at least reversal_pct from the running extreme; the final, still-active leg is appended so the output always ends at the last bar. Input and output engine types match.

Parameters:

Name Type Description Default
frame DataFrame

A history frame containing close. date (used for start_date/end_date) and volume (used for volume statistics) are optional; without date positional integer indexes are used, and without volume the volume columns are 0.0/NaN.

required
reversal_pct float

Minimum reversal, in percent, required to confirm a new pivot. Must be positive. Defaults to 5.0.

5.0

Returns:

Type Description
DataFrame

One row per leg (completed legs plus the active leg) with columns:

DataFrame
  • leg_id (int) — one-based leg number.
DataFrame
  • direction (int) — 1 for up legs, -1 for down legs.
DataFrame
  • start_date / end_date (Any) — values from date, or
DataFrame

positional indexes when date is absent.

DataFrame
  • start_price / end_price (float) — pivot prices.
DataFrame
  • leg_return_pct (float) — percentage price change over the leg.
DataFrame
  • leg_bars (int) — number of bars spanned (end index - start).
DataFrame
  • leg_velocity (float) — leg_return_pct / max(leg_bars, 1).
DataFrame
  • avg_volume (float) — mean volume across the leg's bars.
DataFrame
  • leg_volume_expansion (float) — this leg's avg_volume
DataFrame

divided by the previous leg's; NaN for the first leg or when the

DataFrame

previous average is zero.

DataFrame

An empty frame with the same columns is returned for empty input or

DataFrame

when no pivots are found.

Raises:

Type Description
ValueError

If reversal_pct <= 0.

KeyError

If the close column is missing.

Examples:

>>> legs = detect_swing_legs(iq.history("فولاد"), reversal_pct=5.0)
>>> legs[["direction", "leg_return_pct", "leg_velocity"]].tail(5)
>>> legs[legs["leg_volume_expansion"] > 1.5]["direction"].tolist()
Source code in src/iranquant/quant/momentum.py
def detect_swing_legs(frame: DataFrame, reversal_pct: float = 5.0) -> DataFrame:
    """Detect ZigZag swing legs from the ``close`` column.

    A percentage-reversal ZigZag is run over the closing prices.  A leg is
    confirmed whenever price reverses by at least ``reversal_pct`` from the
    running extreme; the final, still-active leg is appended so the output
    always ends at the last bar.  Input and output engine types match.

    Args:
        frame: A history frame containing ``close``.  ``date`` (used for
            ``start_date``/``end_date``) and ``volume`` (used for volume
            statistics) are optional; without ``date`` positional integer
            indexes are used, and without ``volume`` the volume columns are
            ``0.0``/``NaN``.
        reversal_pct: Minimum reversal, in percent, required to confirm a new
            pivot.  Must be positive.  Defaults to ``5.0``.

    Returns:
        One row per leg (completed legs plus the active leg) with columns:

        * ``leg_id`` (``int``) — one-based leg number.
        * ``direction`` (``int``) — ``1`` for up legs, ``-1`` for down legs.
        * ``start_date`` / ``end_date`` (``Any``) — values from ``date``, or
        positional indexes when ``date`` is absent.
        * ``start_price`` / ``end_price`` (``float``) — pivot prices.
        * ``leg_return_pct`` (``float``) — percentage price change over the leg.
        * ``leg_bars`` (``int``) — number of bars spanned (end index - start).
        * ``leg_velocity`` (``float``) — ``leg_return_pct / max(leg_bars, 1)``.
        * ``avg_volume`` (``float``) — mean volume across the leg's bars.
        * ``leg_volume_expansion`` (``float``) — this leg's ``avg_volume``
        divided by the previous leg's; ``NaN`` for the first leg or when the
        previous average is zero.

        An empty frame with the same columns is returned for empty input or
        when no pivots are found.

    Raises:
        ValueError: If ``reversal_pct <= 0``.
        KeyError: If the ``close`` column is missing.

    Examples:
        >>> legs = detect_swing_legs(iq.history("فولاد"), reversal_pct=5.0)
        >>> legs[["direction", "leg_return_pct", "leg_velocity"]].tail(5)
        >>> legs[legs["leg_volume_expansion"] > 1.5]["direction"].tolist()
    """

    if reversal_pct <= 0:
        raise ValueError("reversal_pct must be positive")

    source = to_pandas(frame)
    if source.empty:
        return empty_like(frame, LEG_COLUMNS)
    if "close" not in source.columns:
        raise KeyError("Missing required column: close")

    closes = source["close"].astype(float).to_numpy()
    dates: list[Any] = (
        source["date"].tolist() if "date" in source.columns else list(range(len(source)))
    )
    volumes = (
        source["volume"].astype(float).to_numpy()
        if "volume" in source.columns
        else np.zeros(len(source), dtype=float)
    )

    pivots = _zigzag(closes, reversal_pct / 100.0)
    legs: list[dict[str, Any]] = []
    for leg_id in range(1, len(pivots)):
        start_index, start_price = pivots[leg_id - 1]
        end_index, end_price = pivots[leg_id]
        if end_index <= start_index:
            continue
        direction = 1 if end_price >= start_price else -1
        return_pct = ((end_price / start_price) - 1.0) * 100.0 if start_price else 0.0
        bars = end_index - start_index
        avg_volume = float(np.mean(volumes[start_index : end_index + 1]))
        legs.append(
            {
                "leg_id": leg_id,
                "direction": direction,
                "start_date": dates[start_index],
                "end_date": dates[end_index],
                "start_price": start_price,
                "end_price": end_price,
                "leg_return_pct": return_pct,
                "leg_bars": bars,
                "leg_velocity": return_pct / max(bars, 1),
                "avg_volume": avg_volume,
                "leg_volume_expansion": float("nan"),
            }
        )

    for index in range(1, len(legs)):
        previous_volume = float(legs[index - 1]["avg_volume"])
        if previous_volume > 0:
            legs[index]["leg_volume_expansion"] = float(legs[index]["avg_volume"]) / previous_volume

    if not legs:
        return empty_like(frame, LEG_COLUMNS)
    result = pd.DataFrame(legs, columns=LEG_COLUMNS)
    return restore(frame, result)

_signed_efficiency_ratio

_signed_efficiency_ratio(
    close: Series, window: int
) -> pd.Series
Source code in src/iranquant/quant/momentum.py
def _signed_efficiency_ratio(close: pd.Series, window: int) -> pd.Series:
    change = close - close.shift(window)
    path = close.diff().abs().rolling(window, min_periods=1).sum()
    ratio = (change.abs() / path.clip(lower=1e-12)).fillna(0.0)
    direction = np.sign(change.fillna(0.0).to_numpy(dtype=float))
    signed = np.nan_to_num(direction * ratio.to_numpy(), nan=0.0)
    return pd.Series(signed, index=close.index, dtype=float)

compute_movement_power

compute_movement_power(
    frame: DataFrame,
    windows: tuple[int, int, int] = (5, 20, 60),
) -> DataFrame

Compute a signed multi-timeframe Kaufman efficiency power score.

For each window w the signed Kaufman efficiency ratio is::

er_w = sign(close - close.shift(w))
       * abs(close - close.shift(w))
       / rolling_sum(abs(close.diff()), w)

The score starts as a weighted sum of the signed ratios. With exactly three windows the weights are (0.5, 0.3, 0.2); otherwise all windows are equally weighted. The score is then multiplied by a volume factor (volume / rolling_mean(volume, min(windows)) clipped to [0.5, 2.0]) and, when present, a buyer-power factor (clip(buyer_power_ratio, 0.5, 3.0) / 1.5 clipped to [0.5, 1.5]), scaled by 100 and clipped to [-100, +100].

Parameters:

Name Type Description Default
frame DataFrame

A history frame containing close. volume and buyer_power_ratio (produced by :func:compute_money_flow) are optional and only modulate the score when present.

required
windows tuple[int, int, int]

One or more positive lookback windows. Defaults to (5, 20, 60).

(5, 20, 60)

Returns:

Type Description
DataFrame

A frame of the same engine with all input columns plus:

DataFrame
  • er_<window> (float) — signed efficiency ratio per window
DataFrame

(for example er_5, er_20, er_60).

DataFrame
  • movement_power_score (float) — weighted, volume- and
DataFrame

buyer-power-adjusted score in [-100, +100].

Raises:

Type Description
ValueError

If windows is empty or contains a non-positive value.

KeyError

If the close column is missing.

Examples:

>>> power = compute_movement_power(iq.full_history("فولاد"))
>>> power[["jdate", "er_5", "er_20", "movement_power_score"]].tail(3)
>>> power.sort_values("movement_power_score", ascending=False).head()
Source code in src/iranquant/quant/momentum.py
def compute_movement_power(
    frame: DataFrame,
    windows: tuple[int, int, int] = (5, 20, 60),
) -> DataFrame:
    """Compute a signed multi-timeframe Kaufman efficiency power score.

    For each window ``w`` the signed Kaufman efficiency ratio is::

        er_w = sign(close - close.shift(w))
               * abs(close - close.shift(w))
               / rolling_sum(abs(close.diff()), w)

    The score starts as a weighted sum of the signed ratios.  With exactly
    three windows the weights are ``(0.5, 0.3, 0.2)``; otherwise all windows
    are equally weighted.  The score is then multiplied by a volume factor
    (``volume / rolling_mean(volume, min(windows))`` clipped to ``[0.5, 2.0]``)
    and, when present, a buyer-power factor
    (``clip(buyer_power_ratio, 0.5, 3.0) / 1.5`` clipped to ``[0.5, 1.5]``),
    scaled by ``100`` and clipped to ``[-100, +100]``.

    Args:
        frame: A history frame containing ``close``.  ``volume`` and
            ``buyer_power_ratio`` (produced by :func:`compute_money_flow`) are
            optional and only modulate the score when present.
        windows: One or more positive lookback windows.  Defaults to
            ``(5, 20, 60)``.

    Returns:
        A frame of the same engine with all input columns plus:

        * ``er_<window>`` (``float``) — signed efficiency ratio per window
        (for example ``er_5``, ``er_20``, ``er_60``).
        * ``movement_power_score`` (``float``) — weighted, volume- and
        buyer-power-adjusted score in ``[-100, +100]``.

    Raises:
        ValueError: If ``windows`` is empty or contains a non-positive value.
        KeyError: If the ``close`` column is missing.

    Examples:
        >>> power = compute_movement_power(iq.full_history("فولاد"))
        >>> power[["jdate", "er_5", "er_20", "movement_power_score"]].tail(3)
        >>> power.sort_values("movement_power_score", ascending=False).head()
    """

    if not windows:
        raise ValueError("At least one window is required")
    if any(window < 1 for window in windows):
        raise ValueError("Windows must be positive integers")

    source = to_pandas(frame)
    if "close" not in source.columns:
        raise KeyError("Missing required column: close")
    if source.empty:
        out = source.copy()
        for window in windows:
            out[f"er_{window}"] = pd.Series(dtype=float)
        out["movement_power_score"] = pd.Series(dtype=float)
        return restore(frame, out)

    out = source.copy()
    close = cast(pd.Series, out["close"].astype(float))

    weights = [0.5, 0.3, 0.2] if len(windows) == 3 else [1.0 / len(windows)] * len(windows)

    score = pd.Series(0.0, index=out.index, dtype=float)
    for window, weight in zip(windows, weights, strict=True):
        signed = _signed_efficiency_ratio(close, window)
        out[f"er_{window}"] = signed
        score = score + (signed * weight)

    shortest = min(windows)
    if "volume" in out.columns:
        volume = cast(pd.Series, out["volume"].astype(float))
        rolling_volume = volume.rolling(shortest, min_periods=1).mean()
        volume_factor = (volume / rolling_volume.clip(lower=1e-9)).fillna(1.0)
        volume_factor = volume_factor.clip(lower=0.5, upper=2.0)
    else:
        volume_factor = pd.Series(1.0, index=out.index, dtype=float)

    if "buyer_power_ratio" in out.columns:
        buyer_power = cast(pd.Series, out["buyer_power_ratio"].astype(float))
        buyer_power = buyer_power.fillna(1.0).clip(lower=0.5, upper=3.0) / 1.5
        buyer_power = buyer_power.clip(lower=0.5, upper=1.5)
    else:
        buyer_power = pd.Series(1.0, index=out.index, dtype=float)

    power = (score * 100.0 * volume_factor * buyer_power).clip(lower=-100.0, upper=100.0)
    out["movement_power_score"] = power
    return restore(frame, out)

Screener

screener

Vectorized market-wide screening helpers.

DataFrame module-attribute

DataFrame: TypeAlias = pd.DataFrame | pl.DataFrame

__all__ module-attribute

__all__ = ['MarketScreener']

MarketScreener

MarketScreener(frame: DataFrame | None = None)

Vectorized filters over a MarketWatch (or batch) DataFrame.

Every filter accepts an optional alternative frame; when omitted the frame passed to the constructor is used. Results preserve the input engine type (Pandas in, Pandas out; Polars in, Polars out) and are reset to a clean index.

Parameters:

Name Type Description Default
frame DataFrame | None

An optional MarketWatch frame from :func:iranquant.market_watch (or any frame with the same columns). Filters may instead receive the frame directly, so both MarketScreener(frame).filter_buy_queue() and MarketScreener().filter_buy_queue(frame) are equivalent.

None

Raises:

Type Description
ValueError

If a filter runs without a bound or call-time frame.

TypeError

If the selected frame is neither a Pandas nor a Polars DataFrame (raised lazily when a filter runs).

Examples:

>>> screener = MarketScreener(iq.market_watch())
>>> screener.filter_buy_queue()[["symbol", "close", "tmax"]]
>>> MarketScreener().filter_buy_queue(iq.market_watch()).head()
Source code in src/iranquant/quant/screener.py
def __init__(self, frame: DataFrame | None = None) -> None:
    self._frame = frame

filter_buy_queue

filter_buy_queue(
    frame: DataFrame | None = None,
) -> DataFrame

Symbols locked at tmax with a positive buy-queue volume.

The mask is (tmax > 0) & (close >= tmax) & (sum(zmd) > 0). The buy-queue volume is the sum of zmd (bid volume) across all order-book levels.

Parameters:

Name Type Description Default
frame DataFrame | None

Optional alternative frame; defaults to the constructor frame.

None

Returns:

Type Description
DataFrame

The matching rows in the same engine as the input.

Raises:

Type Description
KeyError

If close or tmax is missing.

Examples:

>>> locked = screener.filter_buy_queue()
>>> locked[["symbol", "close", "tmax"]].head()
Source code in src/iranquant/quant/screener.py
def filter_buy_queue(self, frame: DataFrame | None = None) -> DataFrame:
    """Symbols locked at ``tmax`` with a positive buy-queue volume.

    The mask is ``(tmax > 0) & (close >= tmax) & (sum(zmd) > 0)``.  The
    buy-queue volume is the sum of ``zmd`` (bid volume) across all order-book
    levels.

    Args:
        frame: Optional alternative frame; defaults to the constructor
            frame.

    Returns:
        The matching rows in the same engine as the input.

    Raises:
        KeyError: If ``close`` or ``tmax`` is missing.

    Examples:
        >>> locked = screener.filter_buy_queue()
        >>> locked[["symbol", "close", "tmax"]].head()
    """

    original, source = self._source(frame)
    for column in ("close", "tmax"):
        if column not in source.columns:
            raise KeyError(f"Missing required column: {column}")
    close = source["close"].astype(float)
    tmax = source["tmax"].astype(float)
    buy_volume = self._queue_volume(source, "buy")
    mask = (tmax > 0) & (close >= tmax) & (buy_volume > 0)
    return self._restore(original, source.loc[mask])

filter_sell_queue

filter_sell_queue(
    frame: DataFrame | None = None,
) -> DataFrame

Symbols locked at tmin with a positive sell-queue volume.

The mask is (tmin > 0) & (close <= tmin) & (sum(zmo) > 0). The sell-queue volume is the sum of zmo (ask volume) across all order-book levels.

Parameters:

Name Type Description Default
frame DataFrame | None

Optional alternative frame; defaults to the constructor frame.

None

Returns:

Type Description
DataFrame

The matching rows in the same engine as the input.

Raises:

Type Description
KeyError

If close or tmin is missing.

Examples:

>>> locked = screener.filter_sell_queue()
>>> locked[["symbol", "close", "tmin"]].head()
Source code in src/iranquant/quant/screener.py
def filter_sell_queue(self, frame: DataFrame | None = None) -> DataFrame:
    """Symbols locked at ``tmin`` with a positive sell-queue volume.

    The mask is ``(tmin > 0) & (close <= tmin) & (sum(zmo) > 0)``.  The
    sell-queue volume is the sum of ``zmo`` (ask volume) across all
    order-book levels.

    Args:
        frame: Optional alternative frame; defaults to the constructor
            frame.

    Returns:
        The matching rows in the same engine as the input.

    Raises:
        KeyError: If ``close`` or ``tmin`` is missing.

    Examples:
        >>> locked = screener.filter_sell_queue()
        >>> locked[["symbol", "close", "tmin"]].head()
    """

    original, source = self._source(frame)
    for column in ("close", "tmin"):
        if column not in source.columns:
            raise KeyError(f"Missing required column: {column}")
    close = source["close"].astype(float)
    tmin = source["tmin"].astype(float)
    sell_volume = self._queue_volume(source, "sell")
    mask = (tmin > 0) & (close <= tmin) & (sell_volume > 0)
    return self._restore(original, source.loc[mask])

filter_positive_tick_surge

filter_positive_tick_surge(
    frame: DataFrame | None = None,
    min_diff_pct: float = 1.5,
) -> DataFrame

Symbols whose last price exceeds the final price by min_diff_pct.

The mask is ((close - final_price) / max(final_price, 1)) * 100 >= min_diff_pct.

Parameters:

Name Type Description Default
frame DataFrame | None

Optional alternative frame; defaults to the constructor frame.

None
min_diff_pct float

Minimum percentage gap between the last traded price and the closing price. Defaults to 1.5.

1.5

Returns:

Type Description
DataFrame

The matching rows in the same engine as the input.

Raises:

Type Description
KeyError

If close or final_price is missing.

Examples:

>>> surges = screener.filter_positive_tick_surge(min_diff_pct=1.5)
>>> surges[["symbol", "close", "final_price"]].head()
Source code in src/iranquant/quant/screener.py
def filter_positive_tick_surge(
    self,
    frame: DataFrame | None = None,
    min_diff_pct: float = 1.5,
) -> DataFrame:
    """Symbols whose last price exceeds the final price by ``min_diff_pct``.

    The mask is
    ``((close - final_price) / max(final_price, 1)) * 100 >= min_diff_pct``.

    Args:
        frame: Optional alternative frame; defaults to the constructor
            frame.
        min_diff_pct: Minimum percentage gap between the last traded price
            and the closing price.  Defaults to ``1.5``.

    Returns:
        The matching rows in the same engine as the input.

    Raises:
        KeyError: If ``close`` or ``final_price`` is missing.

    Examples:
        >>> surges = screener.filter_positive_tick_surge(min_diff_pct=1.5)
        >>> surges[["symbol", "close", "final_price"]].head()
    """

    original, source = self._source(frame)
    for column in ("close", "final_price"):
        if column not in source.columns:
            raise KeyError(f"Missing required column: {column}")
    close = source["close"].astype(float)
    final_price = source["final_price"].astype(float)
    diff_pct = ((close - final_price) / final_price.clip(lower=1.0)) * 100.0
    mask = diff_pct >= min_diff_pct
    return self._restore(original, source.loc[mask])

scan_market

scan_market(
    custom_predicate: Callable[
        [DataFrame], DataFrame | Series
    ],
    frame: DataFrame | None = None,
) -> DataFrame

Apply a custom Pandas predicate/mask and restore the engine type.

Parameters:

Name Type Description Default
custom_predicate Callable[[DataFrame], DataFrame | Series]

A callable that receives the frame as a :class:pandas.DataFrame and returns either a filtered DataFrame or a boolean Series mask. NaN mask values are treated as False.

required
frame DataFrame | None

Optional alternative frame; defaults to the constructor frame.

None

Returns:

Type Description
DataFrame

The filtered rows converted back to the input engine.

Raises:

Type Description
TypeError

If custom_predicate returns neither a DataFrame nor a Series.

Examples:

>>> high_volume = screener.scan_market(
...     lambda df: df["volume"] > df["volume"].median()
... )
>>> high_volume[["symbol", "volume"]].sort_values("volume").tail()
Source code in src/iranquant/quant/screener.py
def scan_market(
    self,
    custom_predicate: Callable[[pd.DataFrame], pd.DataFrame | pd.Series],
    frame: DataFrame | None = None,
) -> DataFrame:
    """Apply a custom Pandas predicate/mask and restore the engine type.

    Args:
        custom_predicate: A callable that receives the frame as a
            :class:`pandas.DataFrame` and returns either a filtered
            DataFrame or a boolean Series mask.  ``NaN`` mask values are
            treated as ``False``.
        frame: Optional alternative frame; defaults to the constructor
            frame.

    Returns:
        The filtered rows converted back to the input engine.

    Raises:
        TypeError: If ``custom_predicate`` returns neither a DataFrame nor
            a Series.

    Examples:
        >>> high_volume = screener.scan_market(
        ...     lambda df: df["volume"] > df["volume"].median()
        ... )
        >>> high_volume[["symbol", "volume"]].sort_values("volume").tail()
    """

    original, source = self._source(frame)
    result = custom_predicate(source)
    if isinstance(result, pd.DataFrame):
        filtered = result
    elif isinstance(result, pd.Series):
        mask = result.fillna(False).astype(bool)
        filtered = source.loc[mask]
    else:
        raise TypeError("custom_predicate must return a pandas DataFrame or boolean Series")
    return self._restore(original, filtered)

restore

restore(
    original: DataFrame, result: DataFrame
) -> DataFrame
Source code in src/iranquant/quant/_utils.py
def restore(original: DataFrame, result: pd.DataFrame) -> DataFrame:
    if isinstance(original, pl.DataFrame):
        return pl.from_pandas(result)
    return result

to_pandas

to_pandas(frame: DataFrame) -> pd.DataFrame
Source code in src/iranquant/quant/_utils.py
def to_pandas(frame: DataFrame) -> pd.DataFrame:
    if isinstance(frame, pl.DataFrame):
        return cast(pd.DataFrame, frame.to_pandas())
    if isinstance(frame, pd.DataFrame):
        return frame
    raise TypeError(f"Expected a pandas or polars DataFrame, got {type(frame)!r}")

_to_float

_to_float(value: Any) -> float
Source code in src/iranquant/quant/screener.py
def _to_float(value: Any) -> float:
    try:
        return float(value)
    except (TypeError, ValueError):
        return 0.0

_side_volume

_side_volume(order_book: Any, side: str) -> float
Source code in src/iranquant/quant/screener.py
def _side_volume(order_book: Any, side: str) -> float:
    if order_book is None:
        return 0.0
    if isinstance(order_book, dict):
        levels: list[Any] = [order_book]
    elif isinstance(order_book, str):
        return 0.0
    else:
        levels = list(order_book)

    key = "zmd" if side == "buy" else "zmo"
    total = 0.0
    for level in levels:
        if isinstance(level, dict):
            total += _to_float(level.get(key, 0.0))
        else:
            total += _to_float(getattr(level, key, 0.0))
    return total