Skip to content

refactor: safe_pct is a nested function inside compute_price_metrics — extract to module-level helper #52

@Codex-Crusader

Description

@Codex-Crusader

Summary

In pulseengine/core/price.py, the helper safe_pct is defined as a closure inside compute_price_metrics. While this works, PEP 8 and Python conventions prefer module-level helpers over closures when the nested function captures only one outer variable (close and latest) and is only a few lines. The current pattern:

  • Makes safe_pct impossible to test directly in isolation
  • Hides a reusable utility from the module namespace
  • Creates a new function object on every call to compute_price_metrics

Location

pulseengine/core/price.py, lines 160–167 (inside compute_price_metrics):

def safe_pct(n: int) -> Optional[float]:
    if len(close) > n:
        old = float(close.iloc[-(n + 1)])
        if abs(old) < 1e-9 or not math.isfinite(old):
            return None
        pct = ((latest - old) / old) * 100
        return round(pct, 2) if math.isfinite(pct) else None
    return None

Proposed fix

Extract to a module-level function with explicit parameters:

def _safe_pct(close: pd.Series, latest: float, n: int) -> float | None:
    """Return the n-bar percentage change relative to *latest*, or None."""
    if len(close) > n:
        old = float(close.iloc[-(n + 1)])
        if abs(old) < 1e-9 or not math.isfinite(old):
            return None
        pct = ((latest - old) / old) * 100
        return round(pct, 2) if math.isfinite(pct) else None
    return None

This function can then be unit-tested directly in tests/test_core.py.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions