rhoa.indicators

class indicators[source]
__init__(series)[source]
Parameters:

series (Series)

Return type:

None

Methods

__init__(series)

bollinger_bands([window_size, num_std, ...])

Calculate Bollinger Bands for volatility and mean reversion analysis.

ewma([window_size, adjust, min_periods])

Calculate the Exponential Weighted Moving Average (EWMA) of the series.

ewmstd([window_size, adjust, min_periods])

Calculate the exponentially weighted moving standard deviation (EWMSTD).

ewmv([window_size, adjust, min_periods])

Calculate the exponentially weighted moving variance (EWMV) of a series.

macd([short_window, long_window, signal_window])

Calculate the MACD (Moving Average Convergence Divergence) indicator.

rsi([window_size, edge_case_value])

Calculate the Relative Strength Index (RSI) for momentum analysis.

sma([window_size, min_periods, center])

Calculate the Simple Moving Average (SMA) over a specified window.

__init__(series)[source]
Parameters:

series (Series)

Return type:

None

sma(window_size=20, min_periods=None, center=False, **kwargs)[source]

Calculate the Simple Moving Average (SMA) over a specified window.

The SMA is a commonly used technical indicator in financial and time series analysis that calculates the arithmetic mean of prices over a defined number of periods. It smooths out price data to identify trends by reducing noise from short-term fluctuations.

Parameters:
  • window_size (int, default 20) – The size of the moving window, representing the number of periods over which to calculate the average.

  • min_periods (int, optional) – Minimum number of observations in window required to have a value. If None, defaults to window_size.

  • center (bool, default False) – Whether to set the labels at the center of the window.

  • **kwargs (dict) – Additional keyword arguments passed to pandas rolling function.

Returns:

A Series containing the calculated SMA values with the same index as the input series.

Return type:

pandas.Series

See also

ewma

Exponential Weighted Moving Average for trend analysis

bollinger_bands

Uses SMA as the middle band

macd

Uses exponential moving averages

Notes

The Simple Moving Average is calculated as:

\[SMA_t = \frac{1}{n} \sum_{i=0}^{n-1} P_{t-i}\]

where \(P_t\) is the price at time t and n is the window_size.

The first window_size - 1 values will be NaN unless min_periods is set to a lower value. SMA gives equal weight to all values in the window, which can make it slower to respond to recent price changes compared to exponential moving averages.

SMA is commonly used for: - Identifying support and resistance levels - Generating crossover trading signals (e.g., golden cross, death cross) - Smoothing price data for trend identification

Tip

Also available via DataFrame accessor: df.rhoa.indicators.sma(window_size=20) which defaults to the Close column. See DataFrameIndicators.

Examples

Calculate 20-period Simple Moving Average:

>>> import pandas as pd
>>> import rhoa
>>> prices = pd.Series([100, 102, 101, 103, 105, 104, 106])
>>> sma = prices.rhoa.indicators.sma(window_size=5)
>>> print(sma.iloc[4])  # First valid SMA value
102.2

Generate trading signals using SMA crossover:

>>> prices = pd.Series([100, 102, 104, 106, 108, 107, 105, 103, 101])
>>> sma_short = prices.rhoa.indicators.sma(window_size=3)
>>> sma_long = prices.rhoa.indicators.sma(window_size=5)
>>> buy_signal = (sma_short > sma_long) & (sma_short.shift(1) <= sma_long.shift(1))
ewma(window_size=20, adjust=False, min_periods=None, **kwargs)[source]

Calculate the Exponential Weighted Moving Average (EWMA) of the series.

The EWMA is a type of infinite impulse response filter that applies weighting factors which decrease exponentially. Unlike simple moving averages, EWMA gives more weight to recent observations, making it more responsive to recent price changes while still providing smoothing.

Parameters:
  • window_size (int, default 20) – The span of the exponential moving average. Determines the level of smoothing, where larger values result in smoother trends and slower responsiveness to changes in the data.

  • adjust (bool, default False) – Divide by decaying adjustment factor in beginning periods. When True, the weights are normalized by the sum of weights to account for the imbalance in the beginning periods.

  • min_periods (int, optional) – Minimum number of observations in window required to have a value. If None, defaults to 0.

  • **kwargs (dict) – Additional keyword arguments passed to pandas ewm function.

Returns:

A Series containing the calculated EWMA values with the same index as the input series.

Return type:

pandas.Series

See also

sma

Simple Moving Average for trend analysis

ewmv

Exponential Weighted Moving Variance

ewmstd

Exponential Weighted Moving Standard Deviation

macd

Uses EWMA for signal generation

Notes

The Exponential Weighted Moving Average is calculated using:

\[EWMA_t = \alpha \cdot P_t + (1 - \alpha) \cdot EWMA_{t-1}\]

where \(\alpha = \frac{2}{span + 1}\) and span is the window_size.

Key characteristics: - More weight to recent prices: reacts faster to recent changes - Smoother than price but more responsive than SMA - All historical data has some influence (infinite impulse response) - No lookback period required (unlike SMA)

The adjust parameter affects the calculation in the initial periods: - adjust=True: Uses normalized weights (standard EWMA definition) - adjust=False: Uses recursive formula (more common in trading)

EWMA is commonly used for: - Trend identification and confirmation - Support and resistance levels that adapt to volatility - Component of MACD and other composite indicators

Tip

Also available via DataFrame accessor: df.rhoa.indicators.ewma(window_size=20) which defaults to the Close column. See DataFrameIndicators.

Examples

Calculate 20-period Exponential Weighted Moving Average:

>>> import pandas as pd
>>> import rhoa
>>> prices = pd.Series([100, 102, 101, 103, 105, 104, 106, 108])
>>> ewma = prices.rhoa.indicators.ewma(window_size=5)
>>> print(f"Latest EWMA: {ewma.iloc[-1]:.2f}")
Latest EWMA: 105.45

Compare EWMA with different window sizes:

>>> ewma_fast = prices.rhoa.indicators.ewma(window_size=5)
>>> ewma_slow = prices.rhoa.indicators.ewma(window_size=20)
>>> crossover = (ewma_fast > ewma_slow) & (ewma_fast.shift(1) <= ewma_slow.shift(1))
ewmv(window_size=20, adjust=True, min_periods=None, **kwargs)[source]

Calculate the exponentially weighted moving variance (EWMV) of a series.

This method computes the variance of a series by applying exponential weighting to give more importance to recent observations. EWMV is useful for measuring volatility that adapts more quickly to recent price changes compared to standard rolling variance.

Parameters:
  • window_size (int, default 20) – The span of the exponential window. Determines the level of smoothing applied to the variance calculation. Larger values result in smoother variance estimates.

  • adjust (bool, default True) – Divide by decaying adjustment factor in beginning periods. When True, the weights are normalized by the sum of weights.

  • min_periods (int, optional) – Minimum number of observations in window required to have a value. If None, defaults to 0.

  • **kwargs (dict) – Additional keyword arguments passed to pandas ewm function.

Returns:

A Series containing the exponentially weighted moving variance values with the same index as the input series.

Return type:

pandas.Series

See also

ewmstd

Exponential Weighted Moving Standard Deviation

ewma

Exponential Weighted Moving Average

bollinger_bands

Uses standard deviation for band calculation

Notes

The exponentially weighted moving variance uses exponential smoothing to calculate variance with the formula:

\[EWMV_t = \alpha \sum_{i=0}^{t} (1-\alpha)^i (P_{t-i} - EWMA_t)^2\]

where \(\alpha = \frac{2}{span + 1}\) and span is the window_size.

Key properties: - Always non-negative (variance cannot be negative) - More responsive to recent volatility changes than rolling variance - Relationship: \(EWMV = EWMSTD^2\) - Units are squared (e.g., squared dollars for price data)

Higher variance values indicate increased volatility and risk. EWMV is commonly used for: - Volatility estimation in risk management - Detecting regime changes in market conditions - Building adaptive trading strategies - Calculating value-at-risk (VaR) metrics

Tip

Also available via DataFrame accessor: df.rhoa.indicators.ewmv(window_size=20) which defaults to the Close column. See DataFrameIndicators.

Examples

Calculate exponentially weighted moving variance:

>>> import pandas as pd
>>> import rhoa
>>> prices = pd.Series([100, 102, 99, 103, 105, 101, 106, 104])
>>> ewmv = prices.rhoa.indicators.ewmv(window_size=5)
>>> print(f"Latest variance: {ewmv.iloc[-1]:.2f}")
Latest variance: 6.24

Detect periods of high volatility:

>>> prices = pd.Series([100, 102, 101, 103, 105, 104, 110, 95, 105, 100])
>>> ewmv = prices.rhoa.indicators.ewmv(window_size=5)
>>> high_volatility = ewmv > ewmv.rolling(20).mean() * 1.5
ewmstd(window_size=20, adjust=True, min_periods=None, **kwargs)[source]

Calculate the exponentially weighted moving standard deviation (EWMSTD).

EWMSTD is a statistical measure that weights recent data points more heavily to provide a smoothed calculation of the moving standard deviation. This makes it more responsive to recent volatility changes compared to traditional rolling standard deviation, while maintaining smoothness.

Parameters:
  • window_size (int, default 20) – The span or window size for the exponentially weighted moving calculation. Smaller spans apply heavier weighting to more recent data points and react faster to changes, while larger spans provide smoother results.

  • adjust (bool, default True) – Divide by decaying adjustment factor in beginning periods. When True, the weights are normalized by the sum of weights.

  • min_periods (int, optional) – Minimum number of observations in window required to have a value. If None, defaults to 0.

  • **kwargs (dict) – Additional keyword arguments passed to pandas ewm function.

Returns:

A Series containing the exponentially weighted moving standard deviation values with the same index as the input series.

Return type:

pandas.Series

See also

ewmv

Exponential Weighted Moving Variance

ewma

Exponential Weighted Moving Average

bollinger_bands

Uses standard deviation for volatility bands

atr

Average True Range for volatility measurement

Notes

The exponentially weighted moving standard deviation is the square root of the exponentially weighted moving variance:

\[EWMSTD_t = \sqrt{EWMV_t}\]

where \(EWMV_t\) is calculated with exponential weights.

The relationship \(EWMSTD^2 = EWMV\) always holds.

Key characteristics: - Always non-negative (standard deviation cannot be negative) - Same units as the original series (unlike variance) - More responsive to recent volatility than rolling standard deviation - Commonly used as a volatility proxy in trading

EWMSTD is commonly used for: - Volatility-based position sizing - Risk management and stop-loss placement - Adaptive trading strategies that respond to volatility - Bollinger Bands and other volatility indicators - Normalized price movements (z-scores)

Higher values indicate increased volatility and uncertainty.

Tip

Also available via DataFrame accessor: df.rhoa.indicators.ewmstd(window_size=20) which defaults to the Close column. See DataFrameIndicators.

Examples

Calculate exponentially weighted moving standard deviation:

>>> import pandas as pd
>>> import rhoa
>>> prices = pd.Series([100, 102, 99, 103, 105, 101, 106, 104])
>>> ewmstd = prices.rhoa.indicators.ewmstd(window_size=5)
>>> print(f"Latest volatility: {ewmstd.iloc[-1]:.2f}")
Latest volatility: 2.50

Use EWMSTD for volatility-adjusted position sizing:

>>> prices = pd.Series([100, 102, 104, 106, 108, 110, 112])
>>> volatility = prices.rhoa.indicators.ewmstd(window_size=10)
>>> position_size = 1000 / volatility  # Risk-adjusted sizing
rsi(window_size=14, edge_case_value=100.0, **kwargs)[source]

Calculate the Relative Strength Index (RSI) for momentum analysis.

RSI is a momentum oscillator that measures the speed and magnitude of price changes on a scale of 0 to 100. Developed by J. Welles Wilder Jr., it helps identify overbought and oversold conditions, as well as potential trend reversals. RSI is one of the most widely used technical indicators in trading.

Parameters:
  • window_size (int, default 14) – The size of the rolling window used to calculate the exponential moving averages of gains and losses. Traditional value is 14 periods as recommended by Wilder.

  • edge_case_value (float, default 100.0) – The RSI value to use when avg_loss == 0 (no losses occurred in the period). Common values are 100.0 (infinite RS, default), 50.0 (neutral), or numpy.nan.

  • **kwargs (dict) – Additional keyword arguments passed to pandas ewm function.

Returns:

A Series containing RSI values between 0 and 100 with the same index as the input series.

Return type:

pandas.Series

See also

stochastic

Similar momentum oscillator

cci

Commodity Channel Index for momentum

williams_r

Williams %R momentum indicator

macd

Moving Average Convergence Divergence

Notes

The Relative Strength Index is calculated using:

\[RSI = 100 - \frac{100}{1 + RS}\]

where \(RS = \frac{EMA(gains)}{EMA(losses)}\) and EMA is the exponential moving average over the specified window_size.

Traditional interpretation levels: - RSI > 70: Overbought condition (potential sell signal) - RSI < 30: Oversold condition (potential buy signal) - RSI = 50: Neutral momentum (balance between bulls and bears)

