Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Heuristic:1kbgz Tributary EMA Backfill From First Window

From Leeroopedia
Knowledge Sources
Domains Financial, Rolling_Calculations
Last Updated 2026-10-14 09:15 GMT

Overview

EMA initialization uses pandas `ewm()` backfill from the first full window when `full_only=True`, then switches to recursive update for subsequent ticks.

Description

The Exponential Moving Average (EMA) in tributary has a cold-start problem: the recursive formula `EMA = prev * (1 - mult) + val * mult` requires a previous EMA value, but none exists at the start. The implementation handles this by:

1. When `len(val) == 1`: Simply set `_prev = val[-1]` (seed with the first value). 2. When `full_only=True` and `_prev is None`: Backfill using `pd.Series(val).ewm(span=window_width).mean().iloc[-1]` — compute the EMA of the entire first full window using pandas, then use that as the seed. 3. For subsequent ticks: Use the standard recursive EMA formula.

The multiplier is `alpha` if provided, otherwise `2 / (window_width + 1)` (standard EMA smoothing ratio).

Usage

Use this heuristic when:

  • Implementing EMA on streaming financial data with `full_only=True` windows.
  • Debugging EMA values that appear incorrect for the first few ticks.
  • Choosing between `alpha` (direct smoothing factor) and `window_width` (span-based) parameterization.

The Insight (Rule of Thumb)

  • Action: Use `full_only=True` with EMA to get an accurate initial value from the first complete window.
  • Value: `alpha` for direct smoothing, or `window_width` for span-based (mult = `2/(window_width+1)`).
  • Trade-off: `full_only=True` delays the first output until the window is full, but provides a much more accurate EMA seed than using the first value alone.
  • Compatibility: Uses `pd.Series.ewm()` for backfill, requiring pandas. Works with both `alpha` and `window_width` parameterizations.

Reasoning

The EMA recursive formula is only valid once a previous EMA exists. Seeding with just the first value (`_prev = val[-1]`) introduces a transient bias that takes many ticks to wash out. By backfilling with pandas' `ewm()` on the first full window, the initial EMA is computed correctly for all elements in the window, providing a stable starting point. After that, the standard recursive formula is efficient and correct.

The `adjust` parameter is passed through to pandas' `ewm()`, controlling whether to use the bias-corrected variant.

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment