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.
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:
>>> importpandasaspd>>> importrhoa>>> 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 value102.2
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.
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.
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.
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.
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.
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:
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.
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:
>>> 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
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.
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)
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.
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)
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: