|
| 1 | +""" |
| 2 | +EMA Trend Ribbon Indicator |
| 3 | +
|
| 4 | +Uses a set of 9 Exponential Moving Averages with increasing periods to |
| 5 | +visualise trend strength and direction. When the majority of EMAs are |
| 6 | +rising the trend is bullish; when most are falling it is bearish. |
| 7 | +""" |
| 8 | +from typing import Union, List, Optional |
| 9 | + |
| 10 | +import numpy as np |
| 11 | +from pandas import DataFrame as PdDataFrame |
| 12 | +from polars import DataFrame as PlDataFrame |
| 13 | +import polars as pl |
| 14 | + |
| 15 | +from pyindicators.exceptions import PyIndicatorException |
| 16 | + |
| 17 | + |
| 18 | +def _calc_ema(src: np.ndarray, period: int) -> np.ndarray: |
| 19 | + """Compute EMA over a numpy array.""" |
| 20 | + n = len(src) |
| 21 | + alpha = 2.0 / (period + 1) |
| 22 | + out = np.empty(n) |
| 23 | + out[0] = src[0] |
| 24 | + |
| 25 | + for i in range(1, n): |
| 26 | + out[i] = src[i] * alpha + out[i - 1] * (1.0 - alpha) |
| 27 | + |
| 28 | + return out |
| 29 | + |
| 30 | + |
| 31 | +def ema_trend_ribbon( |
| 32 | + data: Union[PdDataFrame, PlDataFrame], |
| 33 | + source_column: str = 'Close', |
| 34 | + ema_lengths: Optional[List[int]] = None, |
| 35 | + smoothing_period: int = 2, |
| 36 | + threshold: int = 7, |
| 37 | + trend_column: str = 'ema_ribbon_trend', |
| 38 | + bullish_count_column: str = 'ema_ribbon_bullish_count', |
| 39 | + bearish_count_column: str = 'ema_ribbon_bearish_count', |
| 40 | + ema_column_prefix: str = 'ema_ribbon', |
| 41 | +) -> Union[PdDataFrame, PlDataFrame]: |
| 42 | + """ |
| 43 | + Calculate the EMA Trend Ribbon indicator. |
| 44 | +
|
| 45 | + Computes 9 EMAs with increasing periods and determines the overall |
| 46 | + trend by counting how many EMAs are rising vs falling over a |
| 47 | + smoothing period. When *threshold* or more EMAs agree on |
| 48 | + direction the trend is classified as bullish (1) or bearish (-1); |
| 49 | + otherwise neutral (0). |
| 50 | +
|
| 51 | + Calculation: |
| 52 | + - For each EMA period, compute EMA(source, period) |
| 53 | + - An EMA is "rising" when EMA[t] >= EMA[t - smoothing_period] |
| 54 | + - bullish_count = number of rising EMAs |
| 55 | + - bearish_count = number of falling EMAs |
| 56 | + - trend = 1 if bullish_count >= threshold, |
| 57 | + -1 if bearish_count >= threshold, else 0 |
| 58 | +
|
| 59 | + Args: |
| 60 | + data: pandas or polars DataFrame with price data. |
| 61 | + source_column: Column name for the source prices |
| 62 | + (default: 'Close'). |
| 63 | + ema_lengths: List of EMA periods (default: [8, 14, 20, 26, |
| 64 | + 32, 38, 44, 50, 60]). |
| 65 | + smoothing_period: Number of bars to look back when |
| 66 | + determining EMA slope direction (default: 2). |
| 67 | + threshold: Minimum number of EMAs that must agree for a |
| 68 | + bullish or bearish classification (default: 7, out of 9). |
| 69 | + trend_column: Result column name for the trend state |
| 70 | + (default: 'ema_ribbon_trend'). |
| 71 | + 1 = bullish, -1 = bearish, 0 = neutral. |
| 72 | + bullish_count_column: Result column name for the count of |
| 73 | + rising EMAs (default: 'ema_ribbon_bullish_count'). |
| 74 | + bearish_count_column: Result column name for the count of |
| 75 | + falling EMAs (default: 'ema_ribbon_bearish_count'). |
| 76 | + ema_column_prefix: Prefix for individual EMA result columns |
| 77 | + (default: 'ema_ribbon'). Each EMA is stored as |
| 78 | + ``{prefix}_{period}``. |
| 79 | +
|
| 80 | + Returns: |
| 81 | + DataFrame with added columns: |
| 82 | + - {ema_column_prefix}_{period}: Each individual EMA line |
| 83 | + - {bullish_count_column}: Number of rising EMAs at each bar |
| 84 | + - {bearish_count_column}: Number of falling EMAs at each bar |
| 85 | + - {trend_column}: Trend state (1 / -1 / 0) |
| 86 | +
|
| 87 | + Example: |
| 88 | + >>> import pandas as pd |
| 89 | + >>> from pyindicators import ema_trend_ribbon |
| 90 | + >>> df = pd.DataFrame({ |
| 91 | + ... 'Close': [100, 102, 101, 103, 105, 104, 106, 108, 107, 109] |
| 92 | + ... }) |
| 93 | + >>> result = ema_trend_ribbon(df, smoothing_period=1, threshold=5) |
| 94 | + >>> print(result[['ema_ribbon_trend']].tail()) |
| 95 | + """ |
| 96 | + if ema_lengths is None: |
| 97 | + ema_lengths = [8, 14, 20, 26, 32, 38, 44, 50, 60] |
| 98 | + |
| 99 | + # --- Validation ------------------------------------------------------- |
| 100 | + if smoothing_period < 1: |
| 101 | + raise PyIndicatorException( |
| 102 | + "Smoothing period must be at least 1" |
| 103 | + ) |
| 104 | + |
| 105 | + if threshold < 1: |
| 106 | + raise PyIndicatorException("Threshold must be at least 1") |
| 107 | + |
| 108 | + if threshold > len(ema_lengths): |
| 109 | + raise PyIndicatorException( |
| 110 | + f"Threshold ({threshold}) cannot exceed the number of " |
| 111 | + f"EMAs ({len(ema_lengths)})" |
| 112 | + ) |
| 113 | + |
| 114 | + if len(ema_lengths) < 2: |
| 115 | + raise PyIndicatorException( |
| 116 | + "At least 2 EMA lengths are required" |
| 117 | + ) |
| 118 | + |
| 119 | + for length in ema_lengths: |
| 120 | + if length < 1: |
| 121 | + raise PyIndicatorException( |
| 122 | + f"All EMA lengths must be at least 1, got {length}" |
| 123 | + ) |
| 124 | + |
| 125 | + if source_column not in data.columns: |
| 126 | + raise PyIndicatorException( |
| 127 | + f"The column '{source_column}' does not exist " |
| 128 | + "in the DataFrame." |
| 129 | + ) |
| 130 | + |
| 131 | + is_polars = isinstance(data, PlDataFrame) |
| 132 | + |
| 133 | + # --- Extract source array --------------------------------------------- |
| 134 | + if is_polars: |
| 135 | + src = data[source_column].to_numpy().astype(float) |
| 136 | + else: |
| 137 | + src = data[source_column].values.astype(float) |
| 138 | + |
| 139 | + n = len(src) |
| 140 | + |
| 141 | + # --- Compute all EMAs ------------------------------------------------- |
| 142 | + ema_arrays = [] |
| 143 | + |
| 144 | + for length in ema_lengths: |
| 145 | + ema_arrays.append(_calc_ema(src, length)) |
| 146 | + |
| 147 | + # --- Slope counting --------------------------------------------------- |
| 148 | + bullish_count = np.zeros(n, dtype=int) |
| 149 | + bearish_count = np.zeros(n, dtype=int) |
| 150 | + |
| 151 | + for ema_vals in ema_arrays: |
| 152 | + for t in range(n): |
| 153 | + prev_idx = t - smoothing_period |
| 154 | + |
| 155 | + if prev_idx < 0: |
| 156 | + # Not enough history; treat as neutral |
| 157 | + continue |
| 158 | + |
| 159 | + if ema_vals[t] >= ema_vals[prev_idx]: |
| 160 | + bullish_count[t] += 1 |
| 161 | + else: |
| 162 | + bearish_count[t] += 1 |
| 163 | + |
| 164 | + # --- Trend classification --------------------------------------------- |
| 165 | + trend = np.zeros(n, dtype=int) |
| 166 | + |
| 167 | + for t in range(n): |
| 168 | + if bullish_count[t] >= threshold: |
| 169 | + trend[t] = 1 |
| 170 | + elif bearish_count[t] >= threshold: |
| 171 | + trend[t] = -1 |
| 172 | + |
| 173 | + # --- Write results back ----------------------------------------------- |
| 174 | + if is_polars: |
| 175 | + new_cols = [] |
| 176 | + |
| 177 | + for length, ema_vals in zip(ema_lengths, ema_arrays): |
| 178 | + col_name = f"{ema_column_prefix}_{length}" |
| 179 | + new_cols.append(pl.Series(name=col_name, values=ema_vals)) |
| 180 | + |
| 181 | + new_cols.append( |
| 182 | + pl.Series(name=bullish_count_column, |
| 183 | + values=bullish_count.tolist()) |
| 184 | + ) |
| 185 | + new_cols.append( |
| 186 | + pl.Series(name=bearish_count_column, |
| 187 | + values=bearish_count.tolist()) |
| 188 | + ) |
| 189 | + new_cols.append( |
| 190 | + pl.Series(name=trend_column, values=trend.tolist()) |
| 191 | + ) |
| 192 | + data = data.with_columns(new_cols) |
| 193 | + else: |
| 194 | + for length, ema_vals in zip(ema_lengths, ema_arrays): |
| 195 | + col_name = f"{ema_column_prefix}_{length}" |
| 196 | + data[col_name] = ema_vals |
| 197 | + |
| 198 | + data[bullish_count_column] = bullish_count |
| 199 | + data[bearish_count_column] = bearish_count |
| 200 | + data[trend_column] = trend |
| 201 | + |
| 202 | + return data |
0 commit comments