Key characteristics: - Range: 0 to 100 (bounded oscillator) - Mean-reverting: tends to oscillate around 50 - Leading indicator: can signal reversals before price - Works best in ranging markets (less reliable in strong trends)

Advanced RSI techniques: - Divergence: RSI diverging from price can signal reversals - Failure swings: RSI patterns that don’t confirm new price highs/lows - Centerline crossovers: RSI crossing 50 confirms trend direction - Dynamic thresholds: Use 80/20 in strong trends instead of 70/30

The first window_size values will be NaN as the indicator requires sufficient data to calculate the initial exponential moving averages.

References

Tip

Also available via DataFrame accessor: df.rhoa.indicators.rsi(window_size=14) which defaults to the Close column. See DataFrameIndicators.

Examples

Calculate 14-period RSI and identify trading signals:

>>> import pandas as pd
>>> import rhoa
>>> prices = pd.Series([100, 102, 104, 103, 105, 107, 106, 108, 110, 109])
>>> rsi = prices.rhoa.indicators.rsi(window_size=14)
>>> overbought = rsi > 70  # Potential sell signals
>>> oversold = rsi < 30   # Potential buy signals
>>> print(f"Latest RSI: {rsi.iloc[-1]:.1f}")
Latest RSI: 75.2

Detect RSI divergence for reversal signals:

>>> prices = pd.Series([100, 105, 110, 115, 120, 118, 116, 114])
>>> rsi = prices.rhoa.indicators.rsi()
>>> # Bearish divergence: price makes new high but RSI doesn't
>>> price_higher = prices > prices.shift(1).rolling(5).max()
>>> rsi_lower = rsi < rsi.shift(1).rolling(5).max()
>>> divergence = price_higher & rsi_lower
macd(short_window=12, long_window=26, signal_window=9, **kwargs)[source]

Calculate the MACD (Moving Average Convergence Divergence) indicator.

MACD is a trend-following momentum indicator that shows the relationship between two exponential moving averages of a security’s price. Developed by Gerald Appel, it consists of three components that together provide insights into trend direction, momentum strength, and potential reversals.

Parameters:
  • short_window (int, default 12) – Length of the short-term (fast) EMA window in periods. Smaller values make MACD more responsive to recent price changes.

  • long_window (int, default 26) – Length of the long-term (slow) EMA window in periods. Larger values provide more smoothing and stability.

  • signal_window (int, default 9) – Length of the signal line EMA window in periods. This smooths the MACD line to generate trading signals.

  • **kwargs (dict) – Additional keyword arguments passed to pandas ewm function.

Returns:

A DataFrame with three columns: - ‘macd’ : The MACD line (short_ema - long_ema) - ‘signal’ : The signal line (EMA of MACD line) - ‘histogram’ : The MACD histogram (macd - signal)

Return type:

pandas.DataFrame

See also

ewma

Exponential Weighted Moving Average

rsi

Relative Strength Index for momentum

stochastic

Stochastic Oscillator for momentum

Notes

The MACD indicator components are calculated as:

\[MACD_{line} = EMA_{short} - EMA_{long}\]
\[Signal_{line} = EMA_{signal}(MACD_{line})\]
\[Histogram = MACD_{line} - Signal_{line}\]

Traditional interpretation: - MACD line crosses above signal: Bullish signal (buy) - MACD line crosses below signal: Bearish signal (sell) - Histogram > 0: MACD above signal (bullish momentum) - Histogram < 0: MACD below signal (bearish momentum) - Histogram expanding: Momentum increasing - Histogram contracting: Momentum decreasing

Key characteristics: - Unbounded oscillator (can take any value) - Combines trend-following and momentum aspects - Three signals: crossovers, divergences, and rapid rises/falls - Works best in trending markets

Advanced MACD techniques: - Divergence: MACD diverging from price signals potential reversals - Zero-line crossovers: MACD crossing zero indicates trend change - Histogram analysis: Momentum changes before MACD line crosses - Multiple timeframe confirmation

The standard parameters (12, 26, 9) were optimized for daily charts but can be adjusted for different timeframes or market characteristics.

References

Tip

Also available via DataFrame accessor: df.rhoa.indicators.macd() which defaults to the Close column. See DataFrameIndicators.

Examples

Calculate MACD and identify bullish crossover:

>>> import pandas as pd
>>> import rhoa
>>> prices = pd.Series([100, 102, 104, 103, 105, 107, 106, 108, 110])
>>> macd_data = prices.rhoa.indicators.macd()
>>> # Bullish signal: MACD crosses above signal
>>> bullish = (macd_data['macd'] > macd_data['signal']) &         ...           (macd_data['macd'].shift(1) <= macd_data['signal'].shift(1))
>>> print(f"MACD: {macd_data['macd'].iloc[-1]:.3f}")
MACD: 0.245

Analyze MACD histogram for momentum changes:

>>> macd_data = prices.rhoa.indicators.macd()
>>> histogram = macd_data['histogram']
>>> momentum_increasing = histogram > histogram.shift(1)
>>> momentum_peak = (histogram.shift(1) > histogram) & (histogram.shift(1) > histogram.shift(2))
bollinger_bands(window_size=20, num_std=2.0, min_periods=None, center=False, **kwargs)[source]

Calculate Bollinger Bands for volatility and mean reversion analysis.

Bollinger Bands consist of three lines: an upper band, middle band (SMA), and lower band. Developed by John Bollinger, the bands expand and contract based on market volatility, providing insights into potential overbought/ oversold conditions, volatility patterns, and mean reversion opportunities.

Parameters:
  • window_size (int, default 20) – The size of the rolling window used for computing the moving average and standard deviation. Standard setting is 20 periods.

  • num_std (float, default 2.0) – The number of standard deviations to add/subtract from the moving average to calculate the upper and lower bands. Standard setting is 2.0.

  • min_periods (int, optional) – Minimum number of observations in window required to have a value. If None, defaults to window_size.

  • center (bool, default False) – Whether to set the labels at the center of the window.

  • **kwargs (dict) – Additional keyword arguments passed to pandas rolling function.

Returns:

A DataFrame with three columns: - ‘upper_band’ : Upper Bollinger Band (middle + num_std * std) - ‘middle_band’ : Middle band (SMA of the series) - ‘lower_band’ : Lower Bollinger Band (middle - num_std * std)

Return type:

pandas.DataFrame

See also

sma

Simple Moving Average (middle band)

ewmstd

Exponential Weighted Standard Deviation

atr

Average True Range for volatility

Notes

Bollinger Bands are calculated using:

\[Middle_{band} = SMA(price, window)\]
\[Upper_{band} = Middle_{band} + (num\_std \times \sigma)\]
\[Lower_{band} = Middle_{band} - (num\_std \times \sigma)\]

where \(\sigma\) is the standard deviation over the window.

Traditional interpretation: - Price touching upper band: Potentially overbought (high relative price) - Price touching lower band: Potentially oversold (low relative price) - Price between bands: Normal trading range - Band width: Measure of volatility

Key characteristics: - Approximately 95% of price action occurs within 2 standard deviations - Bands are dynamic support/resistance levels - Band width reflects market volatility - Works as both a trend and volatility indicator

Common Bollinger Band strategies: - Squeeze: Narrow bands indicate low volatility, often precedes breakout - Expansion: Wide bands indicate high volatility - Band walk: Price riding upper/lower band indicates strong trend - Bollinger Bounce: Mean reversion trades off band touches - %B indicator: (price - lower) / (upper - lower) shows relative position

Advanced techniques: - Double tops/bottoms at bands for reversal signals - M-tops and W-bottoms for patterns - Band width as volatility indicator - Combination with other indicators for confirmation

References

Tip

Also available via DataFrame accessor: df.rhoa.indicators.bollinger_bands(window_size=20) which defaults to the Close column. See DataFrameIndicators.

Examples

Calculate Bollinger Bands and identify squeeze conditions:

>>> import pandas as pd
>>> import rhoa
>>> prices = pd.Series([100, 102, 101, 103, 105, 104, 106, 108, 107])
>>> bb = prices.rhoa.indicators.bollinger_bands(window_size=5, num_std=2.0)
>>> # Band width indicates volatility
>>> width = bb['upper_band'] - bb['lower_band']
>>> squeeze = width < width.rolling(10).mean() * 0.8  # Low volatility
>>> print(f"Upper: {bb['upper_band'].iloc[-1]:.2f}")
Upper: 109.45

Calculate %B indicator for position within bands:

>>> bb = prices.rhoa.indicators.bollinger_bands()
>>> percent_b = (prices - bb['lower_band']) / (bb['upper_band'] - bb['lower_band'])
>>> overbought = percent_b > 1.0  # Price above upper band
>>> oversold = percent_b < 0.0    # Price below lower band