diff --git a/.gitignore b/.gitignore index 5f04fe62..3e5901fe 100644 --- a/.gitignore +++ b/.gitignore @@ -36,8 +36,9 @@ bld/ *.coverage *.coveragexml -# NDepend (entire directory — tooling + generated output) -ndepend/ +# NDepend generated output (analysis results + coverage data) +ndepend/NDependOut/ +ndepend/coverage/ # BenchmarkDotNet BenchmarkDotNet.Artifacts/ @@ -110,3 +111,12 @@ $null # Local secrets .secrets + +# Temp utility scripts (not shipped) +NOT +_fix_bullets.ps1 +_indicator_md_list.txt +affected_files.txt +fix-bullets.ps1 +fix_bullets.py +fix_read.py diff --git a/_sidebar.md b/_sidebar.md index 3fdb5bbe..aa324cf5 100644 --- a/_sidebar.md +++ b/_sidebar.md @@ -1,3 +1,5 @@ +* [**All indicators**](/lib/_index.md) + * [Core](/lib/core/_index.md) * [AVGPRICE - Average Price](/lib/core/avgprice/Avgprice.md) * [HA - Heikin-Ashi](/lib/core/ha/Ha.md) diff --git a/lib/VERSION b/lib/VERSION index bbde4bee..120f5321 100644 --- a/lib/VERSION +++ b/lib/VERSION @@ -1 +1 @@ -0.8.5 \ No newline at end of file +0.8.6 \ No newline at end of file diff --git a/lib/_index.md b/lib/_index.md index 6a24a347..781a9dc2 100644 --- a/lib/_index.md +++ b/lib/_index.md @@ -1,29 +1,5 @@ # QuanTAlib Indicators -## Categories - -| Category | Count | Description | -| :----------------------------------- | :-----: | :----------------------------------------------- | -| [Core](core/_index.md) | 8 | Price transforms and fundamental building blocks | -| [Trends (FIR)](trends_FIR/_index.md) | 33 | Finite Impulse Response moving averages | -| [Trends (IIR)](trends_IIR/_index.md) | 36 | Infinite Impulse Response moving averages | -| [Filters](filters/_index.md) | 37 | Signal processing filters | -| [Oscillators](oscillators/_index.md) | 48 | Indicators that fluctuate around a center line | -| [Dynamics](dynamics/_index.md) | 21 | Trend strength and direction indicators | -| [Momentum](momentum/_index.md) | 19 | Momentum-based indicators | -| [Volatility](volatility/_index.md) | 26 | Volatility estimators and indicators | -| [Volume](volume/_index.md) | 27 | Volume-based indicators | -| [Statistics](statistics/_index.md) | 35 | Statistical measures and tests | -| [Channels](channels/_index.md) | 23 | Price channels and bands | -| [Cycles](cycles/_index.md) | 14 | Cycle analysis and signal processing | -| [Reversals](reversals/_index.md) | 12 | Pattern recognition and reversal detection | -| [Forecasts](forecasts/_index.md) | 1 | Predictive indicators | -| [Errors](errors/_index.md) | 26 | Error metrics and loss functions | -| [Numerics](numerics/_index.md) | 27 | Mathematical transformations | -| **Total** | **393** | | - -## All Indicators - | Indicator | Full Name | Category | | :--------------------------------------------------------- | :------------------------------------------------------------------------ | :----------- | | [ABERR](channels/aberr/Aberr.md) | Aberration Bands | Channels | diff --git a/lib/channels/aberr/aberr.md b/lib/channels/aberr/aberr.md index bdb00620..057224d5 100644 --- a/lib/channels/aberr/aberr.md +++ b/lib/channels/aberr/aberr.md @@ -12,11 +12,11 @@ | **Warmup** | `period` bars | | **PineScript** | [aberr.pine](aberr.pine) | -- ABERR measures price deviation from a central moving average using mean absolute deviation rather than standard deviation, producing dynamic bands ... -- Parameterized by `period`, `multiplier` (default 2.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- ABERR measures price deviation from a central moving average using mean absolute deviation rather than standard deviation, producing dynamic bands that are more robust to outliers than Bollinger Bands. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. +- **Similar indicators:** [BBands](../bbands/bbands.md) (standard deviation bands), [SDChannel](../sdchannel/sdchannel.md) (standard deviation channel), [STBands](../stbands/stbands.md) (Stoller bands using ATR). +- **Complementary indicators:** Pair with a momentum oscillator such as RSI or Stochastic to confirm overbought/oversold signals when price touches the bands; volume indicators help distinguish genuine breakouts from false band penetrations. +- **Trading note:** Because MAD ≈ 0.80σ, ABERR bands are tighter than equivalently-scaled Bollinger Bands and produce fewer false signals during fat-tailed moves like earnings gaps or flash crashes. ABERR measures price deviation from a central moving average using mean absolute deviation rather than standard deviation, producing dynamic bands that adapt to volatility while remaining robust against extreme outliers. Where Bollinger Bands amplify outliers through squaring (the $L^2$ norm), ABERR uses raw absolute differences (the $L^1$ norm), so bands respond to typical price behavior rather than the occasional spike that yanks everything sideways. For a 20-period window with a 2.0 multiplier, ABERR contains approximately 89% of normally-distributed price action, but its real advantage emerges with fat-tailed distributions where standard deviation overreacts to single-bar anomalies. diff --git a/lib/channels/accbands/accbands.md b/lib/channels/accbands/accbands.md index df19a406..df0cd2e7 100644 --- a/lib/channels/accbands/accbands.md +++ b/lib/channels/accbands/accbands.md @@ -13,9 +13,7 @@ | **PineScript** | [accbands.pine](accbands.pine) | - Acceleration Bands construct a volatility envelope using the intra-bar high-low range rather than close-to-close standard deviation, creating chann... -- Parameterized by `period`, `factor` (default 4.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BBands](../bbands/bbands.md), [KChannel](../kchannel/kchannel.md) | **Complementary:** ADX for trend strength | **Trading note:** Wider than Bollinger Bands; effective for breakout trading using high-low range volatility. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Acceleration Bands construct a volatility envelope using the intra-bar high-low range rather than close-to-close standard deviation, creating channels that accommodate the full price excursion of the underlying asset. Each bar's contribution to band width is normalized by price level ($w = (H-L)/(H+L)$), making the bands scale-invariant across instruments. Three independent Simple Moving Averages of the adjusted high, adjusted low, and close prices form the upper, lower, and middle bands respectively. Headley's original breakout rule declares a trend when price closes outside the bands for two consecutive bars. diff --git a/lib/channels/apchannel/apchannel.md b/lib/channels/apchannel/apchannel.md index 4783321f..08efef56 100644 --- a/lib/channels/apchannel/apchannel.md +++ b/lib/channels/apchannel/apchannel.md @@ -13,9 +13,7 @@ | **PineScript** | [apchannel.pine](apchannel.pine) | - APCHANNEL applies exponential smoothing independently to price highs and lows, creating a dynamic envelope that "remembers" significant extremes wh... -- Parameterized by `alpha` (default 0.2). -- Output range: Tracks input. -- Requires `⌈3/alpha⌉` bars (default 15) of warmup before first valid output (IsHot = true). +- **Similar:** [RegChannel](../regchannel/regchannel.md), [PChannel](../pchannel/pchannel.md) | **Complementary:** Volume for breakout confirmation | **Trading note:** Based on pivot points; useful for identifying median price paths and potential support/resistance. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. APCHANNEL applies exponential smoothing independently to price highs and lows, creating a dynamic envelope that "remembers" significant extremes while gradually fading their influence over time. Unlike rigid Donchian channels that drop price extremes abruptly when they exit the lookback window (the "cliff effect"), APCHANNEL decays them smoothly through leaky integration. The result is a channel with continuously sloping boundaries that responds to volatility without the discontinuous jumps that plague fixed-window approaches. The algorithm is $O(1)$ per bar with only two state variables and no buffers. diff --git a/lib/channels/apz/apz.md b/lib/channels/apz/apz.md index 32688c1a..a9b679d4 100644 --- a/lib/channels/apz/apz.md +++ b/lib/channels/apz/apz.md @@ -13,9 +13,7 @@ | **PineScript** | [apz.pine](apz.pine) | - APZ constructs a volatility-adaptive envelope using double-smoothed exponential moving averages with an aggressive smoothing factor derived from $\... -- Parameterized by `period`, `multiplier` (default 2.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BBands](../bbands/bbands.md), [KChannel](../kchannel/kchannel.md) | **Complementary:** RSI for overbought/oversold confirmation | **Trading note:** EMA-based deviation adapts faster than standard deviation bands; responsive to recent volatility changes. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. APZ constructs a volatility-adaptive envelope using double-smoothed exponential moving averages with an aggressive smoothing factor derived from $\sqrt{\text{period}}$, making it significantly faster than standard EMA-based channels. The center line is a double-EMA of price; the band width is a double-EMA of the high-low range, scaled by a multiplier. Designed specifically for mean-reversion trading in non-trending markets, APZ identifies overbought/oversold extremes where price is likely to reverse rather than continue. A closing price outside the zone signals an immediate overshoot, not a breakout. diff --git a/lib/channels/atrbands/atrbands.md b/lib/channels/atrbands/atrbands.md index 238b07dd..5101651a 100644 --- a/lib/channels/atrbands/atrbands.md +++ b/lib/channels/atrbands/atrbands.md @@ -13,9 +13,7 @@ | **PineScript** | [atrbands.pine](atrbands.pine) | - ATR Bands create a volatility-adaptive envelope by projecting Wilder's Average True Range above and below a central Simple Moving Average. -- Parameterized by `period`, `multiplier` (default 2.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [KChannel](../kchannel/kchannel.md), [STBands](../stbands/stbands.md) | **Complementary:** ADX to distinguish trend vs range | **Trading note:** Volatility-normalized symmetric bands using ATR; adapts to true volatility including gaps. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ATR Bands create a volatility-adaptive envelope by projecting Wilder's Average True Range above and below a central Simple Moving Average. Unlike fixed-percentage envelopes or standard-deviation bands, ATR Bands use True Range to measure volatility, making them robust for assets with gaps, pre-market moves, and 24/7 trading where the "hidden" volatility between bars is significant. The True Range captures the maximum of intra-bar range, gap-up distance, and gap-down distance, ensuring that overnight gaps contribute fully to band width even when the current bar's open-to-close range is narrow. diff --git a/lib/channels/bbands/bbands.md b/lib/channels/bbands/bbands.md index b1e1536c..da29056b 100644 --- a/lib/channels/bbands/bbands.md +++ b/lib/channels/bbands/bbands.md @@ -13,9 +13,7 @@ | **PineScript** | [bbands.pine](bbands.pine) | - Bollinger Bands construct a volatility-adaptive envelope around a Simple Moving Average using population standard deviation as the width measure. -- Parameterized by `period` (default defaultperiod), `multiplier` (default defaultmultiplier). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [KChannel](../kchannel/kchannel.md), [SDChannel](../sdchannel/sdchannel.md), [ABERR](../aberr/aberr.md) | **Complementary:** %B and BandWidth for squeeze detection; RSI for momentum confirmation | **Trading note:** Most widely used band indicator; 2s captures ~95% of normally-distributed data but markets exhibit fat tails. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Bollinger Bands construct a volatility-adaptive envelope around a Simple Moving Average using population standard deviation as the width measure. The bands expand during high-volatility periods and contract during consolidation, dynamically adapting to changing market conditions. Under Gaussian assumptions, $\pm 2\sigma$ contains approximately 95.4% of price action, but financial returns exhibit fat tails and volatility clustering, so the bands function more as a volatility-normalized reference frame than a strict probability envelope. The derived metrics %B (price position as a fraction of band width) and BandWidth (normalized band spread) extend the raw bands into a complete analytical toolkit. diff --git a/lib/channels/dchannel/dchannel.md b/lib/channels/dchannel/dchannel.md index 6d7a20c1..84f77b09 100644 --- a/lib/channels/dchannel/dchannel.md +++ b/lib/channels/dchannel/dchannel.md @@ -13,9 +13,7 @@ | **PineScript** | [dchannel.pine](dchannel.pine) | - Donchian Channels track the highest high and lowest low over a fixed lookback period, defining the absolute price boundaries within which an asset ... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [PChannel](../pchannel/pchannel.md), [UChannel](../uchannel/uchannel.md) | **Complementary:** Volume on breakouts; ATR for position sizing | **Trading note:** Pure price-based highest high/lowest low; used in the original Turtle Trading system. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Donchian Channels track the highest high and lowest low over a fixed lookback period, defining the absolute price boundaries within which an asset has traded. Unlike volatility-based bands that compute statistical dispersion, Donchian Channels represent actual historical extremes — the literal "price box." The implementation uses monotonic deques for $O(1)$ amortized sliding-window max/min, ensuring that computing a 500-period channel costs no more than a 20-period one. The midpoint of the upper and lower bands serves as a simple trend bias indicator. diff --git a/lib/channels/decaychannel/decaychannel.md b/lib/channels/decaychannel/decaychannel.md index 6002326e..0e9a3aca 100644 --- a/lib/channels/decaychannel/decaychannel.md +++ b/lib/channels/decaychannel/decaychannel.md @@ -13,9 +13,7 @@ | **PineScript** | [decaychannel.pine](decaychannel.pine) | - Decay Channel combines the absolute price boundaries of Donchian Channels with exponential decay toward the midpoint, creating an envelope that exp... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DChannel](../dchannel/dchannel.md), [PChannel](../pchannel/pchannel.md) | **Complementary:** Trend indicators like ADX | **Trading note:** Bands decay toward price when no new extremes form, reducing lag compared to traditional channels. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Decay Channel combines the absolute price boundaries of Donchian Channels with exponential decay toward the midpoint, creating an envelope that expands instantly on new volatility but contracts smoothly during consolidation. While Donchian Channels hold their width until an extreme exits the lookback window, Decay Channel allows the bands to "forget" old extremes over time using a half-life model. The period parameter serves as the half-life: after that many bars without a new extreme, the band has decayed 50% of the distance back toward center. The decayed values are always clamped within Donchian bounds, ensuring they never extrapolate beyond actual price history. diff --git a/lib/channels/fcb/fcb.md b/lib/channels/fcb/fcb.md index 35f31bec..3b0414d1 100644 --- a/lib/channels/fcb/fcb.md +++ b/lib/channels/fcb/fcb.md @@ -13,9 +13,7 @@ | **PineScript** | [fcb.pine](fcb.pine) | - Fractal Chaos Bands filter raw price action through Bill Williams' fractal detection logic, tracking the highest confirmed fractal high and lowest ... -- Parameterized by `period` (default 20). -- Output range: Tracks input. -- Requires `period + 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DChannel](../dchannel/dchannel.md), [PChannel](../pchannel/pchannel.md) | **Complementary:** Williams Fractals for additional confirmation | **Trading note:** Based on Bill Williams' fractal theory; bands update only on fractal pivots, creating a staircase pattern. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Fractal Chaos Bands filter raw price action through Bill Williams' fractal detection logic, tracking the highest confirmed fractal high and lowest confirmed fractal low over a lookback period. Unlike Donchian Channels which use every bar's high and low, FCB uses only structurally significant turning points — bars where the middle element of a 3-bar pattern is a local extremum. The result is a "cleaner" channel that ignores transient spikes and focuses on confirmed support and resistance levels. The bands tend to remain flat during trends and step discretely when new structural pivots form, making them useful for identifying genuine breakouts versus noise. diff --git a/lib/channels/jbands/jbands.md b/lib/channels/jbands/jbands.md index 6a2990b9..098e152c 100644 --- a/lib/channels/jbands/jbands.md +++ b/lib/channels/jbands/jbands.md @@ -13,9 +13,7 @@ | **PineScript** | [Jbands.pine](Jbands.pine) | - JBANDS expose the internal adaptive envelope mechanism of the Jurik Moving Average (JMA), producing asymmetric bands that snap instantly to new pri... -- Parameterized by `period`, `phase` (default 0). -- Output range: Tracks input. -- Requires `⌈20 + 80 × period^0.36⌉` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BBands](../bbands/bbands.md), [KChannel](../kchannel/kchannel.md) | **Complementary:** Momentum oscillators for reversal timing | **Trading note:** Uses JMA (Jurik Moving Average) as center line for smoother, lower-lag bands compared to standard Bollinger. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. JBANDS expose the internal adaptive envelope mechanism of the Jurik Moving Average (JMA), producing asymmetric bands that snap instantly to new price extremes and decay exponentially during consolidation. Unlike standard volatility bands (Bollinger, Keltner) which maintain symmetric width around a center line, JBANDS feature "snap-and-decay" hysteresis: expansion is instantaneous (plasticity), contraction is gradual (elasticity). The decay rate is dynamically modulated by a two-stage volatility estimator — a 10-bar SMA feeding a 128-bar trimmed mean — making the bands tight during quiet markets and expansive during trends. The center line is the full JMA: a 2-pole IIR filter with phase control and adaptive alpha. diff --git a/lib/channels/kchannel/kchannel.md b/lib/channels/kchannel/kchannel.md index d7fd1888..e399450a 100644 --- a/lib/channels/kchannel/kchannel.md +++ b/lib/channels/kchannel/kchannel.md @@ -13,9 +13,7 @@ | **PineScript** | [kchannel.pine](kchannel.pine) | - Keltner Channel constructs a volatility-adaptive envelope by projecting Average True Range above and below an Exponential Moving Average center line. -- Parameterized by `period` (default 20), `multiplier` (default 2.0). -- Output range: Tracks input. -- Requires `period * 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BBands](../bbands/bbands.md), [APZ](../apz/apz.md) | **Complementary:** Bollinger Band squeeze (BBands inside KChannel signals compression); MACD for trend direction | **Trading note:** ATR-based width adapts to true volatility including gaps; Chester Keltner's 1960 original used typical price and average range. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Keltner Channel constructs a volatility-adaptive envelope by projecting Average True Range above and below an Exponential Moving Average center line. The channel differs from ATR Bands solely in the center line: Keltner uses EMA (faster, more responsive) while ATR Bands use SMA (more stable, more lag). The EMA center combined with ATR width creates a channel that both tracks trend and adapts to volatility, making it one of the most widely used channel indicators for trend-following and mean-reversion strategies. The implementation uses EMA with warmup compensation for accurate early values and Wilder's smoothing (RMA) for ATR. diff --git a/lib/channels/maenv/maenv.md b/lib/channels/maenv/maenv.md index bfc68bbf..1e65df76 100644 --- a/lib/channels/maenv/maenv.md +++ b/lib/channels/maenv/maenv.md @@ -13,9 +13,7 @@ | **PineScript** | [maenv.pine](maenv.pine) | - Moving Average Envelope (MA Envelope) constructs symmetric bands at a fixed percentage distance above and below a moving average center line. -- Parameterized by `period` (default 20), `percentage` (default 1.0), `matype` (default maenvtype.ema). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BBands](../bbands/bbands.md), [APZ](../apz/apz.md) | **Complementary:** RSI at envelope extremes | **Trading note:** Fixed-percentage bands around a moving average; simplest channel indicator, useful as a baseline comparison. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Moving Average Envelope (MA Envelope) constructs symmetric bands at a fixed percentage distance above and below a moving average center line. Unlike volatility-adaptive channels (Bollinger, Keltner, ATR Bands) where band width varies with market conditions, MA Envelope uses a constant percentage offset, creating bands whose absolute width scales only with price level. The indicator supports configurable moving average types (SMA, EMA, WMA) for the center line, allowing users to trade off between lag, smoothness, and responsiveness. diff --git a/lib/channels/mmchannel/mmchannel.md b/lib/channels/mmchannel/mmchannel.md index cd5325a9..cf5683f1 100644 --- a/lib/channels/mmchannel/mmchannel.md +++ b/lib/channels/mmchannel/mmchannel.md @@ -13,9 +13,7 @@ | **PineScript** | [mmchannel.pine](mmchannel.pine) | - Min-Max Channel tracks the highest high and lowest low over a lookback period, creating a pure price envelope without any midpoint calculation. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DChannel](../dchannel/dchannel.md), [PChannel](../pchannel/pchannel.md) | **Complementary:** ATR for volatility context | **Trading note:** Min/Max channel; breakout system based on highest high and lowest low. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Min-Max Channel tracks the highest high and lowest low over a lookback period, creating a pure price envelope without any midpoint calculation. Unlike Donchian Channels which include a middle band, MMCHANNEL delivers only the raw extremes. The implementation uses monotonic deques for O(1) amortized updates: each element enters the deque once and leaves at most once, so total work over $N$ bars is $O(N)$ regardless of period length. diff --git a/lib/channels/pchannel/pchannel.md b/lib/channels/pchannel/pchannel.md index cb996a9e..a2da63b7 100644 --- a/lib/channels/pchannel/pchannel.md +++ b/lib/channels/pchannel/pchannel.md @@ -13,9 +13,7 @@ | **PineScript** | [pchannel.pine](pchannel.pine) | - Price Channel tracks the highest high and lowest low over a lookback period with a midpoint average, creating a three-line price envelope that defi... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DChannel](../dchannel/dchannel.md), [MMChannel](../mmchannel/mmchannel.md) | **Complementary:** Volume confirmation on breakouts | **Trading note:** Price channel based on percentage offset from midpoint. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Price Channel tracks the highest high and lowest low over a lookback period with a midpoint average, creating a three-line price envelope that defines where the market has been. Functionally identical to Donchian Channels, the indicator uses actual price extremes rather than volatility estimates, producing bands that represent real support and resistance levels. This implementation uses monotonic deques for O(1) amortized updates instead of the naive O(n) rescan that most platforms use internally. diff --git a/lib/channels/regchannel/regchannel.md b/lib/channels/regchannel/regchannel.md index d6855c5d..f0ccd735 100644 --- a/lib/channels/regchannel/regchannel.md +++ b/lib/channels/regchannel/regchannel.md @@ -13,9 +13,7 @@ | **PineScript** | [regchannel.pine](regchannel.pine) | - Linear Regression Channel plots a best-fit line through price data over a specified period with parallel bands at a configurable standard deviation... -- Parameterized by `period` (default 20), `multiplier` (default 2.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SDChannel](../sdchannel/sdchannel.md), [BBands](../bbands/bbands.md) | **Complementary:** R-squared for trend strength | **Trading note:** Linear regression channel; mean-reversion trades at band extremes. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Linear Regression Channel plots a best-fit line through price data over a specified period with parallel bands at a configurable standard deviation of residuals. Unlike moving average envelopes that offset from a smoothed price, regression channels adapt their slope to the underlying trend and their width to actual dispersion around that trend. The algorithm uses ordinary least squares with precomputed index sums, requiring two passes per bar: one for the regression coefficients and one for the residual standard deviation. diff --git a/lib/channels/sdchannel/sdchannel.md b/lib/channels/sdchannel/sdchannel.md index 7d9243da..61902375 100644 --- a/lib/channels/sdchannel/sdchannel.md +++ b/lib/channels/sdchannel/sdchannel.md @@ -13,9 +13,7 @@ | **PineScript** | [sdchannel.pine](sdchannel.pine) | - Standard Deviation Channel plots a linear regression line through price data with parallel bands at a specified number of standard deviations of re... -- Parameterized by `period` (default 20), `multiplier` (default 2.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BBands](../bbands/bbands.md), [RegChannel](../regchannel/regchannel.md) | **Complementary:** LinReg slope for trend direction | **Trading note:** Standard deviation channel around linear regression; tighter than Bollinger for trending markets. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Standard Deviation Channel plots a linear regression line through price data with parallel bands at a specified number of standard deviations of residuals above and below. Unlike Bollinger Bands which measure deviation from a moving average, SDCHANNEL measures deviation from the best-fit trend line, capturing how much price wanders from its underlying trajectory rather than from its simple average. The algorithm is identical to REGCHANNEL; the distinction is purely a naming convention found across different platforms and literature. diff --git a/lib/channels/starchannel/starchannel.md b/lib/channels/starchannel/starchannel.md index 435a79da..006246f0 100644 --- a/lib/channels/starchannel/starchannel.md +++ b/lib/channels/starchannel/starchannel.md @@ -13,9 +13,7 @@ | **PineScript** | [starchannel.pine](starchannel.pine) | - Stoller Average Range Channel creates a volatility-adaptive price envelope using Average True Range (ATR) to determine band width around a simple m... -- Parameterized by `period` (default 20), `multiplier` (default 2.0), `atrperiod` (default 0). -- Output range: Tracks input. -- Requires `Math.Max(period, effectiveAtrPeriod)` bars of warmup before first valid output (IsHot = true). +- **Similar:** [KChannel](../kchannel/kchannel.md), [ATRBands](../atrbands/atrbands.md) | **Complementary:** ADX for trend confirmation | **Trading note:** Stoller Average Range Channel; ATR-based bands around a moving average. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Stoller Average Range Channel creates a volatility-adaptive price envelope using Average True Range (ATR) to determine band width around a simple moving average centerline. The bands automatically expand during volatile periods and contract during calmer markets. The implementation uses a circular buffer for the SMA running sum and Wilder's RMA with a warmup compensator for ATR, achieving O(1) streaming updates per bar. diff --git a/lib/channels/stbands/stbands.md b/lib/channels/stbands/stbands.md index 86799bf2..8fd7007b 100644 --- a/lib/channels/stbands/stbands.md +++ b/lib/channels/stbands/stbands.md @@ -13,9 +13,7 @@ | **PineScript** | [stbands.pine](stbands.pine) | - Super Trend Bands provide ATR-based dynamic support and resistance levels with asymmetric ratchet logic: the upper band only tightens downward duri... -- Parameterized by `period` (default defaultperiod), `multiplier` (default defaultmultiplier). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BBands](../bbands/bbands.md), [KChannel](../kchannel/kchannel.md) | **Complementary:** Volume for breakout validation | **Trading note:** Stoller bands use ATR multiplier instead of standard deviation. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Super Trend Bands provide ATR-based dynamic support and resistance levels with asymmetric ratchet logic: the upper band only tightens downward during downtrends, and the lower band only tightens upward during uptrends. This creates natural trailing stop-loss levels that respect market momentum. A trend direction signal ($+1$ or $-1$) flips when price breaches the opposite band. The ATR is computed as a simple moving average of True Range via a ring buffer with running sum, providing O(1) streaming updates. diff --git a/lib/channels/ttm_lrc/TtmLrc.md b/lib/channels/ttm_lrc/TtmLrc.md index 416fc542..fde86acc 100644 --- a/lib/channels/ttm_lrc/TtmLrc.md +++ b/lib/channels/ttm_lrc/TtmLrc.md @@ -12,9 +12,6 @@ | **Warmup** | `period` bars | - TTM Linear Regression Channel plots a least-squares regression line through price data with dual standard deviation bands at $\pm 1\sigma$ and $\pm... -- Parameterized by `period` (default 100). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. TTM Linear Regression Channel plots a least-squares regression line through price data with dual standard deviation bands at $\pm 1\sigma$ and $\pm 2\sigma$. Developed by John Carter as part of his TTM (Trade The Markets) indicator suite, it extends the standard regression channel by providing two band levels that create statistically meaningful trading zones. The algorithm is identical to REGCHANNEL/SDCHANNEL in its regression and residual computation, but uses a longer default period (100) and emits four bands instead of two. @@ -139,4 +136,4 @@ Both passes iterate over contiguous ring buffer memory, enabling SIMD vectorizat - Carter, J. (2005). *Mastering the Trade*. McGraw-Hill. - Raff, G. (1991). "Trading the Regression Channel." *Technical Analysis of Stocks & Commodities*. -- Draper, N. & Smith, H. (1998). *Applied Regression Analysis*. Wiley. +- Draper, N. & Smith, H. (1998). *Applied Regression Analysis*. Wiley. \ No newline at end of file diff --git a/lib/channels/ubands/ubands.md b/lib/channels/ubands/ubands.md index 56ff5c2a..24a37785 100644 --- a/lib/channels/ubands/ubands.md +++ b/lib/channels/ubands/ubands.md @@ -13,9 +13,7 @@ | **PineScript** | [ubands.pine](ubands.pine) | - Ehlers Ultimate Bands replace the conventional SMA foundation of Bollinger Bands with the Ultrasmooth Filter (USF), a 2-pole IIR filter with zero o... -- Parameterized by `period` (default defaultperiod), `multiplier` (default defaultmultiplier). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BBands](../bbands/bbands.md), [SDChannel](../sdchannel/sdchannel.md) | **Complementary:** RSI for overbought/oversold | **Trading note:** Uncertainty bands; statistical confidence intervals around a moving average. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Ehlers Ultimate Bands replace the conventional SMA foundation of Bollinger Bands with the Ultrasmooth Filter (USF), a 2-pole IIR filter with zero overshoot and minimal lag. Band width is determined by the RMS (Root Mean Square) of residuals between price and the smoothed centerline, providing a mathematically rigorous deviation measure that makes no assumptions about the distribution of returns. The USF is a recursive filter requiring O(1) computation per bar, while the RMS calculation scans the lookback window at O(n) per bar. diff --git a/lib/channels/uchannel/uchannel.md b/lib/channels/uchannel/uchannel.md index d1b7a284..bf5fd245 100644 --- a/lib/channels/uchannel/uchannel.md +++ b/lib/channels/uchannel/uchannel.md @@ -13,9 +13,7 @@ | **PineScript** | [uchannel.pine](uchannel.pine) | - Ehlers Ultimate Channel applies the Ultrasmooth Filter (USF) twice: once to the close price for the centerline and once to True Range for band widt... -- Parameterized by `strperiod` (default defaultstrperiod), `centerperiod` (default defaultcenterperiod), `multiplier` (default defaultmultiplier). -- Output range: Tracks input. -- Requires `Math.Max(strPeriod, centerPeriod)` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DChannel](../dchannel/dchannel.md), [PChannel](../pchannel/pchannel.md) | **Complementary:** Volume for breakout confirmation | **Trading note:** Upper/lower channel based on recent price extremes. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Ehlers Ultimate Channel applies the Ultrasmooth Filter (USF) twice: once to the close price for the centerline and once to True Range for band width, creating a channel where both the trend estimate and the volatility measure share the same low-lag, zero-overshoot filter characteristics. Unlike UBANDS which uses RMS of price residuals, UCHANNEL uses Smoothed True Range (STR) for band width, making it responsive to gap-inclusive volatility. Separate period parameters allow independent tuning of centerline smoothness and band-width responsiveness. diff --git a/lib/channels/vwapbands/vwapbands.md b/lib/channels/vwapbands/vwapbands.md index f25dd38b..7139c937 100644 --- a/lib/channels/vwapbands/vwapbands.md +++ b/lib/channels/vwapbands/vwapbands.md @@ -13,9 +13,7 @@ | **PineScript** | [vwapbands.pine](vwapbands.pine) | - VWAP Bands extend the Volume Weighted Average Price with dual standard deviation bands at $\pm 1\sigma$ and $\pm 2\sigma$ levels, creating a five-l... -- Parameterized by `multiplier` (default defaultmultiplier). -- Output range: Tracks input. -- Requires `2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [VwapSD](../vwapsd/vwapsd.md), [BBands](../bbands/bbands.md) | **Complementary:** Volume profile | **Trading note:** VWAP with deviation bands; institutional benchmark for intraday fair value. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. VWAP Bands extend the Volume Weighted Average Price with dual standard deviation bands at $\pm 1\sigma$ and $\pm 2\sigma$ levels, creating a five-line channel system anchored to volume-weighted fair value. Three running sums (cumulative price×volume, cumulative volume, cumulative price²×volume) enable O(1) streaming updates per bar. A session reset mechanism clears accumulations at configurable intervals, keeping the indicator anchored to current market structure. diff --git a/lib/channels/vwapsd/vwapsd.md b/lib/channels/vwapsd/vwapsd.md index 5b011de5..7f8fb57c 100644 --- a/lib/channels/vwapsd/vwapsd.md +++ b/lib/channels/vwapsd/vwapsd.md @@ -13,9 +13,7 @@ | **PineScript** | [vwapsd.pine](vwapsd.pine) | - VWAP with Standard Deviation Bands combines the Volume Weighted Average Price with a single configurable standard deviation band pair, providing a ... -- Parameterized by `numdevs` (default defaultnumdevs). -- Output range: Tracks input. -- Requires `2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [VwapBands](../vwapbands/vwapbands.md), [BBands](../bbands/bbands.md) | **Complementary:** Cumulative volume delta | **Trading note:** VWAP standard deviation bands; 1σ/2σ/3σ levels used for institutional mean-reversion. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. VWAP with Standard Deviation Bands combines the Volume Weighted Average Price with a single configurable standard deviation band pair, providing a simpler alternative to VWAPBANDS (which uses dual $\pm 1\sigma$ and $\pm 2\sigma$ levels). Three running sums enable O(1) streaming updates. A session reset mechanism clears accumulations at configurable intervals, keeping the indicator anchored to current market structure. The configurable deviation parameter allows traders to select their desired confidence level ($1\sigma$ ≈ 68%, $2\sigma$ ≈ 95%, $3\sigma$ ≈ 99.7%). diff --git a/lib/core/avgprice/Avgprice.md b/lib/core/avgprice/Avgprice.md index 296f687a..3637b630 100644 --- a/lib/core/avgprice/Avgprice.md +++ b/lib/core/avgprice/Avgprice.md @@ -14,8 +14,6 @@ - AVGPRICE computes the arithmetic mean of a bar's four canonical prices: Open, High, Low, and Close. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `1` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. AVGPRICE computes the arithmetic mean of a bar's four canonical prices: Open, High, Low, and Close. The formula $\frac{O + H + L + C}{4}$ produces a single representative price that weights all four price components equally, unlike Typical Price (which excludes Open) or Weighted Close (which double-weights Close). This equal weighting makes AVGPRICE the least biased single-bar summary statistic, useful as a neutral input to downstream indicators when no particular price component deserves emphasis. The calculation is stateless, requires no warmup, and costs a single FMA instruction per bar. @@ -96,4 +94,4 @@ $O(1)$ per bar. Two additions, one FMA. No memory allocation. Always hot after t ## Resources - **TA-Lib** `TA_AVGPRICE` function reference. -- **Murphy, J.J.** *Technical Analysis of the Financial Markets*. New York Institute of Finance, 1999. +- **Murphy, J.J.** *Technical Analysis of the Financial Markets*. New York Institute of Finance, 1999. \ No newline at end of file diff --git a/lib/core/ha/Ha.md b/lib/core/ha/Ha.md index f07371d9..9a17c575 100644 --- a/lib/core/ha/Ha.md +++ b/lib/core/ha/Ha.md @@ -14,8 +14,6 @@ - HA transforms standard OHLC bars into smoothed Heikin-Ashi candles by averaging each component with its predecessor. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `1` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HA transforms standard OHLC bars into smoothed Heikin-Ashi candles by averaging each component with its predecessor. The Close is the bar's four-price mean $(O+H+L+C)/4$, the Open is a recursive midpoint of the prior HA Open and HA Close, and High/Low are clamped extremes that guarantee the HA body always fits inside the HA wick. Unlike most indicators that reduce a bar to a single scalar, HA outputs a complete `TBar` — four smoothed prices per bar — making it a bar-to-bar transform rather than a bar-to-value reduction. The recursive Open gives HA an IIR character: each bar carries a decaying memory of the entire price history, which is what flattens trend noise but also why HA prices do not match any actual traded price. @@ -202,4 +200,4 @@ Validated against external libraries in `Ha.Validation.Tests.cs`. HA is widely i - **Valcu, D.** (2004). "Using The Heikin-Ashi Technique." *Technical Analysis of Stocks & Commodities*, Vol. 22, No. 2. - **Nison, S.** (1991). *Japanese Candlestick Charting Techniques*. New York Institute of Finance. - **Vervoort, S.** (2008). "Smoothing Heikin-Ashi." *Technical Analysis of Stocks & Commodities*. -- [Investopedia: Heikin-Ashi](https://www.investopedia.com/terms/h/heikinashi.asp) — accessible introduction to the technique and its trading applications. +- [Investopedia: Heikin-Ashi](https://www.investopedia.com/terms/h/heikinashi.asp) — accessible introduction to the technique and its trading applications. \ No newline at end of file diff --git a/lib/core/medprice/Medprice.md b/lib/core/medprice/Medprice.md index 735b1813..2939dcef 100644 --- a/lib/core/medprice/Medprice.md +++ b/lib/core/medprice/Medprice.md @@ -14,8 +14,6 @@ - MEDPRICE computes the midpoint of a bar's High and Low: $(H + L) \times 0.5$. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `1` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. MEDPRICE computes the midpoint of a bar's High and Low: $(H + L) \times 0.5$. This is the simplest possible estimate of a bar's "fair value," splitting the difference between the session's extremes while ignoring both the opening gap and closing settlement. The result represents the geometric center of the bar's vertical range. Because it excludes Open and Close, MEDPRICE responds purely to the supply/demand boundaries that the market tested, making it a useful input for range-based indicators like CCI or as a detrending reference. Stateless, zero-warmup, one addition and one multiply per bar. @@ -95,4 +93,4 @@ $O(1)$ per bar. One addition, one multiply. No memory allocation. Always hot aft ## Resources - **TA-Lib** `TA_MEDPRICE` function reference. -- **Murphy, J.J.** *Technical Analysis of the Financial Markets*. New York Institute of Finance, 1999. +- **Murphy, J.J.** *Technical Analysis of the Financial Markets*. New York Institute of Finance, 1999. \ No newline at end of file diff --git a/lib/core/midpoint/Midpoint.md b/lib/core/midpoint/Midpoint.md index f8283ac0..0a897210 100644 --- a/lib/core/midpoint/Midpoint.md +++ b/lib/core/midpoint/Midpoint.md @@ -13,9 +13,7 @@ | **PineScript** | [midpoint.pine](midpoint.pine) | - Single-series rolling midpoint: `(Highest(V, N) + Lowest(V, N)) * 0.5`. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MidPrice](../midprice/Midprice.md), [Midbody](../midbody/Midbody.md) | **Trading note:** (Highest+Lowest)/2 over period; simple support/resistance level. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Single-series rolling midpoint: `(Highest(V, N) + Lowest(V, N)) * 0.5`. Returns the center of the value range within a lookback window. TA-Lib compatible (`MIDPOINT` function). Unlike MIDPRICE which operates on separate High/Low bar channels, MIDPOINT operates on a single value series. @@ -108,4 +106,4 @@ The span-based `Batch` method uses a single `RingBuffer` with linear scan for ma ## References - TA-Lib `MIDPOINT` function documentation -- Murphy, J. *Technical Analysis of the Financial Markets* (range-based indicators) +- Murphy, J. *Technical Analysis of the Financial Markets* (range-based indicators) \ No newline at end of file diff --git a/lib/core/midprice/Midprice.md b/lib/core/midprice/Midprice.md index bb5b7d35..dadf7576 100644 --- a/lib/core/midprice/Midprice.md +++ b/lib/core/midprice/Midprice.md @@ -13,9 +13,7 @@ | **PineScript** | [midprice.pine](midprice.pine) | - MIDPRICE computes the center of a rolling price channel by averaging the highest High and lowest Low over the past $N$ bars: $(\text{Highest}(H, N)... -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MidPoint](../midpoint/Midpoint.md), [TypPrice](../typprice/typprice.md) | **Trading note:** (High+Low)/2; common price proxy for indicators avoiding close bias. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. MIDPRICE computes the center of a rolling price channel by averaging the highest High and lowest Low over the past $N$ bars: $(\text{Highest}(H, N) + \text{Lowest}(L, N)) \times 0.5$. Unlike the stateless price transforms (AVGPRICE, MEDPRICE, TYPPRICE, WCLPRICE) that operate on a single bar, MIDPRICE maintains a lookback window and produces a rolling estimate of the price range's midpoint. This makes it a simplified channel center line, equivalent to the midpoint of a Donchian Channel. The calculation uses two internal RingBuffers for $O(N)$ max/min computation per bar. TA-Lib compatible via `TA_MIDPRICE`. @@ -116,4 +114,4 @@ A monotonic deque (sliding window max/min) would reduce per-bar cost from $O(N)$ - **TA-Lib** `TA_MIDPRICE` function reference. - **Donchian, R.** "High Finance in Copper." *Financial Analysts Journal*, 1960. (Origin of channel-based price analysis) -- **Achelis, S.B.** *Technical Analysis from A to Z*. McGraw-Hill, 2000. +- **Achelis, S.B.** *Technical Analysis from A to Z*. McGraw-Hill, 2000. \ No newline at end of file diff --git a/lib/core/simd/SimdExtensions.md b/lib/core/simd/SimdExtensions.md index 9a2cbc56..3a2a1167 100644 --- a/lib/core/simd/SimdExtensions.md +++ b/lib/core/simd/SimdExtensions.md @@ -11,8 +11,6 @@ - `SimdExtensions` provides high-performance, SIMD-accelerated extension methods for `ReadOnlySpan`. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. `SimdExtensions` provides high-performance, SIMD-accelerated extension methods for `ReadOnlySpan`. It leverages .NET's `Vector` to achieve 4-8x speedups on supported hardware (AVX2, AVX-512) while automatically falling back to scalar implementations on older hardware. @@ -64,4 +62,4 @@ bool hasInvalid = span.ContainsNonFinite(); // Calculate dot product double dot = span.DotProduct(otherSpan); -``` +``` \ No newline at end of file diff --git a/lib/core/tbar/TBar.md b/lib/core/tbar/TBar.md index acf04f3d..10172b36 100644 --- a/lib/core/tbar/TBar.md +++ b/lib/core/tbar/TBar.md @@ -11,8 +11,6 @@ - `TBar` is a lightweight, immutable struct representing a single OHLCV (Open, High, Low, Close, Volume) bar. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## What It Does @@ -137,4 +135,4 @@ TBar is a 48-byte struct (DateTime + 5 doubles). Field access and construction a ## References * [OHLC Chart](https://en.wikipedia.org/wiki/Open-high-low-close_chart) -* [C# Record Structs](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record) +* [C# Record Structs](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record) \ No newline at end of file diff --git a/lib/core/tbarseries/TBarSeries.md b/lib/core/tbarseries/TBarSeries.md index 6b62ebe7..c191352c 100644 --- a/lib/core/tbarseries/TBarSeries.md +++ b/lib/core/tbarseries/TBarSeries.md @@ -11,8 +11,6 @@ - `TBarSeries` is a high-performance collection of OHLCV bars. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## What It Does @@ -146,4 +144,4 @@ SoA layout enables SIMD processing: each field array is contiguous in memory. Co ## References * [Structure of Arrays (SoA)](https://en.wikipedia.org/wiki/AOS_and_SOA) -* [Data Locality](https://gameprogrammingpatterns.com/data-locality.html) +* [Data Locality](https://gameprogrammingpatterns.com/data-locality.html) \ No newline at end of file diff --git a/lib/core/tseries/TSeries.md b/lib/core/tseries/TSeries.md index ebfeb143..c0493d55 100644 --- a/lib/core/tseries/TSeries.md +++ b/lib/core/tseries/TSeries.md @@ -11,8 +11,6 @@ - `TSeries` is a high-performance, memory-efficient container for time-series data. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## What It Does @@ -140,4 +138,4 @@ The Pub/Sub dispatch dominates practical throughput when multiple subscribers ar ## References * [Data-Oriented Design](https://en.wikipedia.org/wiki/Data-oriented_design) -* [SIMD in .NET](https://learn.microsoft.com/en-us/dotnet/standard/simd) +* [SIMD in .NET](https://learn.microsoft.com/en-us/dotnet/standard/simd) \ No newline at end of file diff --git a/lib/core/tvalue/TValue.md b/lib/core/tvalue/TValue.md index 4a2997f1..a566a1ac 100644 --- a/lib/core/tvalue/TValue.md +++ b/lib/core/tvalue/TValue.md @@ -11,8 +11,6 @@ - `TValue` is the fundamental atomic unit of data in QuanTAlib. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## What It Does @@ -131,4 +129,4 @@ TValue is a 16-byte struct (DateTime + double). Construction and field access ar ## References * [Structure of Arrays (SoA)](https://en.wikipedia.org/wiki/AOS_and_SOA) -* [C# Struct Performance](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct) +* [C# Struct Performance](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct) \ No newline at end of file diff --git a/lib/core/typprice/Typprice.md b/lib/core/typprice/Typprice.md index c763bd47..6b7c1940 100644 --- a/lib/core/typprice/Typprice.md +++ b/lib/core/typprice/Typprice.md @@ -14,8 +14,6 @@ - TYPPRICE computes the equal-weighted average of Open, High, and Low: $(O + H + L) \times \frac{1}{3}$. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `1` bars of warmup before first valid output (IsHot = true). - Equivalent to `TBar.OHL3` computed property. TYPPRICE computes the equal-weighted average of Open, High, and Low: $(O + H + L) \times \frac{1}{3}$. This three-component mean captures the opening price and the full intra-bar range without including the settlement (Close). By excluding Close, Typical Price isolates the session's initial positioning and range extremes, making it useful as an input where you want a price representative that is independent of closing action. The calculation is stateless and costs a single FMA instruction per bar. @@ -92,4 +90,4 @@ Division by a non-power-of-two constant is 4-5x more expensive than multiplicati ## Resources -- **QuanTAlib** `TBar.OHL3` computed property reference. +- **QuanTAlib** `TBar.OHL3` computed property reference. \ No newline at end of file diff --git a/lib/core/wclprice/Wclprice.md b/lib/core/wclprice/Wclprice.md index e7f76e5b..c5f99e4a 100644 --- a/lib/core/wclprice/Wclprice.md +++ b/lib/core/wclprice/Wclprice.md @@ -14,8 +14,6 @@ - WCLPRICE computes a Close-biased average of High, Low, and Close by double-weighting the closing price: $(H + L + 2C) \times 0.25$. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `1` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. WCLPRICE computes a Close-biased average of High, Low, and Close by double-weighting the closing price: $(H + L + 2C) \times 0.25$. This gives Close 50% of the total weight versus 25% each for High and Low, reflecting the widely held belief that the closing price is the most important price of the bar because it represents the final consensus of buyers and sellers. The calculation is stateless, costs a single FMA instruction per bar, and is TA-Lib compatible (`TA_WCLPRICE`). @@ -100,4 +98,4 @@ $O(1)$ per bar. One addition, one FMA. No memory allocation. Always hot after th ## Resources - **TA-Lib** `TA_WCLPRICE` function reference. -- **Achelis, S.B.** *Technical Analysis from A to Z*. McGraw-Hill, 2000. (Weighted Close definition) +- **Achelis, S.B.** *Technical Analysis from A to Z*. McGraw-Hill, 2000. (Weighted Close definition) \ No newline at end of file diff --git a/lib/cycles/ccor/Ccor.md b/lib/cycles/ccor/Ccor.md index fa61e1f2..402e2d96 100644 --- a/lib/cycles/ccor/Ccor.md +++ b/lib/cycles/ccor/Ccor.md @@ -13,9 +13,7 @@ | **PineScript** | [ccor.pine](ccor.pine) | - CCOR extracts cycle phase by computing Pearson correlation of a price window against cosine (Real) and negative-sine (Imaginary) reference waves of... -- Parameterized by `period` (default 20), `threshold` (default 9.0). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Ccyc](../ccyc/Ccyc.md), [CG](../cg/cg.md) | **Complementary:** Hilbert Transform for phase analysis | **Trading note:** Cycle correlation; detects dominant cycle period in price data. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. CCOR extracts cycle phase by computing Pearson correlation of a price window against cosine (Real) and negative-sine (Imaginary) reference waves of a presumed fixed period, converting the resulting phasor to an angle with a monotonic constraint, and classifying the market state as trending or cycling based on the angle rate of change. Unlike Hilbert Transform approaches that rely on analytic signal construction, CCOR uses the statistical machinery of correlation to measure how well price "fits" each quadrature component, yielding bounded $[-1, +1]$ outputs that double as confidence measures. The method was introduced to address the instability of Hilbert-based phasors during trend-dominated regimes. @@ -136,4 +134,4 @@ For default period $N = 20$: ~269 cycles per bar. The O(N) cost comes from dual - **Ehlers, J.F.** "Correlation As A Cycle Indicator." *Technical Analysis of Stocks & Commodities*, June 2020. - **Ehlers, J.F.** *Rocket Science for Traders*. Wiley, 2001. (Hilbert Transform phasor predecessor) - **Ehlers, J.F.** *Cybernetic Analysis for Stocks and Futures*. Wiley, 2004. (Broader cycle analysis framework) -- **Pearson, K.** "Notes on Regression and Inheritance in the Case of Two Parents." *Proceedings of the Royal Society of London*, 58, 1895. (Original Pearson correlation) +- **Pearson, K.** "Notes on Regression and Inheritance in the Case of Two Parents." *Proceedings of the Royal Society of London*, 58, 1895. (Original Pearson correlation) \ No newline at end of file diff --git a/lib/cycles/ccyc/Ccyc.md b/lib/cycles/ccyc/Ccyc.md index 4e64a4b2..01bbce4b 100644 --- a/lib/cycles/ccyc/Ccyc.md +++ b/lib/cycles/ccyc/Ccyc.md @@ -13,9 +13,7 @@ | **PineScript** | [ccyc.pine](ccyc.pine) | - CCYC isolates the dominant cycle component from price data using a 2-pole high-pass IIR filter applied to a 4-tap FIR-smoothed input, producing an ... -- Parameterized by `alpha` (default 0.07). -- Output range: Varies (see docs). -- Requires `7` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Ccor](../ccor/Ccor.md), [CG](../cg/cg.md) | **Complementary:** EBSW for trend/cycle mode | **Trading note:** Cyber Cycle; Ehlers' bandpass approach to isolate dominant market cycles. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. CCYC isolates the dominant cycle component from price data using a 2-pole high-pass IIR filter applied to a 4-tap FIR-smoothed input, producing an oscillator that strips trend while preserving cyclical content with minimal lag. The companion trigger line (one-bar delay of the cycle output) provides crossover signals for timing entries and exits. Unlike band-pass approaches that require specifying a center frequency, CCYC's high-pass architecture extracts whatever cyclic energy exists above a cutoff controlled by a single $\alpha$ damping parameter, making it adaptive to the dominant period present in the data. @@ -152,4 +150,4 @@ O(1) per bar. The 4-tap FIR smoother uses 3 MUL + 2 ADD; the 2-pole IIR high-pas - **Ehlers, J.F.** *Rocket Science for Traders*. Wiley, 2001. (Foundational DSP framework for markets) - **Ehlers, J.F.** "Cybernetic Analysis." *Technical Analysis of Stocks & Commodities*, 2004. - **Wiener, N.** *Cybernetics: Or Control and Communication in the Animal and the Machine*. MIT Press, 1948. (Origin of the "cybernetic" terminology) -- **Oppenheim, A.V. & Schafer, R.W.** *Discrete-Time Signal Processing*. Pearson, 2009. (IIR filter theory, z-domain analysis) +- **Oppenheim, A.V. & Schafer, R.W.** *Discrete-Time Signal Processing*. Pearson, 2009. (IIR filter theory, z-domain analysis) \ No newline at end of file diff --git a/lib/cycles/cg/cg.md b/lib/cycles/cg/cg.md index 1f7ee02a..f2f53116 100644 --- a/lib/cycles/cg/cg.md +++ b/lib/cycles/cg/cg.md @@ -13,9 +13,7 @@ | **PineScript** | [cg.pine](cg.pine) | - CG identifies potential turning points using the physics concept of weighted center of mass applied to a price window. -- Parameterized by `period` (default 10). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Ccyc](../ccyc/Ccyc.md), [EACP](../eacp/eacp.md) | **Complementary:** RSI for momentum confirmation | **Trading note:** Center of Gravity oscillator by Ehlers; leads price turns with minimal lag. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. CG identifies potential turning points using the physics concept of weighted center of mass applied to a price window. Developed by John Ehlers, the oscillator measures where the "weight" of prices is concentrated within a lookback period, producing a leading indicator that oscillates around zero with minimal lag compared to traditional moving average crossover systems. diff --git a/lib/cycles/dsp/dsp.md b/lib/cycles/dsp/dsp.md index 8e024042..8d5c27db 100644 --- a/lib/cycles/dsp/dsp.md +++ b/lib/cycles/dsp/dsp.md @@ -13,9 +13,7 @@ | **PineScript** | [dsp.pine](dsp.pine) | - DSP creates a zero-centered oscillator by subtracting a half-cycle EMA from a quarter-cycle EMA, isolating the dominant cyclical component of price... -- Parameterized by `period` (default 40). -- Output range: Varies (see docs). -- Requires `slowPeriod * 3` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SSFDSP](../ssfdsp/Ssfdsp.md), [Ccyc](../ccyc/Ccyc.md) | **Complementary:** ATR for volatility filter | **Trading note:** Digital Signal Processing filter; separates signal from noise in price data. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. DSP creates a zero-centered oscillator by subtracting a half-cycle EMA from a quarter-cycle EMA, isolating the dominant cyclical component of price while cancelling longer-term trends. Developed by John Ehlers, the indicator is grounded in cycle theory rather than arbitrary period selection, making it a principled alternative to MACD for cycle-aware trading. Bias-corrected EMAs ensure accurate amplitude during warmup. diff --git a/lib/cycles/eacp/eacp.md b/lib/cycles/eacp/eacp.md index 3efda665..6675dc4b 100644 --- a/lib/cycles/eacp/eacp.md +++ b/lib/cycles/eacp/eacp.md @@ -13,9 +13,7 @@ | **PineScript** | [eacp.pine](eacp.pine) | - EACP estimates the dominant cycle period of a financial time series by computing autocorrelation across multiple lags and transforming the result i... -- Parameterized by `minperiod` (default 8), `maxperiod` (default 48), `avglength` (default 3), `enhance` (default true). -- Output range: Varies (see docs). -- Requires `maxPeriod * 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [CG](../cg/cg.md), [HT_DCPeriod](../ht_dcperiod/ht_dcperiod.md) | **Complementary:** EBSW for trend/cycle classification | **Trading note:** Ehlers Autocorrelation Periodogram; identifies dominant cycle length adaptively. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. EACP estimates the dominant cycle period of a financial time series by computing autocorrelation across multiple lags and transforming the result into a power spectrum via the Wiener-Khinchin theorem. The output is a continuously updating cycle period measurement (in bars) that can adaptively tune other indicators to the market's current rhythm, making fixed-period assumptions unnecessary. diff --git a/lib/cycles/ebsw/ebsw.md b/lib/cycles/ebsw/ebsw.md index aae7a6a3..42fdac53 100644 --- a/lib/cycles/ebsw/ebsw.md +++ b/lib/cycles/ebsw/ebsw.md @@ -13,9 +13,7 @@ | **PineScript** | [ebsw.pine](ebsw.pine) | - EBSW is a refined cycle oscillator that combines a high-pass filter (trend removal), a Super-Smoother filter (noise removal), and Automatic Gain Co... -- Parameterized by `hplength` (default 40), `ssflength` (default 10). -- Output range: Varies (see docs). -- Requires `Math.Max(hpLength, ssfLength) + 3` bars (default 43) of warmup before first valid output (IsHot = true). +- **Similar:** [HT_TrendMode](../../dynamics/ht_trendmode/ht_trendmode.md), [VHF](../../dynamics/vhf/Vhf.md) | **Complementary:** ADX for trend strength | **Trading note:** Even Better Sine Wave; classifies market as trending or cycling. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. EBSW is a refined cycle oscillator that combines a high-pass filter (trend removal), a Super-Smoother filter (noise removal), and Automatic Gain Control to produce a normalized $[-1, +1]$ output representing the current position within the dominant market cycle. Developed by John Ehlers as an improvement over the original Hilbert Transform SineWave, it provides cleaner turning point detection without requiring complex phase extraction mathematics. diff --git a/lib/cycles/homod/homod.md b/lib/cycles/homod/homod.md index 91692bfe..100a7ba1 100644 --- a/lib/cycles/homod/homod.md +++ b/lib/cycles/homod/homod.md @@ -13,9 +13,7 @@ | **PineScript** | [homod.pine](homod.pine) | - HOMOD estimates the dominant cycle period of a market using homodyne mixing, a technique from radio engineering where a signal is multiplied by a d... -- Parameterized by `minperiod` (default 6.0), `maxperiod` (default 50.0). -- Output range: Varies (see docs). -- Requires `maxPeriod * 2` bars (default 100) of warmup before first valid output (IsHot = true). +- **Similar:** [HT_Phasor](../ht_phasor/ht_phasor.md), [HT_Sine](../ht_sine/ht_sine.md) | **Complementary:** Cycle period for context | **Trading note:** Homodyne discriminator; Ehlers' phase detection for cycle turning points. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HOMOD estimates the dominant cycle period of a market using homodyne mixing, a technique from radio engineering where a signal is multiplied by a delayed copy of itself to expose the angular phase change between samples. The output is a continuously varying period measurement (in bars) that tracks the market's instantaneous cycle length, enabling adaptive indicator tuning. Developed by John Ehlers, it offers better noise rejection and stability than the raw Hilbert Transform period estimator. diff --git a/lib/cycles/ht_dcperiod/HtDcperiod.md b/lib/cycles/ht_dcperiod/HtDcperiod.md index ceede2c9..1fc24c89 100644 --- a/lib/cycles/ht_dcperiod/HtDcperiod.md +++ b/lib/cycles/ht_dcperiod/HtDcperiod.md @@ -14,8 +14,6 @@ - HT_DCPERIOD estimates the period of the dominant market cycle using Ehlers' Hilbert Transform cascade. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `LOOKBACK` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HT_DCPERIOD estimates the period of the dominant market cycle using Ehlers' Hilbert Transform cascade. The algorithm extracts In-Phase and Quadrature components from price, computes instantaneous phase via homodyne discrimination, and derives the period from the phase rate of change. Output is a continuously varying period (typically 6-50 bars) compatible with TA-Lib's `HT_DCPERIOD` function. The indicator enables dynamic tuning of other indicators to the market's actual rhythm rather than fixed-parameter assumptions. @@ -112,4 +110,4 @@ The period range [6, 50] and all smoothing constants are fixed by the TA-Lib spe - **Ehlers, J.F.** *Rocket Science for Traders*. Wiley, 2001. - **TA-Lib** `TA_HT_DCPERIOD()` reference implementation. -- **Ehlers, J.F.** *Cybernetic Analysis for Stocks and Futures*. Wiley, 2004. +- **Ehlers, J.F.** *Cybernetic Analysis for Stocks and Futures*. Wiley, 2004. \ No newline at end of file diff --git a/lib/cycles/ht_dcphase/HtDcphase.md b/lib/cycles/ht_dcphase/HtDcphase.md index f0dd6407..8ad2c93b 100644 --- a/lib/cycles/ht_dcphase/HtDcphase.md +++ b/lib/cycles/ht_dcphase/HtDcphase.md @@ -14,8 +14,6 @@ - HT_DCPHASE measures the instantaneous phase angle of the dominant market cycle using Ehlers' Hilbert Transform cascade. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `LOOKBACK` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HT_DCPHASE measures the instantaneous phase angle of the dominant market cycle using Ehlers' Hilbert Transform cascade. The output ranges from $-45°$ to $315°$, with phase discontinuities at cycle completions marking the transition from one cycle to the next. Compatible with TA-Lib's `HT_DCPHASE` function, the indicator enables cycle-position timing for entries and exits based on where price currently sits within the dominant cycle. @@ -114,4 +112,4 @@ All internal constants are fixed by the TA-Lib specification. - **Ehlers, J.F.** *Rocket Science for Traders*. Wiley, 2001. - **TA-Lib** `TA_HT_DCPHASE()` reference implementation. - **Ehlers, J.F.** *Cybernetic Analysis for Stocks and Futures*. Wiley, 2004. -- **Hilbert, D.** *Grundzüge einer allgemeinen Theorie der linearen Integralgleichungen*. Teubner, 1912. +- **Hilbert, D.** *Grundzüge einer allgemeinen Theorie der linearen Integralgleichungen*. Teubner, 1912. \ No newline at end of file diff --git a/lib/cycles/ht_phasor/HtPhasor.md b/lib/cycles/ht_phasor/HtPhasor.md index 3668450a..0250c2e7 100644 --- a/lib/cycles/ht_phasor/HtPhasor.md +++ b/lib/cycles/ht_phasor/HtPhasor.md @@ -14,8 +14,6 @@ - HT_PHASOR decomposes the price signal into two orthogonal components, InPhase ($I$) and Quadrature ($Q$), using the Hilbert Transform. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `LOOKBACK` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HT_PHASOR decomposes the price signal into two orthogonal components, InPhase ($I$) and Quadrature ($Q$), using the Hilbert Transform. Together these form a complex phasor $Z = I + jQ$ that describes the instantaneous amplitude and phase of the dominant market cycle. Compatible with TA-Lib's `HT_PHASOR` function, this dual-output indicator provides the fundamental building blocks for cycle analysis, phasor crossover timing, and instantaneous amplitude measurement. @@ -105,4 +103,4 @@ $O(1)$ per bar. Fixed Hilbert cascade with circular buffers. Warmup: 32 bars (TA - **Ehlers, J.F.** *Rocket Science for Traders*. Wiley, 2001. - **TA-Lib** `TA_HT_PHASOR()` reference implementation. -- **Ehlers, J.F.** *Cybernetic Analysis for Stocks and Futures*. Wiley, 2004. +- **Ehlers, J.F.** *Cybernetic Analysis for Stocks and Futures*. Wiley, 2004. \ No newline at end of file diff --git a/lib/cycles/ht_sine/HtSine.md b/lib/cycles/ht_sine/HtSine.md index 582d17cb..affebc4f 100644 --- a/lib/cycles/ht_sine/HtSine.md +++ b/lib/cycles/ht_sine/HtSine.md @@ -14,8 +14,6 @@ - HT_SINE extracts the dominant market cycle phase and outputs both Sine and LeadSine (45° phase advance) for cycle timing. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `LOOKBACK` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HT_SINE extracts the dominant market cycle phase and outputs both Sine and LeadSine (45° phase advance) for cycle timing. The crossover of these two waves identifies turning points in ranging markets up to one-eighth of a cycle early. Compatible with TA-Lib's `HT_SINE` function, the indicator builds on the full Hilbert Transform cascade (phasor extraction, homodyne period estimation, DFT phase accumulation) to produce dual bounded $[-1, +1]$ oscillators that track cycle position rather than price amplitude. @@ -119,4 +117,4 @@ All constants are fixed by the TA-Lib specification. - **Ehlers, J.F.** *Rocket Science for Traders*. Wiley, 2001. - **TA-Lib** `TA_HT_SINE()` reference implementation. - **Ehlers, J.F.** *Cybernetic Analysis for Stocks and Futures*. Wiley, 2004. -- **Hilbert, D.** *Grundzüge einer allgemeinen Theorie der linearen Integralgleichungen*. Teubner, 1912. +- **Hilbert, D.** *Grundzüge einer allgemeinen Theorie der linearen Integralgleichungen*. Teubner, 1912. \ No newline at end of file diff --git a/lib/cycles/lunar/Lunar.md b/lib/cycles/lunar/Lunar.md index 76db6131..737c1587 100644 --- a/lib/cycles/lunar/Lunar.md +++ b/lib/cycles/lunar/Lunar.md @@ -14,8 +14,6 @@ - LUNAR calculates the Moon's illumination fraction using precise orbital mechanics from Jean Meeus' *Astronomical Algorithms*. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `0` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. LUNAR calculates the Moon's illumination fraction using precise orbital mechanics from Jean Meeus' *Astronomical Algorithms*. Output ranges from 0.0 (New Moon) through 0.5 (Quarter) to 1.0 (Full Moon), providing a continuous astronomical cycle for research into potential lunar-correlated market behavior. The indicator is purely time-based, requires no price data, and has zero warmup since the calculation is deterministic from any timestamp. @@ -126,4 +124,4 @@ The calculation is entirely determined by the input timestamp. - **Meeus, J.** *Astronomical Algorithms*. 2nd ed., Willmann-Bell, 1998. - **Dichev, I.D. & Janes, T.D.** "Lunar Cycle Effects in Stock Returns." *Journal of Private Equity*, 2001. -- **Yuan, K., Zheng, L. & Zhu, Q.** "Are Investors Moonstruck? Lunar Phases and Stock Returns." *Journal of Empirical Finance*, 2006. +- **Yuan, K., Zheng, L. & Zhu, Q.** "Are Investors Moonstruck? Lunar Phases and Stock Returns." *Journal of Empirical Finance*, 2006. \ No newline at end of file diff --git a/lib/cycles/solar/Solar.md b/lib/cycles/solar/Solar.md index 853e262b..25c0f334 100644 --- a/lib/cycles/solar/Solar.md +++ b/lib/cycles/solar/Solar.md @@ -14,8 +14,6 @@ - SOLAR models Earth's seasonal position relative to the Sun using astronomical ephemeris calculations. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `0` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. SOLAR models Earth's seasonal position relative to the Sun using astronomical ephemeris calculations. Output oscillates continuously from $-1.0$ (Winter Solstice) through $0.0$ (Equinoxes) to $+1.0$ (Summer Solstice), providing a smooth, mathematically precise seasonal phase for econometric modeling. Like LUNAR, the indicator is purely time-based, requires no price data, and has zero warmup since the calculation is deterministic from any timestamp. @@ -123,4 +121,4 @@ The calculation is entirely determined by the input timestamp. ## Resources - **Meeus, J.** *Astronomical Algorithms*. 2nd ed., Willmann-Bell, 1998. -- **USNO** *Astronomical Almanac*. U.S. Government Publishing Office (annual reference for solstice/equinox verification). +- **USNO** *Astronomical Almanac*. U.S. Government Publishing Office (annual reference for solstice/equinox verification). \ No newline at end of file diff --git a/lib/cycles/ssfdsp/Ssfdsp.md b/lib/cycles/ssfdsp/Ssfdsp.md index dccf2d92..36ef593e 100644 --- a/lib/cycles/ssfdsp/Ssfdsp.md +++ b/lib/cycles/ssfdsp/Ssfdsp.md @@ -13,9 +13,7 @@ | **PineScript** | [ssfdsp.pine](ssfdsp.pine) | - SSFDSP isolates the dominant cycle by subtracting a half-cycle Super-Smoother from a quarter-cycle Super-Smoother, producing a zero-centered oscill... -- Parameterized by `period` (default 40). -- Output range: Varies (see docs). -- Requires `slowPeriod * 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DSP](../dsp/dsp.md), [SSF2](../../filters/ssf2/Ssf2.md) | **Complementary:** Roofing filter for preprocessing | **Trading note:** Super Smoother with DSP; combines Ehlers' smoothing with signal processing. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. SSFDSP isolates the dominant cycle by subtracting a half-cycle Super-Smoother from a quarter-cycle Super-Smoother, producing a zero-centered oscillator with superior noise rejection compared to the EMA-based DSP. The 2-pole Butterworth characteristic of the Super-Smoother filter provides zero phase lag at the cutoff frequency and sharper rolloff than exponential smoothing, making SSFDSP the preferred variant for cycle-aware trading when the approximate dominant period is known. @@ -119,4 +117,4 @@ The SSF has $-3$ dB attenuation at the cutoff period, $-12$ dB/octave rolloff (2 - **Ehlers, J.F.** *Cybernetic Analysis for Stocks and Futures*. Wiley, 2004. - **Ehlers, J.F.** *Cycle Analytics for Traders*. Wiley, 2013. -- **Butterworth, S.** "On the Theory of Filter Amplifiers." *Experimental Wireless*, 7, 1930. +- **Butterworth, S.** "On the Theory of Filter Amplifiers." *Experimental Wireless*, 7, 1930. \ No newline at end of file diff --git a/lib/dynamics/adx/Adx.md b/lib/dynamics/adx/Adx.md index a6424274..50aae4e3 100644 --- a/lib/dynamics/adx/Adx.md +++ b/lib/dynamics/adx/Adx.md @@ -13,9 +13,7 @@ | **PineScript** | [adx.pine](adx.pine) | - The Average Directional Index is the industry-standard measure of trend strength, ignoring direction entirely to focus on the velocity of price exp... -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period * 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ADXR](../adxr/Adxr.md), [DX](../dx/Dx.md) | **Complementary:** Moving averages for direction | **Trading note:** Wilder's trend strength gauge; >25 trending, <20 ranging. Does not indicate direction. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Average Directional Index is the industry-standard measure of trend strength, ignoring direction entirely to focus on the velocity of price expansion. Wilder's pipeline decomposes range into directional movement (+DM, -DM), normalizes against True Range to produce directional indicators (+DI, -DI), derives a directional index (DX) from their ratio, then smooths DX with a final RMA pass. The double-smoothed architecture creates significant lag but exceptional noise rejection, making ADX a regime filter rather than a timing tool. Output is unbounded above 0, with readings above 25 conventionally indicating trending conditions and below 20 indicating choppy markets. @@ -143,4 +141,4 @@ The recursive RMA passes block SIMD across bars. The TR/DM initial computation ( ## Resources - Wilder, J.W. — *New Concepts in Technical Trading Systems* (Trend Research, 1978) -- PineScript reference: `adx.pine` in indicator directory +- PineScript reference: `adx.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/adxr/Adxr.md b/lib/dynamics/adxr/Adxr.md index c4e2f45e..6c2b5e0b 100644 --- a/lib/dynamics/adxr/Adxr.md +++ b/lib/dynamics/adxr/Adxr.md @@ -13,9 +13,7 @@ | **PineScript** | [adxr.pine](adxr.pine) | - The Average Directional Movement Rating is a smoothed version of ADX that dampens short-term fluctuations in trend strength by averaging the curren... -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `adx.WarmupPeriod + period - 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ADX](../adx/Adx.md), [DX](../dx/Dx.md) | **Complementary:** Aroon for trend timing | **Trading note:** Smoothed ADX; slower but fewer false signals. Used in Wilder's Directional Movement System. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Average Directional Movement Rating is a smoothed version of ADX that dampens short-term fluctuations in trend strength by averaging the current ADX with a historical ADX value. This creates a doubly-lagged metric that sacrifices all timing utility in exchange for stable regime classification. ADXR answers one question: does the current market environment reward trend-following strategies? If ADXR is high, deploy momentum logic. If low, deploy mean-reversion. It is a strategic filter, not a tactical signal. @@ -116,4 +114,4 @@ The final averaging step is trivially vectorizable once the ADX time series is m ## Resources - Wilder, J.W. — *New Concepts in Technical Trading Systems* (Trend Research, 1978) -- PineScript reference: `adxr.pine` in indicator directory +- PineScript reference: `adxr.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/alligator/Alligator.md b/lib/dynamics/alligator/Alligator.md index 0e5069bd..3cd61f0a 100644 --- a/lib/dynamics/alligator/Alligator.md +++ b/lib/dynamics/alligator/Alligator.md @@ -13,9 +13,7 @@ | **PineScript** | [alligator.pine](alligator.pine) | - The Williams Alligator is a trend-following system that uses three Smoothed Moving Averages (SMMA/RMA) with different periods and forward display o... -- Parameterized by `jawperiod`, `jawoffset`, `teethperiod`, `teethoffset`, `lipsperiod`, `lipsoffset`. -- Output range: Varies (see docs). -- Requires `Math.Max(Math.Max(jawPeriod, teethPeriod), lipsPeriod)` bars of warmup before first valid output (IsHot = true). +- **Similar:** [AMAT](../amat/Amat.md), [Ichimoku](../ichimoku/Ichimoku.md) | **Complementary:** Fractal indicator for entry signals | **Trading note:** Bill Williams' Alligator; three displaced SMAs (Jaw/Teeth/Lips) indicate trend state. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Williams Alligator is a trend-following system that uses three Smoothed Moving Averages (SMMA/RMA) with different periods and forward display offsets to visualize market phases. The Jaw (13-period, offset 8), Teeth (8-period, offset 5), and Lips (5-period, offset 3) create a layered structure where intertwined lines indicate consolidation ("sleeping") and separated, aligned lines indicate trending conditions ("eating"). The metaphor maps directly to position management: stay out when the alligator sleeps, ride when it eats. Each line uses Wilder's smoothing ($\alpha = 1/N$), which is heavier than standard EMA, providing superior noise rejection at the cost of additional lag. @@ -131,4 +129,4 @@ Three independent recursive streams. No cross-stream dependencies, but each stre - Williams, B. — *Trading Chaos* (John Wiley & Sons, 1995) - Williams, B. — *New Trading Dimensions* (John Wiley & Sons, 1998) -- PineScript reference: `alligator.pine` in indicator directory +- PineScript reference: `alligator.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/amat/Amat.md b/lib/dynamics/amat/Amat.md index b7f954b1..cbe0fe1c 100644 --- a/lib/dynamics/amat/Amat.md +++ b/lib/dynamics/amat/Amat.md @@ -13,9 +13,7 @@ | **PineScript** | [amat.pine](amat.pine) | - The Archer Moving Averages Trends indicator is a triple-confirmation trend identification system that uses dual EMAs to produce discrete directiona... -- Parameterized by `fastperiod` (default 10), `slowperiod` (default 50). -- Output range: Varies (see docs). -- Requires `slowPeriod` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Alligator](../alligator/Alligator.md), [Ichimoku](../ichimoku/Ichimoku.md) | **Complementary:** ADX for trend strength | **Trading note:** Archer Moving Average Trend; uses MA crossover zones to classify trend phases. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Archer Moving Averages Trends indicator is a triple-confirmation trend identification system that uses dual EMAs to produce discrete directional signals (+1 bullish, -1 bearish, 0 neutral). Unlike simple crossover systems that trigger on any intersection, AMAT requires alignment of three conditions: relative position (fast above/below slow), fast EMA direction (rising/falling), and slow EMA direction (rising/falling). This triple gate filters out the whipsaw endemic to single-condition crossover systems in ranging markets. A secondary output quantifies trend strength as the percentage separation between EMAs, providing a conviction metric for position sizing. @@ -121,4 +119,4 @@ Both EMA passes are recursive and sequential. The final comparison step is trivi ## Resources - Joseph, T. — AMAT trend confirmation methodology (2009) -- PineScript reference: `amat.pine` in indicator directory +- PineScript reference: `amat.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/aroon/Aroon.md b/lib/dynamics/aroon/Aroon.md index fb199573..36537663 100644 --- a/lib/dynamics/aroon/Aroon.md +++ b/lib/dynamics/aroon/Aroon.md @@ -13,9 +13,7 @@ | **PineScript** | [aroon.pine](aroon.pine) | - The Aroon indicator measures the temporal freshness of price extremes, answering not "how much did price move?" but "how long ago did it make a new... -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [AroonOsc](../aroonosc/AroonOsc.md), [ADX](../adx/Adx.md) | **Complementary:** Volume for confirmation | **Trading note:** Aroon Up/Down measures time since highest high or lowest low; 100 = new high/low this period. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Aroon indicator measures the temporal freshness of price extremes, answering not "how much did price move?" but "how long ago did it make a new high or low?" Aroon Up tracks the recency of the highest high within the lookback window; Aroon Down tracks the recency of the lowest low. Both are normalized to 0-100 where 100 means the extreme occurred on the current bar and 0 means it occurred at the far edge of the window. A companion Aroon Oscillator (Up minus Down) provides a single zero-centered metric for trend bias. Unlike recursive indicators that accumulate floating-point drift, Aroon is purely windowed — its value depends only on data within the lookback period, making it immune to initialization artifacts. @@ -120,4 +118,4 @@ Batch mode with SIMD prefix-max/min and horizontal ArgMax achieves ~4× throughp - Chande, T.S. — *Beyond Technical Analysis* (John Wiley & Sons, 1995) - Chande, T.S. — *The New Technical Trader* (John Wiley & Sons, 1995) -- PineScript reference: `aroon.pine` in indicator directory +- PineScript reference: `aroon.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/aroonosc/AroonOsc.md b/lib/dynamics/aroonosc/AroonOsc.md index d1d2426a..8ea773ab 100644 --- a/lib/dynamics/aroonosc/AroonOsc.md +++ b/lib/dynamics/aroonosc/AroonOsc.md @@ -13,9 +13,7 @@ | **PineScript** | [aroonosc.pine](aroonosc.pine) | - The Aroon Oscillator condenses the dual-line Aroon system into a single zero-centered value by computing $\text{AroonUp} - \text{AroonDown}$. -- Parameterized by `period`. -- Output range: $-100$ to $+100$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Aroon](../aroon/Aroon.md), [CMO](../../momentum/cmo/Cmo.md) | **Complementary:** ADX for trend strength | **Trading note:** Aroon Up minus Aroon Down; positive = uptrend, negative = downtrend. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Aroon Oscillator condenses the dual-line Aroon system into a single zero-centered value by computing $\text{AroonUp} - \text{AroonDown}$. This distills the temporal battle between fresh highs and fresh lows into a bounded $[-100, +100]$ metric where positive values indicate bullish recency dominance and negative values indicate bearish. Unlike recursive indicators that accumulate floating-point drift, the Aroon Oscillator is purely windowed — its value depends only on data within the lookback period, making it stateless in the long term and immune to initialization poisoning. The step-function output reflects discrete events (new extremes appearing or aging out) rather than smooth price trajectories. @@ -114,4 +112,4 @@ Trivially parallelizable subtraction step after Aroon computation. - Chande, T.S. — *The New Technical Trader* (John Wiley & Sons, 1995) - Chande, T.S. — *Beyond Technical Analysis* (John Wiley & Sons, 1995) -- PineScript reference: `aroonosc.pine` in indicator directory +- PineScript reference: `aroonosc.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/chop/Chop.md b/lib/dynamics/chop/Chop.md index 27896b61..5f5fb310 100644 --- a/lib/dynamics/chop/Chop.md +++ b/lib/dynamics/chop/Chop.md @@ -13,9 +13,7 @@ | **PineScript** | [chop.pine](chop.pine) | - The Choppiness Index is a non-directional regime indicator that measures whether the market is trending or trading sideways. -- Parameterized by `period` (default 14). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ADX](../adx/Adx.md), [VHF](../vhf/Vhf.md) | **Complementary:** BBands for range boundaries | **Trading note:** Choppiness Index; high values = choppy/ranging, low values = trending. Range 0–100. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Choppiness Index is a non-directional regime indicator that measures whether the market is trending or trading sideways. It compares total price movement (sum of True Range) to net price movement (high-low channel width) using a logarithmic ratio, producing a bounded value where high readings indicate choppy/consolidating conditions and low readings indicate trending conditions. CHOP does not indicate direction — only whether directional strategies are likely to succeed. The logarithmic scaling normalizes the output to approximately 0-100 regardless of price level or volatility magnitude. @@ -120,4 +118,4 @@ With AVX2 and Intel SVML for vectorized log, batch mode achieves ~3× throughput ## Resources - Dreiss, E.W. — Choppiness Index (original development) -- PineScript reference: `chop.pine` in indicator directory +- PineScript reference: `chop.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/dmx/Dmx.md b/lib/dynamics/dmx/Dmx.md index 96251ad2..5a2078eb 100644 --- a/lib/dynamics/dmx/Dmx.md +++ b/lib/dynamics/dmx/Dmx.md @@ -13,9 +13,7 @@ | **PineScript** | [dmx.pine](dmx.pine) | - The DMX is Mark Jurik's modernized overhaul of Wilder's Directional Movement system, replacing the sluggish RMA smoothing with the Jurik Moving Ave... -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ADX](../adx/Adx.md), [DX](../dx/Dx.md) | **Complementary:** +DI/-DI for direction | **Trading note:** Directional Movement extended; enhanced version of Wilder's DM system. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The DMX is Mark Jurik's modernized overhaul of Wilder's Directional Movement system, replacing the sluggish RMA smoothing with the Jurik Moving Average (JMA) to achieve faster trend detection with superior noise rejection. The core directional movement logic (+DM, -DM, True Range) is preserved faithfully from Wilder, but the three parallel smoothing passes use JMA's adaptive bandwidth instead of RMA's fixed $\alpha = 1/N$. The result is a directional indicator that reacts 3-5 bars earlier to trend changes than standard DMI while filtering out more noise during consolidation. Output is the difference between smoothed directional indicators: $DMX = DI^+ - DI^-$, positive for uptrends and negative for downtrends. @@ -131,4 +129,4 @@ Same constraint as ADX: the recursive RMA smoothing blocks cross-bar SIMD. - Wilder, J.W. — *New Concepts in Technical Trading Systems* (Trend Research, 1978) - Jurik, M. — JMA adaptive smoothing methodology -- PineScript reference: `dmx.pine` in indicator directory +- PineScript reference: `dmx.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/dx/Dx.md b/lib/dynamics/dx/Dx.md index 140ed80f..9a698cbf 100644 --- a/lib/dynamics/dx/Dx.md +++ b/lib/dynamics/dx/Dx.md @@ -13,9 +13,7 @@ | **PineScript** | [dx.pine](dx.pine) | - The Directional Movement Index is the raw, unsmoothed measure of trend strength from Wilder's directional movement system. -- Parameterized by `period` (default 14). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ADX](../adx/Adx.md), [ADXR](../adxr/Adxr.md) | **Complementary:** +DI/-DI for direction | **Trading note:** Directional Index; unsmoothed ADX. More responsive but noisier. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Directional Movement Index is the raw, unsmoothed measure of trend strength from Wilder's directional movement system. It decomposes price expansion into +DM and -DM, normalizes against True Range using RMA smoothing to produce +DI and -DI, then computes the ratio $DX = 100 \times |{+DI - {-DI}}| / ({+DI + {-DI}})$. Unlike ADX, which applies a final RMA pass to DX, the raw DX responds immediately to changes in directional dominance — making it noisier but approximately one full period faster. Output ranges from 0 to 100, where high values indicate strong directional movement regardless of up/down direction. DX is the building block from which ADX is derived. @@ -139,4 +137,4 @@ Same RMA bottleneck as ADX. The DX formula itself is fully vectorizable. ## Resources - Wilder, J.W. — *New Concepts in Technical Trading Systems* (Trend Research, 1978) -- PineScript reference: `dx.pine` in indicator directory +- PineScript reference: `dx.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/ghla/Ghla.md b/lib/dynamics/ghla/Ghla.md index 91445d9c..50e842ab 100644 --- a/lib/dynamics/ghla/Ghla.md +++ b/lib/dynamics/ghla/Ghla.md @@ -13,9 +13,7 @@ | **PineScript** | [ghla.pine](ghla.pine) | - The Gann High-Low Activator (GHLA) is a trend-following stop/reversal indicator that alternates between the Simple Moving Average of Highs and the ... -- Parameterized by `period` (default 13). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Super](../super/Super.md), [PSAR](../../reversals/psar/Psar.md) | **Complementary:** ATR for stop placement | **Trading note:** Gann High-Low Activator; trend-following stop based on prior period's median. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Gann High-Low Activator (GHLA) is a trend-following stop/reversal indicator that alternates between the Simple Moving Average of Highs and the Simple Moving Average of Lows based on a three-state crossover rule. Developed by Robert Krausz and published in *Technical Analysis of Stocks & Commodities* (February 1998), the indicator produces a single trailing line: SMA(Low) during uptrends (acting as dynamic support) and SMA(High) during downtrends (acting as dynamic resistance). The flip between states occurs only when price closes decisively beyond the opposing SMA, creating a hysteresis zone that filters minor whipsaws. With a default period of 3 bars, GHLA responds aggressively to trend changes while requiring just $O(N)$ additions and one comparison per bar. @@ -220,4 +218,4 @@ Key validation points: - Gann, W.D. *Truth of the Stock Tape.* Financial Guardian Publishing, 1923. - TradeStation. "HiLoActivator Study Reference." TradeStation Help Center. - financial-hacker.com. "Petra on Programming: The Gann Hi-Lo Activator." 2020. -- PineScript reference: `ghla.pine` in indicator directory. +- PineScript reference: `ghla.pine` in indicator directory. \ No newline at end of file diff --git a/lib/dynamics/ht_trendmode/HtTrendmode.md b/lib/dynamics/ht_trendmode/HtTrendmode.md index 11656cb9..c998b429 100644 --- a/lib/dynamics/ht_trendmode/HtTrendmode.md +++ b/lib/dynamics/ht_trendmode/HtTrendmode.md @@ -14,8 +14,6 @@ - The Hilbert Transform Trend Mode indicator is a binary regime classifier that determines whether price action is dominated by trending behavior (ou... - No configurable parameters; computation is stateless per bar. -- Output range: $0$ to $1$. -- Requires `LOOKBACK` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Hilbert Transform Trend Mode indicator is a binary regime classifier that determines whether price action is dominated by trending behavior (output = 1) or cyclical/mean-reverting behavior (output = 0). It uses the full Ehlers Hilbert Transform pipeline — 4-bar WMA smoothing, Hilbert FIR filters, homodyne discriminator for period estimation, DC phase extraction, and SineWave indicators — then applies four decision criteria to classify the current regime. The implementation follows TA-Lib's Ehlers-faithful algorithm from the February 2002 publication. Output is discrete {0, 1}, making it a direct strategy selector: deploy trend-following logic when mode = 1, and mean-reversion logic when mode = 0. @@ -152,4 +150,4 @@ The recursive EMA smoothing of the period estimate blocks full vectorization. - Ehlers, J.F. — "The Instantaneous Trendline" (February 2002) - Ehlers, J.F. — *MESA and Trading Market Cycles* (John Wiley & Sons, 2002) - Ehlers, J.F. — *Rocket Science for Traders* (John Wiley & Sons, 2001) -- PineScript reference: `ht_trendmode.pine` in indicator directory +- PineScript reference: `ht_trendmode.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/ichimoku/Ichimoku.md b/lib/dynamics/ichimoku/Ichimoku.md index fa0acaef..9724d5a0 100644 --- a/lib/dynamics/ichimoku/Ichimoku.md +++ b/lib/dynamics/ichimoku/Ichimoku.md @@ -13,9 +13,7 @@ | **PineScript** | [ichimoku.pine](ichimoku.pine) | - Ichimoku Kinko Hyo ("One Glance Equilibrium Chart") is a comprehensive trend-following system that provides five distinct components revealing tren... -- Parameterized by `tenkanperiod`, `kijunperiod`, `senkoubperiod`, `displacement`. -- Output range: Varies (see docs). -- Requires `maxPeriod` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Alligator](../alligator/Alligator.md), [AMAT](../amat/Amat.md) | **Complementary:** Volume for cloud breakout confirmation | **Trading note:** Five-line system: Tenkan, Kijun, Senkou A/B, Chikou. Cloud defines support/resistance zones. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Ichimoku Kinko Hyo ("One Glance Equilibrium Chart") is a comprehensive trend-following system that provides five distinct components revealing trend direction, momentum, support/resistance levels, and potential future price zones simultaneously. The Tenkan-sen and Kijun-sen are midpoints of high-low ranges at different timescales (not moving averages of closes). Senkou Span A and B form the "cloud" (Kumo) — a projected equilibrium zone displaced forward in time. Chikou Span is simply the current close displaced backward. All components use sliding window min/max arithmetic, producing step-function behavior on breakouts rather than the smooth curves of EMA-based systems. The system requires OHLC bar input. @@ -148,4 +146,4 @@ Three independent window extremum computations can be parallelized. The midpoint - Hosoda, G. — *Ichimoku Kinko Hyo* (7-volume series, Tokyo, 1969) - Patel, M. — *Trading with Ichimoku Clouds* (John Wiley & Sons, 2010) - Elliott, N. — *Ichimoku Charts: An Introduction* (Harriman House, 2007) -- PineScript reference: `ichimoku.pine` in indicator directory +- PineScript reference: `ichimoku.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/impulse/Impulse.md b/lib/dynamics/impulse/Impulse.md index dc90b289..0820defa 100644 --- a/lib/dynamics/impulse/Impulse.md +++ b/lib/dynamics/impulse/Impulse.md @@ -12,9 +12,6 @@ | **Warmup** | `Math.Max(emaPeriod, macdSlow) + macdSignal - 1` bars (default 34) | - The Elder Impulse System combines a 13-period EMA (trend inertia) with the MACD(12,26,9) histogram (momentum acceleration) to classify each bar as ... -- Parameterized by `emaperiod` (default 13), `macdfast` (default 12), `macdslow` (default 26), `macdsignal` (default 9). -- Output range: Varies (see docs). -- Requires `Math.Max(emaPeriod, macdSlow) + macdSignal - 1` bars (default 34) of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Elder Impulse System combines a 13-period EMA (trend inertia) with the MACD(12,26,9) histogram (momentum acceleration) to classify each bar as bullish (+1), bearish (-1), or neutral (0). Both EMA slope and histogram slope must agree for a directional signal; disagreement forces neutral. The system functions as a permission filter rather than a signal generator, requiring 34 bars warmup and running at O(1) per bar through composition of two child indicators. @@ -131,4 +128,4 @@ Same EMA constraint across all impulse components. - Elder, A. (2002). *Come Into My Trading Room*. John Wiley and Sons. - Appel, G. (1979). "The Moving Average Convergence-Divergence Method." -- Aspray, T. (1986). "MACD Histogram." *Technical Analysis of Stocks and Commodities*. +- Aspray, T. (1986). "MACD Histogram." *Technical Analysis of Stocks and Commodities*. \ No newline at end of file diff --git a/lib/dynamics/minusdi/MinusDi.md b/lib/dynamics/minusdi/MinusDi.md index 6ee59964..7d17a9e0 100644 --- a/lib/dynamics/minusdi/MinusDi.md +++ b/lib/dynamics/minusdi/MinusDi.md @@ -13,9 +13,7 @@ | **PineScript** | [minusdi.pine](minusdi.pine) | - The Minus Directional Indicator measures the strength of downward price movement relative to true range. -- Parameterized by `period` (default 14). -- Output range: 0 to 100. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [PlusDi](../plusdi/PlusDi.md), [ADX](../adx/Adx.md) | **Complementary:** ADX for trend strength | **Trading note:** Minus Directional Indicator; measures downward movement strength. Part of Wilder's DM system. - Validated against TA-Lib, Skender, and Dx equivalence. The Minus Directional Indicator (-DI) is one component of J. Welles Wilder Jr.'s Directional Movement System. It quantifies the fraction of recent true range attributable to downward price extension. The computation smooths both -DM (minus directional movement) and TR (true range) with Wilder's RMA ($\alpha = 1/N$), then divides: $-DI = 100 \times \text{Smooth}(-DM) / \text{Smooth}(TR)$. When -DI rises, downward price pressure is increasing. When -DI crosses above +DI, it signals a potential bearish trend. The -DI line is commonly plotted alongside +DI to visualize directional balance. @@ -97,4 +95,4 @@ When $TR_{\text{smooth}} = 0$ (no price movement), -DI = 0. ## Resources - Wilder, J.W. — *New Concepts in Technical Trading Systems* (Trend Research, 1978) -- PineScript reference: `minusdi.pine` in indicator directory +- PineScript reference: `minusdi.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/minusdm/MinusDm.md b/lib/dynamics/minusdm/MinusDm.md index a3c8148d..519f8fc3 100644 --- a/lib/dynamics/minusdm/MinusDm.md +++ b/lib/dynamics/minusdm/MinusDm.md @@ -13,9 +13,7 @@ | **PineScript** | [minusdm.pine](minusdm.pine) | - Minus Directional Movement outputs the Wilder-smoothed downward directional movement in price units. -- Parameterized by `period` (default 14). -- Output range: ≥ 0 (price units, scales with instrument). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [PlusDm](../plusdm/PlusDm.md), [DX](../dx/Dx.md) | **Complementary:** ATR for normalization | **Trading note:** Minus Directional Movement; raw downward price expansion before smoothing. - Validated against TA-Lib and Dx equivalence. Minus Directional Movement (-DM) measures the magnitude of downward price movement, smoothed using Wilder's method. Unlike -DI which normalizes by true range to produce a percentage, -DM outputs raw smoothed values in price units. -DM captures when the previous bar's low exceeds the current bar's low by more than the current bar's high exceeds the previous bar's high. It is the raw building block of the Directional Movement System — the unnormalized signal before division by True Range converts it to -DI. @@ -89,4 +87,4 @@ $$-DM_{\text{smooth}} = \text{RMA}(-DM, N), \quad \alpha = 1/N$$ ## Resources - Wilder, J.W. — *New Concepts in Technical Trading Systems* (Trend Research, 1978) -- PineScript reference: `minusdm.pine` in indicator directory +- PineScript reference: `minusdm.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/pfe/Pfe.md b/lib/dynamics/pfe/Pfe.md index 3e98b5ef..3959e3ac 100644 --- a/lib/dynamics/pfe/Pfe.md +++ b/lib/dynamics/pfe/Pfe.md @@ -13,9 +13,7 @@ | **PineScript** | [pfe.pine](pfe.pine) | - Polarized Fractal Efficiency (PFE) quantifies trend strength by comparing the Euclidean distance a price series actually travels bar-to-bar against... -- Parameterized by `period` (default 10), `smoothperiod` (default 5). -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ADX](../adx/Adx.md), [VHF](../vhf/Vhf.md) | **Complementary:** Moving average for trend direction | **Trading note:** Polarized Fractal Efficiency; measures how efficiently price travels. ±100 scale. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Polarized Fractal Efficiency (PFE) quantifies trend strength by comparing the Euclidean distance a price series actually travels bar-to-bar against the straight-line distance between the endpoints over the same window. The ratio, scaled to [-100, +100] and smoothed with an EMA, distinguishes efficient trending motion (values near ±100) from fractal, self-similar noise (values near 0). Created by Hans Hannula and published in *Technical Analysis of Stocks & Commodities* (January 1994), PFE applies fractal geometry to price action without requiring Hurst exponent estimation or rescaled-range analysis. With default parameters (period=10, smooth=5), the indicator needs 11 close values for the first raw reading plus 5 bars of EMA convergence, totaling ~16 bars of warmup. The core loop executes $N$ square roots per bar, making it $O(N)$ per update in streaming mode. @@ -251,4 +249,4 @@ Key validation points: - Mandelbrot, Benoit. "The Variation of Certain Speculative Prices." *The Journal of Business*, Vol. 36, No. 4, October 1963. - Kaufman, Perry. *Trading Systems and Methods*, 5th Edition. Wiley, 2013. (Efficiency Ratio comparison) - Hannula, Hans. "Chaos and the Stock Market." *Cycles Magazine*, 1993. -- PineScript reference: `pfe.pine` in indicator directory. +- PineScript reference: `pfe.pine` in indicator directory. \ No newline at end of file diff --git a/lib/dynamics/plusdi/PlusDi.md b/lib/dynamics/plusdi/PlusDi.md index a398989b..9c158a65 100644 --- a/lib/dynamics/plusdi/PlusDi.md +++ b/lib/dynamics/plusdi/PlusDi.md @@ -13,9 +13,7 @@ | **PineScript** | [plusdi.pine](plusdi.pine) | - The Plus Directional Indicator measures the strength of upward price movement relative to true range. -- Parameterized by `period` (default 14). -- Output range: 0 to 100. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MinusDi](../minusdi/MinusDi.md), [ADX](../adx/Adx.md) | **Complementary:** ADX for trend strength | **Trading note:** Plus Directional Indicator; measures upward movement strength. Part of Wilder's DM system. - Validated against TA-Lib, Skender, and Dx equivalence. The Plus Directional Indicator (+DI) is one component of J. Welles Wilder Jr.'s Directional Movement System. It quantifies the fraction of recent true range attributable to upward price extension. The computation smooths both +DM (plus directional movement) and TR (true range) with Wilder's RMA ($\alpha = 1/N$), then divides: $+DI = 100 \times \text{Smooth}(+DM) / \text{Smooth}(TR)$. When +DI rises, upward price pressure is increasing. When +DI crosses above -DI, it signals a potential bullish trend. The +DI line is commonly plotted alongside -DI to visualize directional balance. @@ -97,4 +95,4 @@ When $TR_{\text{smooth}} = 0$ (no price movement), +DI = 0. ## Resources - Wilder, J.W. — *New Concepts in Technical Trading Systems* (Trend Research, 1978) -- PineScript reference: `plusdi.pine` in indicator directory +- PineScript reference: `plusdi.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/plusdm/PlusDm.md b/lib/dynamics/plusdm/PlusDm.md index a5d6c7d8..236e4aa1 100644 --- a/lib/dynamics/plusdm/PlusDm.md +++ b/lib/dynamics/plusdm/PlusDm.md @@ -13,9 +13,7 @@ | **PineScript** | [plusdm.pine](plusdm.pine) | - Plus Directional Movement outputs the Wilder-smoothed upward directional movement in price units. -- Parameterized by `period` (default 14). -- Output range: ≥ 0 (price units, scales with instrument). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MinusDm](../minusdm/MinusDm.md), [DX](../dx/Dx.md) | **Complementary:** ATR for normalization | **Trading note:** Plus Directional Movement; raw upward price expansion before smoothing. - Validated against TA-Lib and Dx equivalence. Plus Directional Movement (+DM) measures the magnitude of upward price movement, smoothed using Wilder's method. Unlike +DI which normalizes by true range to produce a percentage, +DM outputs raw smoothed values in price units. +DM captures when the current bar's high exceeds the previous bar's high by more than the previous bar's low exceeds the current bar's low. It is the raw building block of the Directional Movement System — the unnormalized signal before division by True Range converts it to +DI. @@ -89,4 +87,4 @@ $$+DM_{\text{smooth}} = \text{RMA}(+DM, N), \quad \alpha = 1/N$$ ## Resources - Wilder, J.W. — *New Concepts in Technical Trading Systems* (Trend Research, 1978) -- PineScript reference: `plusdm.pine` in indicator directory +- PineScript reference: `plusdm.pine` in indicator directory \ No newline at end of file diff --git a/lib/dynamics/qstick/Qstick.md b/lib/dynamics/qstick/Qstick.md index 6d9b07e2..a1da016c 100644 --- a/lib/dynamics/qstick/Qstick.md +++ b/lib/dynamics/qstick/Qstick.md @@ -13,9 +13,7 @@ | **PineScript** | [qstick.pine](qstick.pine) | - The Qstick indicator, developed by Tushar Chande, computes a moving average of the close-minus-open difference over a lookback period, quantifying ... -- Parameterized by `period` (default defaultperiod), `useema` (default defaultuseema). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [CMO](../../momentum/cmo/Cmo.md), [Impulse](../impulse/Impulse.md) | **Complementary:** Volume for confirmation | **Trading note:** Qstick averages (Close−Open); positive = buying pressure, negative = selling pressure. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Qstick indicator, developed by Tushar Chande, computes a moving average of the close-minus-open difference over a lookback period, quantifying whether bars are predominantly bullish or bearish. Positive values indicate closes above opens (buying pressure); negative values indicate closes below opens (selling pressure). It supports both SMA (O(N) space via ring buffer) and EMA (O(1) space) smoothing modes and requires TBar input for open/close access. @@ -114,4 +112,4 @@ Fully SIMD-vectorizable in batch mode. AVX2 achieves ~4× throughput on large ar ## Resources - Chande, T. S. & Kroll, S. (1994). *The New Technical Trader*. John Wiley and Sons. -- Kirkpatrick, C. D. & Dahlquist, J. R. (2015). *Technical Analysis: The Complete Resource for Financial Market Technicians*. FT Press. +- Kirkpatrick, C. D. & Dahlquist, J. R. (2015). *Technical Analysis: The Complete Resource for Financial Market Technicians*. FT Press. \ No newline at end of file diff --git a/lib/dynamics/ravi/Ravi.md b/lib/dynamics/ravi/Ravi.md index 98bcbeef..bf322317 100644 --- a/lib/dynamics/ravi/Ravi.md +++ b/lib/dynamics/ravi/Ravi.md @@ -13,9 +13,7 @@ | **PineScript** | [ravi.pine](ravi.pine) | - RAVI (Range Action Verification Index) measures trend strength by computing the absolute percentage divergence between a short-period SMA and a lon... -- Parameterized by `shortperiod` (default 7), `longperiod` (default 65). -- Output range: Varies (see docs). -- Requires `longPeriod` bars (default 65) of warmup before first valid output (IsHot = true). +- **Similar:** [ADX](../adx/Adx.md), [Chop](../chop/Chop.md) | **Complementary:** Moving average crossover for entries | **Trading note:** Range Action Verification Index; ratio of fast/slow MA difference to slow MA. Trend filter. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. RAVI (Range Action Verification Index) measures trend strength by computing the absolute percentage divergence between a short-period SMA and a long-period SMA. Created by Tushar Chande and published in *Beyond Technical Analysis* (Wiley, 2001), the indicator classifies markets into trending (RAVI > 3%) and ranging (RAVI < 3%) regimes using a single threshold. With default parameters (short=7, long=65), RAVI requires 65 bars of warmup for the first valid reading. The core computation is three operations per bar in streaming mode: two running-sum updates and one division. No square roots, no exponentials, no recursion. The entire indicator reduces to normalized SMA spread, making it one of the cheapest dynamics classifiers available. @@ -247,4 +245,4 @@ Key validation points: - Chande, Tushar S. "Adapting Moving Averages to Market Volatility." *Stocks & Commodities*, V10:3, 1992. pp. 108-114. (VIDYA introduction; RAVI is the companion trend classifier.) - Chande, Tushar S., and Kroll, Stanley. *The New Technical Trader: Boost Your Profit by Plugging into the Latest Indicators*. John Wiley & Sons, 1994. ISBN: 0471597805. - Wilder, J. Welles. *New Concepts in Technical Trading Systems*. Trend Research, 1978. (ADX reference for comparison.) -- PineScript reference: `ravi.pine` in indicator directory. +- PineScript reference: `ravi.pine` in indicator directory. \ No newline at end of file diff --git a/lib/dynamics/super/Super.md b/lib/dynamics/super/Super.md index e8d305dc..2bc06c91 100644 --- a/lib/dynamics/super/Super.md +++ b/lib/dynamics/super/Super.md @@ -13,9 +13,7 @@ | **PineScript** | [super.pine](super.pine) | - SuperTrend is a trend-following overlay that uses ATR-scaled bands around the HL2 midpoint, switching between upper and lower bands based on close ... -- Parameterized by `period` (default 10), `multiplier` (default 3.0). -- Output range: Varies (see docs). -- Requires `> period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [PSAR](../../reversals/psar/Psar.md), [Ghla](../ghla/Ghla.md) | **Complementary:** ADX for trend strength | **Trading note:** SuperTrend; ATR-based trailing stop that flips direction. Popular in crypto and forex. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. SuperTrend is a trend-following overlay that uses ATR-scaled bands around the HL2 midpoint, switching between upper and lower bands based on close price breakouts. A ratchet mechanism prevents the active band from moving against the trend, creating a step-like trailing stop that adapts to volatility. The indicator is a two-state machine (bullish/bearish) with O(1) per-bar updates and zero allocations in the hot path. @@ -127,4 +125,4 @@ The ratchet and trend-flip logic create strong sequential dependencies. The ATR ## Resources - Seban, O. SuperTrend indicator documentation. -- Wilder, J. W. (1978). *New Concepts in Technical Trading Systems*. Trend Research. +- Wilder, J. W. (1978). *New Concepts in Technical Trading Systems*. Trend Research. \ No newline at end of file diff --git a/lib/dynamics/ttm_squeeze/TtmSqueeze.md b/lib/dynamics/ttm_squeeze/TtmSqueeze.md index 613afd14..558d77e7 100644 --- a/lib/dynamics/ttm_squeeze/TtmSqueeze.md +++ b/lib/dynamics/ttm_squeeze/TtmSqueeze.md @@ -12,9 +12,6 @@ | **Warmup** | `Math.Max(Math.Max(bbPeriod, kcPeriod), momPeriod)` bars | - John Carter's TTM Squeeze detects low-volatility compression by comparing Bollinger Band width against Keltner Channel width: when BB fits inside K... -- Parameterized by `bbperiod` (default 20), `bbmult` (default 2.0), `kcperiod` (default 20), `kcmult` (default 1.5), `momperiod` (default 20). -- Output range: Varies (see docs). -- Requires `Math.Max(Math.Max(bbPeriod, kcPeriod), momPeriod)` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. John Carter's TTM Squeeze detects low-volatility compression by comparing Bollinger Band width against Keltner Channel width: when BB fits inside KC, a "squeeze" is on, signaling imminent breakout. The momentum component uses linear regression of price deviation from the Donchian midline to indicate direction. The indicator outputs a boolean squeeze state plus a continuous momentum histogram, requiring BB(20,2.0) and KC(20,1.5) as default parameters with a combined warmup of 20 bars. @@ -139,4 +136,4 @@ Regression can be recast as prefix-sum dot products for SIMD acceleration; ATR/E - Carter, J. (2005). *Mastering the Trade*. McGraw-Hill. - Bollinger, J. (2001). *Bollinger on Bollinger Bands*. McGraw-Hill. -- Keltner, C. (1960). *How to Make Money in Commodities*. The Keltner Statistical Service. +- Keltner, C. (1960). *How to Make Money in Commodities*. The Keltner Statistical Service. \ No newline at end of file diff --git a/lib/dynamics/ttm_trend/TtmTrend.md b/lib/dynamics/ttm_trend/TtmTrend.md index 87f4cf8b..49f01fe2 100644 --- a/lib/dynamics/ttm_trend/TtmTrend.md +++ b/lib/dynamics/ttm_trend/TtmTrend.md @@ -13,9 +13,7 @@ | **PineScript** | [TtmTrend.pine](TtmTrend.pine) | - John Carter's TTM Trend uses a fast EMA (default period 6) applied to typical price (HLC/3) to determine short-term trend direction via slope sign. -- Parameterized by `period` (default defaultperiod). -- Output range: Varies (see docs). -- Requires `> 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Impulse](../impulse/Impulse.md), [AMAT](../amat/Amat.md) | **Complementary:** TTM Squeeze for timing | **Trading note:** John Carter's trend indicator; colors bars based on close vs midpoint of prior 5-bar range. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. John Carter's TTM Trend uses a fast EMA (default period 6) applied to typical price (HLC/3) to determine short-term trend direction via slope sign. Output is a ternary trend state: +1 (bullish, EMA rising), -1 (bearish, EMA falling), or 0 (neutral, EMA unchanged). The indicator requires only 2 bars warmup, runs at O(1) per bar with O(1) space, and produces zero allocations in the hot path. @@ -119,4 +117,4 @@ The EMA histogram is the only sequential step. SMA and comparison are fully vect ## Resources -- Carter, J. (2005). *Mastering the Trade*. McGraw-Hill. +- Carter, J. (2005). *Mastering the Trade*. McGraw-Hill. \ No newline at end of file diff --git a/lib/dynamics/vhf/Vhf.md b/lib/dynamics/vhf/Vhf.md index 09f4a0b6..1486412e 100644 --- a/lib/dynamics/vhf/Vhf.md +++ b/lib/dynamics/vhf/Vhf.md @@ -13,9 +13,7 @@ | **PineScript** | [vhf.pine](vhf.pine) | - VHF (Vertical Horizontal Filter) measures trend strength by dividing the price range over $N$ periods by the total absolute bar-to-bar path distanc... -- Parameterized by `period` (default 28). -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ADX](../adx/Adx.md), [Chop](../chop/Chop.md) | **Complementary:** Moving averages for direction | **Trading note:** Vertical Horizontal Filter; ratio of price range to cumulative movement. High = trending. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. VHF (Vertical Horizontal Filter) measures trend strength by dividing the price range over $N$ periods by the total absolute bar-to-bar path distance over the same window. Created by Adam White and published in the August 1991 issue of *Futures* magazine, VHF produces a single positive value where higher readings indicate trending conditions and lower readings indicate choppy, range-bound markets. With the default period of 28, the indicator requires 29 close values for the first valid output. The core computation in streaming mode is O(1) per bar when implemented with deque-based min/max tracking and a running sum of absolute changes. No square roots, no exponentials, no recursion. VHF is one of the simplest and cheapest trend-strength classifiers available, requiring approximately 12 operations per bar at steady state. @@ -234,4 +232,4 @@ Key validation points: - Dreiss, Bill. "Choppiness Index." Referenced in various technical analysis encyclopedias. No formal publication; oral tradition via market conferences circa 1993. - Wilder, J. Welles. *New Concepts in Technical Trading Systems*. Trend Research, 1978. (ADX reference for comparison.) - Pardo, Robert. *The Evaluation and Optimization of Trading Strategies*, 2nd Edition. Wiley, 2008. (Uses VHF as a regime filter in walk-forward optimization framework.) -- PineScript reference: `vhf.pine` in indicator directory. +- PineScript reference: `vhf.pine` in indicator directory. \ No newline at end of file diff --git a/lib/dynamics/vortex/Vortex.md b/lib/dynamics/vortex/Vortex.md index 13647115..cb265cc6 100644 --- a/lib/dynamics/vortex/Vortex.md +++ b/lib/dynamics/vortex/Vortex.md @@ -13,9 +13,7 @@ | **PineScript** | [vortex.pine](vortex.pine) | - The Vortex Indicator measures upward and downward trend momentum by computing the ratio of positive and negative vortex movements to true range ove... -- Parameterized by `period` (default 14). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ADX](../adx/Adx.md), [Aroon](../aroon/Aroon.md) | **Complementary:** Volume for confirmation | **Trading note:** VI+ and VI− oscillate around 1.0; crossovers signal trend changes. Inspired by Viktor Schauberger's vortex theory. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Vortex Indicator measures upward and downward trend momentum by computing the ratio of positive and negative vortex movements to true range over a rolling window. VI+ captures the distance from current high to previous low (upward force); VI- captures the distance from current low to previous high (downward force). Both are normalized by summed true range, producing two lines that oscillate around 1.0. Crossovers signal trend changes. The implementation uses three ring buffers with running sums for O(1) streaming updates. @@ -140,4 +138,4 @@ All individual-bar computations are independent and SIMD-friendly. The prefix-su ## Resources -- Botes, E. & Siepman, D. (2010). "The Vortex Indicator." *Technical Analysis of Stocks and Commodities*, January 2010. +- Botes, E. & Siepman, D. (2010). "The Vortex Indicator." *Technical Analysis of Stocks and Commodities*, January 2010. \ No newline at end of file diff --git a/lib/errors/huber/Huber.md b/lib/errors/huber/Huber.md index 2a6b0540..89186fd0 100644 --- a/lib/errors/huber/Huber.md +++ b/lib/errors/huber/Huber.md @@ -13,9 +13,7 @@ | **PineScript** | [huber.pine](huber.pine) | - Huber Loss is a hybrid loss function that combines the best properties of Mean Squared Error (MSE) and Mean Absolute Error (MAE). -- Parameterized by `period`, `delta` (default 1.345). -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [PseudoHuber](../pseudohuber/PseudoHuber.md), [MAE](../mae/Mae.md) | **Trading note:** Huber loss; robust to outliers — quadratic for small errors, linear for large. Used in ML-based trading models. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Huber Loss is a hybrid loss function that combines the best properties of Mean Squared Error (MSE) and Mean Absolute Error (MAE). For small errors, it behaves quadratically like MSE; for large errors, it behaves linearly like MAE. @@ -188,4 +186,4 @@ huber.Update(110, 100); // Returns ~12.546 * [MAE](../mae/Mae.md) - Mean Absolute Error (linear everywhere) * [MSE](../mse/Mse.md) - Mean Squared Error (quadratic everywhere) -* [RMSE](../rmse/Rmse.md) - Root Mean Squared Error +* [RMSE](../rmse/Rmse.md) - Root Mean Squared Error \ No newline at end of file diff --git a/lib/errors/logcosh/LogCosh.md b/lib/errors/logcosh/LogCosh.md index 83fcacb2..870b130d 100644 --- a/lib/errors/logcosh/LogCosh.md +++ b/lib/errors/logcosh/LogCosh.md @@ -13,9 +13,7 @@ | **PineScript** | [logcosh.pine](logcosh.pine) | - Log-Cosh Loss combines the best properties of L1 (absolute) and L2 (squared) error metrics through the logarithm of the hyperbolic cosine function. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [Huber](../huber/Huber.md), [MSE](../mse/Mse.md) | **Trading note:** Log-cosh loss; smooth approximation to MAE. Twice differentiable; preferred for gradient-based optimization. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Log-Cosh Loss combines the best properties of L1 (absolute) and L2 (squared) error metrics through the logarithm of the hyperbolic cosine function. It provides smooth gradients everywhere while remaining robust to outliers. @@ -184,4 +182,4 @@ For large errors, Log-Cosh grows approximately linearly (like L1), avoiding the * [MAE](../mae/Mae.md) - Mean Absolute Error (pure L1) * [MSE](../mse/Mse.md) - Mean Squared Error (pure L2) * [Huber](../huber/Huber.md) - Huber Loss (piecewise L1/L2) -* [PseudoHuber](../pseudohuber/PseudoHuber.md) - Smooth Huber approximation +* [PseudoHuber](../pseudohuber/PseudoHuber.md) - Smooth Huber approximation \ No newline at end of file diff --git a/lib/errors/maape/Maape.md b/lib/errors/maape/Maape.md index 5b9bd138..463abfa0 100644 --- a/lib/errors/maape/Maape.md +++ b/lib/errors/maape/Maape.md @@ -13,9 +13,7 @@ | **PineScript** | [maape.pine](maape.pine) | - Mean Arctangent Absolute Percentage Error (MAAPE) transforms percentage errors through the arctangent function, naturally bounding the metric betwe... -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [MAPE](../mape/Mape.md), [SMAPE](../smape/Smape.md) | **Trading note:** Mean Arctangent Absolute Percentage Error; bounded and symmetric, handles zero values unlike MAPE. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Mean Arctangent Absolute Percentage Error (MAAPE) transforms percentage errors through the arctangent function, naturally bounding the metric between 0 and π/2. This eliminates the unbounded nature of MAPE while preserving its scale-independence. @@ -178,4 +176,4 @@ The arctangent compression means that the difference between 100% and 1000% erro * [MAPE](../mape/Mape.md) - Mean Absolute Percentage Error (unbounded) * [SMAPE](../smape/Smape.md) - Symmetric MAPE (different bounding approach) -* [LogCosh](../logcosh/LogCosh.md) - Log-Cosh Loss (similar compression philosophy) +* [LogCosh](../logcosh/LogCosh.md) - Log-Cosh Loss (similar compression philosophy) \ No newline at end of file diff --git a/lib/errors/mae/Mae.md b/lib/errors/mae/Mae.md index 3cf62387..6a186f50 100644 --- a/lib/errors/mae/Mae.md +++ b/lib/errors/mae/Mae.md @@ -13,9 +13,7 @@ | **PineScript** | [mae.pine](mae.pine) | - Mean Absolute Error (MAE) measures the average magnitude of errors in a set of predictions, without considering their direction. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [MSE](../mse/Mse.md), [MdAE](../mdae/Mdae.md) | **Trading note:** Mean Absolute Error; simple, interpretable forecast accuracy metric. Same units as input. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Mean Absolute Error (MAE) measures the average magnitude of errors in a set of predictions, without considering their direction. It represents the average of the absolute differences between actual and predicted values. @@ -160,4 +158,4 @@ Batch SIMD: 4x-8x speedup for large windows. ~3-5 cy/bar amortized in vectorized * [MSE](../mse/Mse.md) - Mean Squared Error * [RMSE](../rmse/Rmse.md) - Root Mean Squared Error -* [MAPE](../mape/Mape.md) - Mean Absolute Percentage Error +* [MAPE](../mape/Mape.md) - Mean Absolute Percentage Error \ No newline at end of file diff --git a/lib/errors/mapd/Mapd.md b/lib/errors/mapd/Mapd.md index 99fa8141..2538996d 100644 --- a/lib/errors/mapd/Mapd.md +++ b/lib/errors/mapd/Mapd.md @@ -13,9 +13,7 @@ | **PineScript** | [mapd.pine](mapd.pine) | - Mean Absolute Percentage Deviation (MAPD) measures the average absolute percentage difference between actual and predicted values, using the predic... -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [MAPE](../mape/Mape.md), [WMAPE](../wmape/Wmape.md) | **Trading note:** Mean Absolute Percentage Deviation; total absolute error divided by total actual values. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Mean Absolute Percentage Deviation (MAPD) measures the average absolute percentage difference between actual and predicted values, using the predicted value as the denominator. This is the key difference from MAPE, which uses the actual value. @@ -176,4 +174,4 @@ mapd.Update(200, 100); // |200-100|/100 = 100% * [MAPE](../mape/Mape.md) - Mean Absolute Percentage Error (divides by actual) * [SMAPE](../smape/Smape.md) - Symmetric Mean Absolute Percentage Error * [MPE](../mpe/Mpe.md) - Mean Percentage Error (signed) -* [MAE](../mae/Mae.md) - Mean Absolute Error (same units) +* [MAE](../mae/Mae.md) - Mean Absolute Error (same units) \ No newline at end of file diff --git a/lib/errors/mape/Mape.md b/lib/errors/mape/Mape.md index 909ace2c..8026ee87 100644 --- a/lib/errors/mape/Mape.md +++ b/lib/errors/mape/Mape.md @@ -13,9 +13,7 @@ | **PineScript** | [mape.pine](mape.pine) | - Mean Absolute Percentage Error (MAPE) measures the average absolute percentage difference between actual and predicted values. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [SMAPE](../smape/Smape.md), [MAAPE](../maape/Maape.md) | **Trading note:** Mean Absolute Percentage Error; scale-independent accuracy. Undefined when actuals are zero. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Mean Absolute Percentage Error (MAPE) measures the average absolute percentage difference between actual and predicted values. It expresses accuracy as a percentage, making it scale-independent and easy to interpret. @@ -192,4 +190,4 @@ Same absolute error (50), but over-prediction shows higher MAPE. * [MAPD](../mapd/Mapd.md) - Mean Absolute Percentage Deviation (divides by predicted) * [SMAPE](../smape/Smape.md) - Symmetric Mean Absolute Percentage Error * [MPE](../mpe/Mpe.md) - Mean Percentage Error (signed) -* [MAE](../mae/Mae.md) - Mean Absolute Error (same units) +* [MAE](../mae/Mae.md) - Mean Absolute Error (same units) \ No newline at end of file diff --git a/lib/errors/mase/Mase.md b/lib/errors/mase/Mase.md index a3c5bdb7..b43a5f12 100644 --- a/lib/errors/mase/Mase.md +++ b/lib/errors/mase/Mase.md @@ -13,9 +13,7 @@ | **PineScript** | [mase.pine](mase.pine) | - Mean Absolute Scaled Error (MASE) normalizes forecast errors by the average error of a naive "random walk" forecast (using the previous value as th... -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MAE](../mae/Mae.md), [RAE](../rae/Rae.md) | **Trading note:** Mean Absolute Scaled Error; compares forecast to naïve random-walk baseline. <1 = better than naïve. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Mean Absolute Scaled Error (MASE) normalizes forecast errors by the average error of a naive "random walk" forecast (using the previous value as the prediction). This makes MASE scale-independent and interpretable across different time series. @@ -135,4 +133,4 @@ MASE is particularly valuable when: * Comparing forecasts across different series * Evaluating against a natural baseline (naive forecast) * Working with data that includes zeros -* Needing symmetric treatment of over/under predictions +* Needing symmetric treatment of over/under predictions \ No newline at end of file diff --git a/lib/errors/mdae/Mdae.md b/lib/errors/mdae/Mdae.md index af239ccb..5787be32 100644 --- a/lib/errors/mdae/Mdae.md +++ b/lib/errors/mdae/Mdae.md @@ -13,9 +13,7 @@ | **PineScript** | [mdae.pine](mdae.pine) | - Median Absolute Error (MdAE) measures the middle value of all absolute errors. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MAE](../mae/Mae.md), [MdAPE](../mdape/Mdape.md) | **Trading note:** Median Absolute Error; robust central-tendency error metric, resistant to outliers. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Median Absolute Error (MdAE) measures the middle value of all absolute errors. Unlike MAE which averages errors, MdAE finds the median, providing exceptional robustness against outliers and extreme values. @@ -167,4 +165,4 @@ Batch SIMD: 4x-8x speedup for large windows. ~3-5 cy/bar amortized in vectorized * [MAE](../mae/Mae.md) - Mean Absolute Error (uses mean) * [MdAPE](../mdape/Mdape.md) - Median Absolute Percentage Error -* [Huber](../huber/Huber.md) - Huber Loss (robust but differentiable) +* [Huber](../huber/Huber.md) - Huber Loss (robust but differentiable) \ No newline at end of file diff --git a/lib/errors/mdape/Mdape.md b/lib/errors/mdape/Mdape.md index 392522e4..85d62a3d 100644 --- a/lib/errors/mdape/Mdape.md +++ b/lib/errors/mdape/Mdape.md @@ -13,9 +13,7 @@ | **PineScript** | [mdape.pine](mdape.pine) | - Median Absolute Percentage Error (MdAPE) combines the scale-independence of percentage errors with the robustness of median statistics. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MAPE](../mape/Mape.md), [MdAE](../mdae/Mdae.md) | **Trading note:** Median Absolute Percentage Error; robust version of MAPE for skewed error distributions. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Median Absolute Percentage Error (MdAPE) combines the scale-independence of percentage errors with the robustness of median statistics. It provides a measure of typical relative prediction accuracy that remains stable even when some predictions are dramatically wrong. @@ -164,4 +162,4 @@ Batch SIMD: 4x-8x speedup for large windows. ~3-5 cy/bar amortized in vectorized * [MAPE](../mape/Mape.md) - Mean Absolute Percentage Error (uses mean) * [MdAE](../mdae/Mdae.md) - Median Absolute Error (non-percentage) -* [SMAPE](../smape/Smape.md) - Symmetric MAPE (different normalization) +* [SMAPE](../smape/Smape.md) - Symmetric MAPE (different normalization) \ No newline at end of file diff --git a/lib/errors/me/Me.md b/lib/errors/me/Me.md index 1ad4009d..74ffb23f 100644 --- a/lib/errors/me/Me.md +++ b/lib/errors/me/Me.md @@ -13,9 +13,7 @@ | **PineScript** | [me.pine](me.pine) | - Mean Error (ME), also known as Mean Bias Error, measures the average error between actual and predicted values while preserving the sign. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [MAE](../mae/Mae.md), [MPE](../mpe/Mpe.md) | **Trading note:** Mean Error (bias); positive = systematic overprediction, negative = underprediction. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Mean Error (ME), also known as Mean Bias Error, measures the average error between actual and predicted values while preserving the sign. Unlike MAE, ME reveals systematic bias in predictions: whether a model consistently over-predicts or under-predicts. @@ -179,4 +177,4 @@ Always use ME alongside MAE or MSE to get a complete picture. * [MAE](../mae/Mae.md) - Mean Absolute Error (magnitude only) * [MSE](../mse/Mse.md) - Mean Squared Error -* [MPE](../mpe/Mpe.md) - Mean Percentage Error (relative bias) +* [MPE](../mpe/Mpe.md) - Mean Percentage Error (relative bias) \ No newline at end of file diff --git a/lib/errors/mpe/Mpe.md b/lib/errors/mpe/Mpe.md index 5d6e12c9..76f3c30f 100644 --- a/lib/errors/mpe/Mpe.md +++ b/lib/errors/mpe/Mpe.md @@ -13,9 +13,7 @@ | **PineScript** | [mpe.pine](mpe.pine) | - Mean Percentage Error measures the average percentage difference between actual and predicted values while preserving the sign. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [ME](../me/Me.md), [MAPE](../mape/Mape.md) | **Trading note:** Mean Percentage Error; reveals directional bias as percentage. Positive/negative cancellation is a feature. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Mean Percentage Error measures the average percentage difference between actual and predicted values while preserving the sign. Unlike MAPE, which takes absolute values, MPE reveals systematic bias in predictions—whether a model consistently over-predicts or under-predicts. @@ -176,4 +174,4 @@ Unlike MAPE (bounded at 0% to ∞), MPE can range from -∞ to +100%: * [MAPE](../mape/Mape.md) - Unsigned percentage error for magnitude * [ME](../me/Me.md) - Signed absolute error for absolute bias -* [MAE](../mae/Mae.md) - Unsigned absolute error for magnitude +* [MAE](../mae/Mae.md) - Unsigned absolute error for magnitude \ No newline at end of file diff --git a/lib/errors/mrae/Mrae.md b/lib/errors/mrae/Mrae.md index 4d0de101..e538b607 100644 --- a/lib/errors/mrae/Mrae.md +++ b/lib/errors/mrae/Mrae.md @@ -13,9 +13,7 @@ | **PineScript** | [mrae.pine](mrae.pine) | - Mean Relative Absolute Error (MRAE) measures the average magnitude of errors relative to the actual values. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [RAE](../rae/Rae.md), [MASE](../mase/Mase.md) | **Trading note:** Mean Relative Absolute Error; ratio of errors to benchmark errors. Scale-free comparison metric. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Mean Relative Absolute Error (MRAE) measures the average magnitude of errors relative to the actual values. This normalization makes the metric scale-independent and easier to interpret across different datasets. @@ -161,4 +159,4 @@ Batch SIMD: 4x-8x speedup for large windows. ~3-5 cy/bar amortized in vectorized * [MAE](../mae/Mae.md) - Mean Absolute Error (non-relative) * [MAPE](../mape/Mape.md) - Mean Absolute Percentage Error -* [SMAPE](../smape/Smape.md) - Symmetric Mean Absolute Percentage Error +* [SMAPE](../smape/Smape.md) - Symmetric Mean Absolute Percentage Error \ No newline at end of file diff --git a/lib/errors/mse/Mse.md b/lib/errors/mse/Mse.md index 9c00e278..b085bf48 100644 --- a/lib/errors/mse/Mse.md +++ b/lib/errors/mse/Mse.md @@ -13,9 +13,7 @@ | **PineScript** | [mse.pine](mse.pine) | - Mean Squared Error (MSE) measures the average of the squares of the errors between actual and predicted values. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [RMSE](../rmse/Rmse.md), [MAE](../mae/Mae.md) | **Trading note:** Mean Squared Error; penalizes large errors quadratically. Standard loss function in regression. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Mean Squared Error (MSE) measures the average of the squares of the errors between actual and predicted values. By squaring errors, MSE penalizes large deviations more heavily than small ones. @@ -147,4 +145,4 @@ RMSE has the advantage of being in the same units as the original data. * [MAE](../mae/Mae.md) - Mean Absolute Error (robust to outliers) * [RMSE](../rmse/Rmse.md) - Root Mean Squared Error (same units as data) -* [Huber](../huber/Huber.md) - Combines MSE and MAE benefits +* [Huber](../huber/Huber.md) - Combines MSE and MAE benefits \ No newline at end of file diff --git a/lib/errors/msle/Msle.md b/lib/errors/msle/Msle.md index 30e5c427..4839d6fd 100644 --- a/lib/errors/msle/Msle.md +++ b/lib/errors/msle/Msle.md @@ -13,9 +13,7 @@ | **PineScript** | [msle.pine](msle.pine) | - Mean Squared Logarithmic Error transforms both actual and predicted values through logarithms before computing squared error. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [RMSLE](../rmsle/Rmsle.md), [MSE](../mse/Mse.md) | **Trading note:** Mean Squared Log Error; penalizes under-prediction more than over-prediction. Good for growth rates. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Mean Squared Logarithmic Error transforms both actual and predicted values through logarithms before computing squared error. This compression makes MSLE robust to outliers and particularly suited for data with exponential growth patterns or wide dynamic ranges. @@ -205,4 +203,4 @@ Near zero, small absolute differences create large MSLE: * [RMSLE](../rmsle/Rmsle.md) - Root of MSLE for interpretable units * [MSE](../mse/Mse.md) - Linear-scale squared error -* [MAPE](../mape/Mape.md) - Percentage-based comparison +* [MAPE](../mape/Mape.md) - Percentage-based comparison \ No newline at end of file diff --git a/lib/errors/pseudohuber/PseudoHuber.md b/lib/errors/pseudohuber/PseudoHuber.md index 877a68ba..70cb8b72 100644 --- a/lib/errors/pseudohuber/PseudoHuber.md +++ b/lib/errors/pseudohuber/PseudoHuber.md @@ -13,9 +13,7 @@ | **PineScript** | [pseudohuber.pine](pseudohuber.pine) | - Pseudo-Huber Loss (also called Charbonnier Loss) is a smooth approximation to the Huber loss function. -- Parameterized by `period`, `delta` (default 1.0). -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Huber](../huber/Huber.md), [LogCosh](../logcosh/LogCosh.md) | **Trading note:** Smooth approximation to Huber loss; continuously differentiable with tunable delta parameter. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Pseudo-Huber Loss (also called Charbonnier Loss) is a smooth approximation to the Huber loss function. Unlike Huber which has a piecewise definition with a kink at δ, Pseudo-Huber is continuously differentiable everywhere, making it ideal for gradient-based optimization. @@ -191,4 +189,4 @@ Pseudo-Huber produces slightly smaller values but follows the same qualitative b * [Huber](../huber/Huber.md) - Huber Loss (piecewise, with kink) * [LogCosh](../logcosh/LogCosh.md) - Log-Cosh Loss (different smooth approximation) * [MAE](../mae/Mae.md) - Mean Absolute Error (pure L1) -* [MSE](../mse/Mse.md) - Mean Squared Error (pure L2) +* [MSE](../mse/Mse.md) - Mean Squared Error (pure L2) \ No newline at end of file diff --git a/lib/errors/quantileloss/QuantileLoss.md b/lib/errors/quantileloss/QuantileLoss.md index 628eaa29..52dd25c5 100644 --- a/lib/errors/quantileloss/QuantileLoss.md +++ b/lib/errors/quantileloss/QuantileLoss.md @@ -13,9 +13,7 @@ | **PineScript** | [quantileloss.pine](quantileloss.pine) | - Quantile Loss (also called Pinball Loss) measures prediction accuracy with asymmetric penalties for over-prediction versus under-prediction. -- Parameterized by `period`, `quantile` (default 0.5). -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [MAE](../mae/Mae.md), [Huber](../huber/Huber.md) | **Trading note:** Asymmetric loss for quantile regression; set tau to penalize over/under-prediction differently. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Quantile Loss (also called Pinball Loss) measures prediction accuracy with asymmetric penalties for over-prediction versus under-prediction. It's essential for probabilistic forecasting where different quantiles of the distribution matter. @@ -178,4 +176,4 @@ With τ=0.9, under-predictions are penalized 9x more than over-predictions. * [MAE](../mae/Mae.md) - Mean Absolute Error (equivalent to τ=0.5 × 2) * [Huber](../huber/Huber.md) - Huber Loss (robust symmetric) -* [MAPE](../mape/Mape.md) - Mean Absolute Percentage Error +* [MAPE](../mape/Mape.md) - Mean Absolute Percentage Error \ No newline at end of file diff --git a/lib/errors/rae/Rae.md b/lib/errors/rae/Rae.md index a47abb34..8f685543 100644 --- a/lib/errors/rae/Rae.md +++ b/lib/errors/rae/Rae.md @@ -13,9 +13,7 @@ | **PineScript** | [rae.pine](rae.pine) | - Relative Absolute Error (RAE) measures the total absolute error of predictions relative to the total absolute error of a simple baseline predictor ... -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MASE](../mase/Mase.md), [MRAE](../mrae/Mrae.md) | **Trading note:** Relative Absolute Error; total absolute error relative to naïve model. <1 = outperforms naïve. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Relative Absolute Error (RAE) measures the total absolute error of predictions relative to the total absolute error of a simple baseline predictor that always predicts the mean of actual values. This provides a normalized performance metric. @@ -136,4 +134,4 @@ RAE is preferable when: * You want robustness to outliers (absolute vs squared errors) * You need a ratio interpretation (< 1 is good, > 1 is bad) -* The mean predictor is a relevant baseline for your domain +* The mean predictor is a relevant baseline for your domain \ No newline at end of file diff --git a/lib/errors/rmse/Rmse.md b/lib/errors/rmse/Rmse.md index 921c96fc..010fcc1f 100644 --- a/lib/errors/rmse/Rmse.md +++ b/lib/errors/rmse/Rmse.md @@ -13,9 +13,7 @@ | **PineScript** | [rmse.pine](rmse.pine) | - Root Mean Squared Error (RMSE) is the square root of MSE, providing an error metric in the same units as the original data while retaining sensitiv... -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [MSE](../mse/Mse.md), [MAE](../mae/Mae.md) | **Trading note:** Root Mean Squared Error; same units as input, emphasizes large deviations. Most common accuracy metric. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Root Mean Squared Error (RMSE) is the square root of MSE, providing an error metric in the same units as the original data while retaining sensitivity to large errors. @@ -76,4 +74,4 @@ Batch SIMD: 4x-8x speedup for large windows. ~3-5 cy/bar amortized in vectorized ## Related Indicators * [MSE](../mse/Mse.md) - Mean Squared Error -* [MAE](../mae/Mae.md) - Mean Absolute Error +* [MAE](../mae/Mae.md) - Mean Absolute Error \ No newline at end of file diff --git a/lib/errors/rmsle/Rmsle.md b/lib/errors/rmsle/Rmsle.md index b0d2dbbe..aeb9d37b 100644 --- a/lib/errors/rmsle/Rmsle.md +++ b/lib/errors/rmsle/Rmsle.md @@ -13,9 +13,7 @@ | **PineScript** | [rmsle.pine](rmsle.pine) | - Root Mean Squared Logarithmic Error is the square root of MSLE, providing an error metric in log-scale units. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MSLE](../msle/Msle.md), [RMSE](../rmse/Rmse.md) | **Trading note:** Root Mean Squared Log Error; measures relative error magnitude. Useful for price ratios. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Root Mean Squared Logarithmic Error is the square root of MSLE, providing an error metric in log-scale units. This makes RMSLE more interpretable than MSLE while retaining all its benefits for data spanning multiple orders of magnitude. @@ -225,4 +223,4 @@ Small absolute values near zero can produce large RMSLE: * [MSLE](../msle/Msle.md) - Squared version without root * [RMSE](../rmse/Rmse.md) - Linear-scale root mean squared error -* [MAPE](../mape/Mape.md) - Percentage error without log transform +* [MAPE](../mape/Mape.md) - Percentage error without log transform \ No newline at end of file diff --git a/lib/errors/rse/Rse.md b/lib/errors/rse/Rse.md index ef4fc194..17672d56 100644 --- a/lib/errors/rse/Rse.md +++ b/lib/errors/rse/Rse.md @@ -13,9 +13,7 @@ | **PineScript** | [rse.pine](rse.pine) | - Relative Squared Error (RSE) measures the total squared error of predictions relative to the total squared error of a simple baseline predictor tha... -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [RMSE](../rmse/Rmse.md), [Rsquared](../rsquared/Rsquared.md) | **Trading note:** Relative Squared Error; normalized by variance of actuals. >1 = worse than mean prediction. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Relative Squared Error (RSE) measures the total squared error of predictions relative to the total squared error of a simple baseline predictor that always predicts the mean. RSE is directly related to the coefficient of determination (R²). @@ -140,4 +138,4 @@ Rse.Batch(actualSpan, predictedSpan, outputSpan, 14); | **Outlier sensitivity** | High | Low | | **Related to** | R² | — | | **Baseline** | Mean predictor | Mean predictor | -| **Interpretation** | 1 - R² | Better/worse than mean | +| **Interpretation** | 1 - R² | Better/worse than mean | \ No newline at end of file diff --git a/lib/errors/rsquared/Rsquared.md b/lib/errors/rsquared/Rsquared.md index 9001671e..bc12ba56 100644 --- a/lib/errors/rsquared/Rsquared.md +++ b/lib/errors/rsquared/Rsquared.md @@ -13,9 +13,7 @@ | **PineScript** | [rsquared.pine](rsquared.pine) | - The Coefficient of Determination (R²) measures the proportion of variance in the actual values that is predictable from the predicted values. -- Parameterized by `period`. -- Output range: $(-\infty, 1]$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [RSE](../rse/Rse.md), [Correlation](../../statistics/correlation/Correlation.md) | **Trading note:** R-squared (coefficient of determination); 1.0 = perfect fit, 0 = no better than mean. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Coefficient of Determination (R²) measures the proportion of variance in the actual values that is predictable from the predicted values. R² ranges from negative infinity to 1, where 1 indicates perfect predictions. @@ -149,4 +147,4 @@ Rsquared.Batch(actualSpan, predictedSpan, outputSpan, 14); * **Use R²** when you want an intuitive measure of model quality (0-1 scale for good models) * **Use RSE** when you want to compare error magnitudes directly -* **Use both** to get complementary perspectives on model performance +* **Use both** to get complementary perspectives on model performance \ No newline at end of file diff --git a/lib/errors/smape/Smape.md b/lib/errors/smape/Smape.md index c7794968..3e9ab3bd 100644 --- a/lib/errors/smape/Smape.md +++ b/lib/errors/smape/Smape.md @@ -13,9 +13,7 @@ | **PineScript** | [smape.pine](smape.pine) | - Symmetric Mean Absolute Percentage Error addresses a fundamental asymmetry in MAPE: the fact that over-predictions and under-predictions of the sam... -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MAPE](../mape/Mape.md), [MAAPE](../maape/Maape.md) | **Trading note:** Symmetric MAPE; bounded 0–200%, handles zeros better than MAPE. Common in forecasting competitions. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Symmetric Mean Absolute Percentage Error addresses a fundamental asymmetry in MAPE: the fact that over-predictions and under-predictions of the same magnitude receive different penalties. SMAPE uses the average of actual and predicted values in the denominator, creating a metric that treats both directions equally. @@ -182,4 +180,4 @@ This scales to 0-100% but is mathematically equivalent to the 0-200% version. Qu * [MAPE](../mape/Mape.md) - Asymmetric percentage error * [MPE](../mpe/Mpe.md) - Signed percentage error for bias -* [MAE](../mae/Mae.md) - Absolute error without scaling +* [MAE](../mae/Mae.md) - Absolute error without scaling \ No newline at end of file diff --git a/lib/errors/theilu/TheilU.md b/lib/errors/theilu/TheilU.md index 26b4541e..b3881cdb 100644 --- a/lib/errors/theilu/TheilU.md +++ b/lib/errors/theilu/TheilU.md @@ -13,9 +13,7 @@ | **PineScript** | [theilu.pine](theilu.pine) | - Theil's U Statistic measures forecast accuracy relative to a naive no-change forecast. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MASE](../mase/Mase.md), [Rsquared](../rsquared/Rsquared.md) | **Trading note:** Theil's U statistic; <1 = forecast beats naïve, >1 = worse than naïve random walk. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Theil's U Statistic measures forecast accuracy relative to a naive no-change forecast. A value below 1 indicates the model outperforms simply predicting that tomorrow equals today; above 1 means you'd be better off not forecasting at all. @@ -171,4 +169,4 @@ Batch MSE accumulation vectorizable; final ratio is scalar. ~8 cy/bar for square * [RMSE](../rmse/Rmse.md) - Root Mean Squared Error (absolute, not relative) * [MASE](../mase/Mase.md) - Mean Absolute Scaled Error (similar concept) -* [R-Squared](../rsquared/RSquared.md) - Coefficient of Determination +* [R-Squared](../rsquared/RSquared.md) - Coefficient of Determination \ No newline at end of file diff --git a/lib/errors/tukeybiweight/TukeyBiweight.md b/lib/errors/tukeybiweight/TukeyBiweight.md index d076424f..458a15e9 100644 --- a/lib/errors/tukeybiweight/TukeyBiweight.md +++ b/lib/errors/tukeybiweight/TukeyBiweight.md @@ -13,9 +13,7 @@ | **PineScript** | [tukeybiweight.pine](tukeybiweight.pine) | - Tukey's Biweight (also called Bisquare) is a redescending M-estimator that completely ignores errors beyond a threshold. -- Parameterized by `period`, `c` (default defaultc). -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Huber](../huber/Huber.md), [PseudoHuber](../pseudohuber/PseudoHuber.md) | **Trading note:** Tukey's biweight loss; completely rejects extreme outliers beyond tuning constant c. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Tukey's Biweight (also called Bisquare) is a redescending M-estimator that completely ignores errors beyond a threshold. Unlike Huber loss which still penalizes large errors linearly, Tukey's biweight treats extreme outliers as if they don't exist. @@ -182,4 +180,4 @@ Tukey's biweight is the only loss function that completely stops penalizing erro * [Huber](../huber/Huber.md) - Huber Loss (linear, not redescending) * [MdAE](../mdae/Mdae.md) - Median Absolute Error (robust via median) -* [LogCosh](../logcosh/LogCosh.md) - Log-Cosh Loss (smooth L1/L2 hybrid) +* [LogCosh](../logcosh/LogCosh.md) - Log-Cosh Loss (smooth L1/L2 hybrid) \ No newline at end of file diff --git a/lib/errors/wmape/Wmape.md b/lib/errors/wmape/Wmape.md index 643a0d4b..fb1821d1 100644 --- a/lib/errors/wmape/Wmape.md +++ b/lib/errors/wmape/Wmape.md @@ -13,9 +13,7 @@ | **PineScript** | [wmape.pine](wmape.pine) | - Weighted Mean Absolute Percentage Error (WMAPE) adjusts MAPE by weighting each error by the magnitude of the actual value. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MAPE](../mape/Mape.md), [MAPD](../mapd/Mapd.md) | **Trading note:** Weighted MAPE; weights errors by actual values. More stable than MAPE for intermittent demand. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Weighted Mean Absolute Percentage Error (WMAPE) adjusts MAPE by weighting each error by the magnitude of the actual value. This produces a single, interpretable percentage that represents overall accuracy weighted by importance. @@ -174,4 +172,4 @@ WMAPE gives less weight to the small-volume item with high percentage error. * [MAPE](../mape/Mape.md) - Mean Absolute Percentage Error (unweighted) * [MAE](../mae/Mae.md) - Mean Absolute Error (non-percentage) -* [SMAPE](../smape/Smape.md) - Symmetric MAPE +* [SMAPE](../smape/Smape.md) - Symmetric MAPE \ No newline at end of file diff --git a/lib/errors/wrmse/Wrmse.md b/lib/errors/wrmse/Wrmse.md index 4c437495..2994d3ae 100644 --- a/lib/errors/wrmse/Wrmse.md +++ b/lib/errors/wrmse/Wrmse.md @@ -13,9 +13,7 @@ | **PineScript** | [wrmse.pine](wrmse.pine) | - WRMSE extends the classic RMSE by incorporating weights for each observation, enabling analysts to emphasize critical data points such as recent ob... -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [RMSE](../rmse/Rmse.md), [WMAPE](../wmape/Wmape.md) | **Trading note:** Weighted RMSE; emphasizes accuracy at specific points. Useful for time-decay weighting. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. WRMSE extends the classic RMSE by incorporating weights for each observation, enabling analysts to emphasize critical data points such as recent observations, high-volume periods, or specific market regimes. When all weights are equal, WRMSE reduces exactly to RMSE, making it a strict generalization. This implementation uses dual RingBuffers for O(1) streaming updates with periodic resync to manage floating-point drift. @@ -185,4 +183,4 @@ WRMSE is validated by: - Aitken, A.C. (1936). "On Least Squares and Linear Combinations of Observations." *Proceedings of the Royal Society of Edinburgh*. - Gauss, C.F. (1809). *Theoria Motus Corporum Coelestium*. (Foundation of least squares theory) -- Greene, W.H. (2012). *Econometric Analysis*. 7th ed. Chapter 9: Generalized Least Squares. +- Greene, W.H. (2012). *Econometric Analysis*. 7th ed. Chapter 9: Generalized Least Squares. \ No newline at end of file diff --git a/lib/feeds/IFeed.md b/lib/feeds/IFeed.md index 78b79de5..2274c503 100644 --- a/lib/feeds/IFeed.md +++ b/lib/feeds/IFeed.md @@ -9,11 +9,12 @@ | **Output range** | Varies (see docs) | | **Warmup** | 1 bar | -- `IFeed` defines the standard contract for all data feeds in QuanTAlib, ensuring consistent behavior across different data sources (synthetic, file-... +- `IFeed` defines the standard contract for all data feeds in QuanTAlib, ensuring consistent behavior across different data sources (synthetic, file-based, or live API). - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. +- Feeds are the entry point of any indicator chain — all indicators subscribe to a feed or to another indicator's output. +- Common feed implementations include synthetic (GBM), file-based (CSV), and live API sources (Alpha Vantage). +- For backtesting, pair feeds with any trend, momentum, or volatility indicator to simulate streaming bar-by-bar processing. `IFeed` defines the standard contract for all data feeds in QuanTAlib, ensuring consistent behavior across different data sources (synthetic, file-based, or live API). diff --git a/lib/feeds/csvfeed/CsvFeed.md b/lib/feeds/csvfeed/CsvFeed.md index 7a052dea..f11198dc 100644 --- a/lib/feeds/csvfeed/CsvFeed.md +++ b/lib/feeds/csvfeed/CsvFeed.md @@ -10,9 +10,6 @@ | **Warmup** | 1 bar | - `CsvFeed` is a file-based feed implementation that loads historical OHLCV data from CSV files. -- Parameterized by `filepath`. -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. `CsvFeed` is a file-based feed implementation that loads historical OHLCV data from CSV files. It supports both streaming access (simulating real-time playback) and batch retrieval. @@ -84,4 +81,4 @@ while (true) ```csharp long startTime = new DateTime(2024, 1, 1).Ticks; -var batch = feed.Fetch(10, startTime, TimeSpan.FromDays(1)); +var batch = feed.Fetch(10, startTime, TimeSpan.FromDays(1)); \ No newline at end of file diff --git a/lib/feeds/gbm/GBM.md b/lib/feeds/gbm/GBM.md index a63b7a0d..0d7385ed 100644 --- a/lib/feeds/gbm/GBM.md +++ b/lib/feeds/gbm/GBM.md @@ -11,8 +11,6 @@ - `GBM` (Geometric Brownian Motion) is a synthetic data generator that simulates realistic financial price movements. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. `GBM` (Geometric Brownian Motion) is a synthetic data generator that simulates realistic financial price movements. It is useful for testing indicators, strategies, and system performance without relying on external data files. @@ -83,4 +81,4 @@ long startTime = DateTime.UtcNow.Ticks; var interval = TimeSpan.FromMinutes(1); // Generate 1000 bars -var history = gbm.Fetch(1000, startTime, interval); +var history = gbm.Fetch(1000, startTime, interval); \ No newline at end of file diff --git a/lib/filters/agc/Agc.md b/lib/filters/agc/Agc.md index 47b52b75..0549a5a0 100644 --- a/lib/filters/agc/Agc.md +++ b/lib/filters/agc/Agc.md @@ -13,9 +13,7 @@ | **PineScript** | [agc.pine](agc.pine) | - The Automatic Gain Control normalizes any oscillating signal to the \[-1, +1\] range through exponential peak tracking. -- Parameterized by `decay` (default 0.991). -- Output range: [-1, +1] (normalized amplitude). -- Requires `1` bar of warmup before first valid output (IsHot = true). +- **Similar:** [Kalman](../kalman/Kalman.md), [LMS](../lms/Lms.md) | **Complementary:** ATR for volatility context | **Trading note:** Automatic Gain Control; normalizes signal amplitude adaptively. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -181,4 +179,4 @@ source.Add(new TValue(DateTime.UtcNow, close)); ## References - Ehlers, J. F. "The Universal Oscillator." *Technical Analysis of Stocks & Commodities*, January 2015. -- Ehlers, J. F. *Cycle Analytics for Traders*. Wiley, 2013. +- Ehlers, J. F. *Cycle Analytics for Traders*. Wiley, 2013. \ No newline at end of file diff --git a/lib/filters/alaguerre/ALaguerre.md b/lib/filters/alaguerre/ALaguerre.md index 3d1911bc..e9d41787 100644 --- a/lib/filters/alaguerre/ALaguerre.md +++ b/lib/filters/alaguerre/ALaguerre.md @@ -14,9 +14,7 @@ | **Signature** | [alaguerre_signature](alaguerre_signature.md) | - The Adaptive Laguerre Filter extends Ehlers' four-element all-pass cascade by replacing the fixed damping factor with a per-bar adaptive alpha deri... -- Parameterized by `length` (default 20), `medianlength` (default 5). -- Output range: Tracks input. -- Requires `max(4, length)` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Laguerre](../laguerre/Laguerre.md), [SSF2](../ssf2/Ssf2.md) | **Complementary:** RSI for momentum | **Trading note:** Adaptive Laguerre filter by Ehlers; adjusts damping based on market conditions. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -185,4 +183,4 @@ Since the Adaptive Laguerre Filter is a custom Ehlers indicator not found in sta - Ehlers, John F. *Cybernetic Analysis for Stocks and Futures*. Wiley, 2004. ISBN: 978-0-471-46307-8. - WiseStockTrader Amibroker AFL: Adaptive Laguerre Filter implementation. -- Ehlers, John F. "Laguerre Filter." *Technical Analysis of Stocks and Commodities*, various issues. +- Ehlers, John F. "Laguerre Filter." *Technical Analysis of Stocks and Commodities*, various issues. \ No newline at end of file diff --git a/lib/filters/baxterking/BaxterKing.md b/lib/filters/baxterking/BaxterKing.md index 71471468..b57f6808 100644 --- a/lib/filters/baxterking/BaxterKing.md +++ b/lib/filters/baxterking/BaxterKing.md @@ -13,9 +13,7 @@ | **PineScript** | [baxterking.pine](baxterking.pine) | - The **Baxter-King Band-Pass Filter** is a symmetric finite impulse response (FIR) filter that approximates the ideal spectral band-pass by truncati... -- Parameterized by `plow` (default 6), `phigh` (default 32), `k` (default 12). -- Output range: Oscillates around zero (extracts cyclical component). -- Requires `2K+1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Cfitz](../cfitz/Cfitz.md), [BPF](../bpf/Bpf.md) | **Complementary:** Hilbert Transform for phase | **Trading note:** Baxter-King bandpass filter; isolates business cycle frequencies. Symmetric FIR. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The **Baxter-King Band-Pass Filter** is a symmetric finite impulse response (FIR) filter that approximates the ideal spectral band-pass by truncating the infinite sinc-like impulse response at lag $K$ and normalizing the weights to sum to zero. It extracts cyclical components with periodicities between $p_L$ (low) and $p_H$ (high) bars, rejecting both the DC trend and high-frequency noise. Output oscillates around zero with a fixed delay of $K$ bars. @@ -197,4 +195,4 @@ var (results, indicator) = BaxterKing.Calculate(series, pLow: 6, pHigh: 32, k: 1 var source = new TSeries(); var bkChained = new BaxterKing(source, pLow: 6, pHigh: 32, k: 12); source.Add(new TValue(DateTime.UtcNow, price)); // bkChained.Last auto-updates -``` +``` \ No newline at end of file diff --git a/lib/filters/bessel/Bessel.md b/lib/filters/bessel/Bessel.md index a5caf26a..e4ce4b3f 100644 --- a/lib/filters/bessel/Bessel.md +++ b/lib/filters/bessel/Bessel.md @@ -14,9 +14,7 @@ | **Signature** | [bessel_signature](bessel_signature.md) | - The Bessel Filter is a 2nd-order low-pass IIR filter designed to preserve the **shape** and **timing** of price moves. -- Parameterized by `length`. -- Output range: Tracks input. -- Requires `length` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Butter2](../butter2/Butter2.md), [Gauss](../gauss/Gauss.md) | **Complementary:** ATR for volatility | **Trading note:** Bessel filter; maximally flat group delay (linear phase). Best for preserving waveform shape. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. > When you care more about *when* the market turns than how aggressively you can torture the noise, you reach for a Bessel. @@ -157,4 +155,4 @@ Validation focuses on internal consistency between streaming, TSeries, and Span * **Misinterpreting flat response as “weak” filter:** The goal is not to crush all noise. The goal is to keep enough structure that pattern recognition, divergence analysis, and multi-stream alignment still make sense. * **Ignoring NaN propagation:** If your upstream feed throws `NaN` or infinities and you do not clean it, BESSEL will fall back to the last valid value. This is intentional. If you want gaps instead, preprocess the series and pass explicit masked values. -Used correctly, BESSEL gives you a **shape-faithful trend line** with clean timing and low overshoot, ideal for traders who care more about *when* than *how loudly* the filter shouts. +Used correctly, BESSEL gives you a **shape-faithful trend line** with clean timing and low overshoot, ideal for traders who care more about *when* than *how loudly* the filter shouts. \ No newline at end of file diff --git a/lib/filters/bilateral/Bilateral.md b/lib/filters/bilateral/Bilateral.md index 8c169817..4f8528ea 100644 --- a/lib/filters/bilateral/Bilateral.md +++ b/lib/filters/bilateral/Bilateral.md @@ -14,9 +14,7 @@ | **Signature** | [bilateral_signature](bilateral_signature.md) | - The Bilateral Filter is a non-linear, edge-preserving, and noise-reducing smoothing filter. -- Parameterized by `period`, `sigmasratio` (default 0.5), `sigmarmult` (default 1.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Kalman](../kalman/Kalman.md), [RMed](../rmed/Rmed.md) | **Complementary:** Volume for weight adjustment | **Trading note:** Bilateral filter; preserves edges (sudden price moves) while smoothing noise. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Bilateral Filter is a non-linear, edge-preserving, and noise-reducing smoothing filter. Unlike standard Gaussian filters that blur everything indiscriminately, the Bilateral Filter respects strong edges by weighting pixels based on both their spatial distance and their intensity difference (range). @@ -121,4 +119,4 @@ var bilateral = new Bilateral(14, sigmaSRatio: 0.5, sigmaRMult: 1.0); // Update with new price var result = bilateral.Update(new TValue(DateTime.UtcNow, 100.0)); -Console.WriteLine($"Bilateral: {result.Value}"); +Console.WriteLine($"Bilateral: {result.Value}"); \ No newline at end of file diff --git a/lib/filters/bpf/Bpf.md b/lib/filters/bpf/Bpf.md index ca09872a..f9d676d0 100644 --- a/lib/filters/bpf/Bpf.md +++ b/lib/filters/bpf/Bpf.md @@ -13,9 +13,7 @@ | **PineScript** | [bpf.pine](bpf.pine) | - The **BPF** (BandPass Filter) is a second-order IIR architecture designed to surgically excise specific frequency components from a time series. -- Parameterized by `lowerperiod`, `upperperiod`. -- Output range: Oscillates around zero (bandpass extracts cyclic component). -- Requires `Math.Max(lowerPeriod, upperPeriod)` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BaxterKing](../baxterking/BaxterKing.md), [Notch](../notch/Notch.md) | **Complementary:** Cycle indicators | **Trading note:** Bandpass filter; isolates a specific frequency band. Used for cycle extraction. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The **BPF** (BandPass Filter) is a second-order IIR architecture designed to surgically excise specific frequency components from a time series. By cascading a HighPass Filter (to reject trend) and a LowPass Filter (to reject noise), it isolates cyclic energy within a user-defined window. Unlike simple moving average crossovers which smear data, the BPF relies on Gaussian-based coefficients to achieve steeper roll-off with deterministic phase characteristics. @@ -124,4 +122,4 @@ var result = bpf.Update(new TValue(DateTime.UtcNow, price)); // Static Analysis (Zero Allocation) double[] output = new double[prices.Length]; Bpf.Calculate(prices, output, 40, 10); -``` +``` \ No newline at end of file diff --git a/lib/filters/butter2/Butter2.md b/lib/filters/butter2/Butter2.md index 4048a527..f01276c4 100644 --- a/lib/filters/butter2/Butter2.md +++ b/lib/filters/butter2/Butter2.md @@ -14,9 +14,7 @@ | **Signature** | [butter2_signature](butter2_signature.md) | - The 2-Pole Butterworth Filter (BUTTER2) is a signal processing tool designed to provide maximally flat frequency response in the passband. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `4 * period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Butter3](../butter3/Butter3.md), [Bessel](../bessel/Bessel.md) | **Complementary:** Ehlers cycle indicators | **Trading note:** 2nd-order Butterworth; maximally flat passband. Classic IIR low-pass filter. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The 2-Pole Butterworth Filter (BUTTER2) is a signal processing tool designed to provide maximally flat frequency response in the passband. Developed by British engineer Stephen Butterworth in 1930, it offers traders a means to smooth price data without introducing ripples in the frequency response. This implementation provides a 2nd-order low-pass filter that effectively removes high-frequency market noise while preserving lower-frequency trend components. Compared to other filters, Butterworth offers an optimal compromise between smoothing efficiency and signal fidelity, making it a versatile choice for various market conditions. @@ -108,4 +106,4 @@ double result = butter.Update(price).Value; // Batch var series = Butter2.Calculate(sourceSeries, period: 14); -``` +``` \ No newline at end of file diff --git a/lib/filters/butter3/Butter3.md b/lib/filters/butter3/Butter3.md index f0a73914..38e65a5f 100644 --- a/lib/filters/butter3/Butter3.md +++ b/lib/filters/butter3/Butter3.md @@ -14,9 +14,7 @@ | **Signature** | [butter3_signature](butter3_signature.md) | - The 3-Pole Butterworth Filter (BUTTER3) extends the classic Butterworth design to third order, providing -60 dB/decade rolloff compared to -40 dB/d... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `6 * period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Butter2](../butter2/Butter2.md), [Elliptic](../elliptic/Elliptic.md) | **Complementary:** Phase analysis tools | **Trading note:** 3rd-order Butterworth; steeper rolloff than 2nd-order but more phase distortion. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The 3-Pole Butterworth Filter (BUTTER3) extends the classic Butterworth design to third order, providing -60 dB/decade rolloff compared to -40 dB/decade for the 2-pole variant. Developed from John Ehlers' formulation in "Cybernetic Analysis for Stocks and Futures" (2004), this implementation uses the same pole placement as the 3-pole Super Smoother (SSF3) but with binomial (1,3,3,1) feedforward weights that preserve the maximally flat passband characteristic. The steeper rolloff makes BUTTER3 more effective at rejecting high-frequency noise, at the cost of slightly more lag than BUTTER2. @@ -129,4 +127,4 @@ Butter3.Batch(sourceSpan, destSpan, period: 20, initialLast: double.NaN); ## References * Ehlers, John F. "Cybernetic Analysis for Stocks and Futures." Wiley, 2004. -* Butterworth, Stephen. "On the Theory of Filter Amplifiers." Experimental Wireless and the Wireless Engineer, 1930. +* Butterworth, Stephen. "On the Theory of Filter Amplifiers." Experimental Wireless and the Wireless Engineer, 1930. \ No newline at end of file diff --git a/lib/filters/cfitz/Cfitz.md b/lib/filters/cfitz/Cfitz.md index 269c9673..8e517ec4 100644 --- a/lib/filters/cfitz/Cfitz.md +++ b/lib/filters/cfitz/Cfitz.md @@ -13,9 +13,7 @@ | **PineScript** | [cfitz.pine](cfitz.pine) | - The **Christiano-Fitzgerald Band-Pass Filter** is an asymmetric full-sample filter that approximates the ideal spectral band-pass by using time-var... -- Parameterized by `plow` (default 6), `phigh` (default 32). -- Output range: Oscillates around zero (extracts cyclical component). -- Requires `2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BaxterKing](../baxterking/BaxterKing.md), [HP](../hp/Hp.md) | **Complementary:** Trend indicators | **Trading note:** Christiano-Fitzgerald bandpass filter; asymmetric, optimal for finite samples. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Overview @@ -183,4 +181,4 @@ var (results, indicator) = Cfitz.Calculate(series, pLow: 6, pHigh: 32); var source = new TSeries(); var cfChained = new Cfitz(source, pLow: 6, pHigh: 32); source.Add(new TValue(DateTime.UtcNow, price)); // cfChained.Last auto-updates -``` +``` \ No newline at end of file diff --git a/lib/filters/cheby1/Cheby1.md b/lib/filters/cheby1/Cheby1.md index dc465e81..8dbf7889 100644 --- a/lib/filters/cheby1/Cheby1.md +++ b/lib/filters/cheby1/Cheby1.md @@ -14,9 +14,7 @@ | **Signature** | [cheby1_signature](cheby1_signature.md) | - The Chebyshev Type I filter minimizes the error between the idealized and the actual filter characteristic over the range of the passband, but with... -- Parameterized by `period`, `ripple` (default 1.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Cheby2](../cheby2/Cheby2.md), [Elliptic](../elliptic/Elliptic.md) | **Complementary:** ATR for stop distance | **Trading note:** Chebyshev Type I; passband ripple for sharper transition. Steeper than Butterworth. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Chebyshev Type I filter minimizes the error between the idealized and the actual filter characteristic over the range of the passband, but with ripples in the passband. This type of filter has a steeper rolloff and more passband ripple (type I) or stopband ripple (type II) than Butterworth filters. @@ -109,4 +107,4 @@ IIR filters cannot be vectorized across the time axis due to their recursive str ## References -- [Chebyshev filter - Wikipedia](https://en.wikipedia.org/wiki/Chebyshev_filter) +- [Chebyshev filter - Wikipedia](https://en.wikipedia.org/wiki/Chebyshev_filter) \ No newline at end of file diff --git a/lib/filters/cheby2/Cheby2.md b/lib/filters/cheby2/Cheby2.md index b8f996e4..ee3a5a03 100644 --- a/lib/filters/cheby2/Cheby2.md +++ b/lib/filters/cheby2/Cheby2.md @@ -14,9 +14,7 @@ | **Signature** | [cheby2_signature](cheby2_signature.md) | - A Chebyshev Type II filter (also known as Inverse Chebyshev) with O(1) complexity. -- Parameterized by `period`, `attenuation` (default 5.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Cheby1](../cheby1/Cheby1.md), [Elliptic](../elliptic/Elliptic.md) | **Complementary:** Trend strength indicators | **Trading note:** Chebyshev Type II; flat passband with stopband ripple. No overshoot in passband. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. A Chebyshev Type II filter (also known as Inverse Chebyshev) with O(1) complexity. Unlike the Type I filter, Type II is maximally flat in the passband (like Butterworth) but has equiripple in the stopband. @@ -85,4 +83,4 @@ Console.WriteLine($"Filter value: {result.Value}"); ## complexity - **Time**: O(1) per update. -- **Space**: O(1) constant storage. +- **Space**: O(1) constant storage. \ No newline at end of file diff --git a/lib/filters/edcf/Edcf.md b/lib/filters/edcf/Edcf.md index b2fc3172..40f4068e 100644 --- a/lib/filters/edcf/Edcf.md +++ b/lib/filters/edcf/Edcf.md @@ -14,9 +14,7 @@ | **Signature** | [edcf_signature](edcf_signature.md) | - The **Ehlers Distance Coefficient Filter (EDCF)** is a nonlinear adaptive FIR filter created by John F. -- Parameterized by `length` (default 15). -- Output range: Tracks input. -- Requires `length` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HP](../hp/Hp.md), [SSF2](../ssf2/Ssf2.md) | **Complementary:** Cycle period detection | **Trading note:** Ehlers Distance Coefficient Filter; adapts to dominant cycle period. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Overview @@ -160,4 +158,4 @@ SIMD reduces the inner loop throughput by 4x-8x but does not change the O(N^2) c ## References 1. Ehlers, J. F. "Ehlers Filters." MESA Software. [PDF](https://www.mesasoftware.com/papers/EhlersFilters.pdf) -2. Ehlers, J. F. "Nonlinear Ehlers Filters." *Stocks & Commodities*, V.19:4, pp.25-34. +2. Ehlers, J. F. "Nonlinear Ehlers Filters." *Stocks & Commodities*, V.19:4, pp.25-34. \ No newline at end of file diff --git a/lib/filters/elliptic/Elliptic.md b/lib/filters/elliptic/Elliptic.md index a8139397..ac9aafbb 100644 --- a/lib/filters/elliptic/Elliptic.md +++ b/lib/filters/elliptic/Elliptic.md @@ -14,9 +14,7 @@ | **Signature** | [elliptic_signature](elliptic_signature.md) | - The Elliptic filter (or Cauer filter for the history buffs) is the uncompromising extremist of linear filtering. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Cheby1](../cheby1/Cheby1.md), [Butter2](../butter2/Butter2.md) | **Complementary:** Phase analysis | **Trading note:** Elliptic (Cauer) filter; sharpest transition of all IIR filters but has ripple in both bands. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Elliptic filter (or Cauer filter for the history buffs) is the uncompromising extremist of linear filtering. It offers the steepest possible roll-off for a given order, but extracts a heavy price: ripple in both the passband and the stopband. While Butterworth is polite and Chebyshev is opinionated, Elliptic is aggressive. This implementation delivers a sharp 2nd-order Lowpass response with **1dB passband ripple** and a crushing **40dB stopband attenuation**. @@ -90,4 +88,4 @@ Correctness is non-negotiable. | :--- | :--- | :--- | | **PineScript** | ✅ | Matches the reference implementation logic. | | **Python** | ✅ | Validated against scipy.signal.cheby1 (proxy) and noise reduction tests. | -| **Stability** | ✅ | Unity gain enforced. Transient suppression active. | +| **Stability** | ✅ | Unity gain enforced. Transient suppression active. | \ No newline at end of file diff --git a/lib/filters/gauss/Gauss.md b/lib/filters/gauss/Gauss.md index 8db32d70..d555adf8 100644 --- a/lib/filters/gauss/Gauss.md +++ b/lib/filters/gauss/Gauss.md @@ -15,9 +15,7 @@ - Gauss (Gaussian Filter) is a smoothing filter that applies a Gaussian kernel to time series data. -- Parameterized by `sigma` (default 1.0). -- Output range: Tracks input. -- Requires `2⌈3σ⌉+1` bars of warmup before first valid output (IsHot = true). Default: **7 bars** (σ=1.0). +- **Similar:** [Bessel](../bessel/Bessel.md), [SSF2](../ssf2/Ssf2.md) | **Complementary:** ATR for volatility bands | **Trading note:** Gaussian filter; IIR approximation of the Gaussian window. Smooth with minimal overshoot. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Gauss (Gaussian Filter) is a smoothing filter that applies a Gaussian kernel to time series data. Unlike Simple Moving Average (SMA), which weights all points in the window equally (boxcar function), the Gaussian filter applies weights that follow a bell curve distribution. This minimizes lag while providing superior noise reduction and significantly better preservation of signal edges. @@ -125,4 +123,4 @@ var result = gauss.Update(new TValue(DateTime.UtcNow, 100.0)); Gauss.Calculate(inputSpan, outputSpan, sigma: 2.0); // Use with a higher sigma for stronger smoothing -var smoothGauss = new Gauss(sigma: 3.0); // Window ~19 +var smoothGauss = new Gauss(sigma: 3.0); // Window ~19 \ No newline at end of file diff --git a/lib/filters/hann/Hann.md b/lib/filters/hann/Hann.md index 1b7e190b..6b8e31fb 100644 --- a/lib/filters/hann/Hann.md +++ b/lib/filters/hann/Hann.md @@ -14,9 +14,7 @@ | **Signature** | [hann_signature](hann_signature.md) | - Hann (Hann Filter) is a Finite Impulse Response (FIR) smoothing filter that applies a Hann window to time series data. -- Parameterized by `length`. -- Output range: Tracks input. -- Requires `length` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Gauss](../gauss/Gauss.md), [Bessel](../bessel/Bessel.md) | **Complementary:** Cycle analysis tools | **Trading note:** Hann window filter; smooth taper to zero at edges. Good spectral properties. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Hann (Hann Filter) is a Finite Impulse Response (FIR) smoothing filter that applies a Hann window to time series data. Named after Julius von Hann, this filter uses a cosine-sum window function that tapers inputs to zero at the edges. This tapering process significantly reduces spectral leakage and provides excellent high-frequency noise attenuation compared to a Simple Moving Average (SMA). @@ -116,4 +114,4 @@ var result = hann.Update(new TValue(DateTime.UtcNow, 100.0)); Hann.Calculate(inputSpan, outputSpan, length: 20); // Use with a publisher -var hannLive = new Hann(source, length: 20); +var hannLive = new Hann(source, length: 20); \ No newline at end of file diff --git a/lib/filters/hp/Hp.md b/lib/filters/hp/Hp.md index 1401a8d7..e6685e1b 100644 --- a/lib/filters/hp/Hp.md +++ b/lib/filters/hp/Hp.md @@ -15,9 +15,7 @@ - The Hodrick-Prescott (HP) filter is a widely used tool in macroeconomics for separating the cyclical component of a time series from raw data. -- Parameterized by `lambda` (default 1600.0). -- Output range: Tracks input. -- Requires `⌈2√λ⌉` bars of warmup before first valid output (IsHot = true). Default: **~80 bars** (λ=1600). +- **Similar:** [HPF](../hpf/Hpf.md), [Roofing](../roofing/Roofing.md) | **Complementary:** Low-pass filter for trend | **Trading note:** Hodrick-Prescott filter; separates trend from cycle component. Lambda controls smoothness. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Hodrick-Prescott (HP) filter is a widely used tool in macroeconomics for separating the cyclical component of a time series from raw data. While the standard HP filter is non-causal (requiring future data), this implementation uses a causal approximation suitable for real-time streaming analysis. @@ -112,4 +110,4 @@ TValue trend = hp.Update(new TValue(time, price)); // Static batch calculation double[] prices = ...; double[] trend = new double[prices.Length]; -Hp.Calculate(prices, trend, 1600); +Hp.Calculate(prices, trend, 1600); \ No newline at end of file diff --git a/lib/filters/hpf/Hpf.md b/lib/filters/hpf/Hpf.md index 5b0b1b57..4bf2322a 100644 --- a/lib/filters/hpf/Hpf.md +++ b/lib/filters/hpf/Hpf.md @@ -13,9 +13,7 @@ | **PineScript** | [hpf.pine](hpf.pine) | - The 2-Pole Highpass Filter (HPF) is designed to separate high-frequency components (like cycles and noise) from the underlying trend. -- Parameterized by `length` (default 40). -- Output range: Oscillates around zero (detrended signal). -- Requires `length` bars of warmup before first valid output (IsHot = true). Default: **40 bars**. +- **Similar:** [HP](../hp/Hp.md), [Roofing](../roofing/Roofing.md) | **Complementary:** SSF for low-pass | **Trading note:** High-pass filter; removes trend, isolates cycles and noise. Ehlers' 1-pole design. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The 2-Pole Highpass Filter (HPF) is designed to separate high-frequency components (like cycles and noise) from the underlying trend. By suppressing low-frequency movements, it acts as a "detrender," making it invaluable for oscillator construction and cycle analysis. @@ -114,4 +112,4 @@ TValue cycle = hpf.Update(new TValue(time, price)); // Static batch calculation double[] prices = ...; double[] cycle = new double[prices.Length]; -Hpf.Calculate(prices, cycle, 40); +Hpf.Calculate(prices, cycle, 40); \ No newline at end of file diff --git a/lib/filters/kalman/Kalman.md b/lib/filters/kalman/Kalman.md index 90f6de37..3bdfc4de 100644 --- a/lib/filters/kalman/Kalman.md +++ b/lib/filters/kalman/Kalman.md @@ -15,9 +15,7 @@ - The **Kalman Filter** is a recursive algorithm that estimates the state of a dynamic system from a series of incomplete and noisy measurements. -- Parameterized by `q` (default 0.01), `r` (default 0.1). -- Output range: Tracks input. -- Requires `10` bars of warmup before first valid output (IsHot = true). +- **Similar:** [LMS](../lms/Lms.md), [RLS](../rls/Rls.md) | **Complementary:** ATR for measurement noise estimation | **Trading note:** Kalman filter; optimal linear estimator. Adapts to changing market dynamics. Widely used in quant finance. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The **Kalman Filter** is a recursive algorithm that estimates the state of a dynamic system from a series of incomplete and noisy measurements. In technical analysis, it acts as a sophisticated smoothing filter that adapts to price changes based on specified noise covariances. Unlike simple moving averages that treat all past data equally or with fixed weights, the Kalman Filter dynamically adjusts its "trust" between its own prediction and the new price data. @@ -126,4 +124,4 @@ Kalman.Calculate(inputs, outputs, q: 0.05, r: 0.5); // Chaining var source = new TSeries(); var kf1 = new Kalman(source, q: 0.01, r: 0.1); -var kf2 = new Kalman(kf1, q: 0.001, r: 0.1); // Double smoothing +var kf2 = new Kalman(kf1, q: 0.001, r: 0.1); // Double smoothing \ No newline at end of file diff --git a/lib/filters/laguerre/Laguerre.md b/lib/filters/laguerre/Laguerre.md index 62ade347..1039b70f 100644 --- a/lib/filters/laguerre/Laguerre.md +++ b/lib/filters/laguerre/Laguerre.md @@ -15,9 +15,7 @@ - The Laguerre Filter is a four-element IIR (Infinite Impulse Response) filter designed by John F. -- Parameterized by `gamma` (default 0.8). -- Output range: Tracks input. -- Requires `WarmupBars` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ALaguerre](../alaguerre/ALaguerre.md), [SSF2](../ssf2/Ssf2.md) | **Complementary:** RSI for momentum | **Trading note:** Laguerre filter by Ehlers; FIR-like response from IIR structure. Damping factor 0–1 controls smoothing. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -171,4 +169,4 @@ Since the Laguerre Filter is not available in standard external validation libra 1. Ehlers, J.F. (2004). *Cybernetic Analysis for Stocks and Futures*. Wiley. ISBN: 978-0-471-46307-8 2. Ehlers, J.F. "EhlersFilters.pdf" — MESA Software technical papers. [mesasoftware.com](https://www.mesasoftware.com/papers/EhlersFilters.pdf) 3. Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley. ISBN: 978-0-471-40567-1 -4. Laguerre, E. (1898). "Sur les fonctions du genre de Laguerre." *Comptes Rendus de l'Académie des Sciences.* +4. Laguerre, E. (1898). "Sur les fonctions du genre de Laguerre." *Comptes Rendus de l'Académie des Sciences.* \ No newline at end of file diff --git a/lib/filters/lms/Lms.md b/lib/filters/lms/Lms.md index bdd4e1e4..f77511ba 100644 --- a/lib/filters/lms/Lms.md +++ b/lib/filters/lms/Lms.md @@ -13,9 +13,7 @@ | **PineScript** | [lms.pine](lms.pine) | - The **Least Mean Squares (LMS) Adaptive Filter** is the Widrow-Hoff adaptive FIR filter, the simplest and most widely deployed adaptive algorithm i... -- Parameterized by `order` (default 16), `mu` (default 0.5). -- Output range: Tracks input. -- Requires `order + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [RLS](../rls/Rls.md), [Kalman](../kalman/Kalman.md) | **Complementary:** Error metrics for convergence monitoring | **Trading note:** Least Mean Squares adaptive filter; tracks changing signal statistics. Low computational cost. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The **Least Mean Squares (LMS) Adaptive Filter** is the Widrow-Hoff adaptive FIR filter, the simplest and most widely deployed adaptive algorithm in signal processing. It maintains an `order`-tap weight vector that learns to predict the current input from its recent history, updating weights via the Normalized LMS (NLMS) gradient descent rule. The result is a price-following overlay filter that automatically adapts its frequency response to changing market conditions with O(order) per-bar complexity. @@ -192,4 +190,4 @@ Lms.Batch(prices, output, order: 16, mu: 0.5); var source = new TSeries(); var lmsChained = new Lms(source, order: 16, mu: 0.5); source.Add(new TValue(DateTime.UtcNow, price)); // lmsChained.Last auto-updates -``` +``` \ No newline at end of file diff --git a/lib/filters/loess/Loess.md b/lib/filters/loess/Loess.md index fca81d63..4038e006 100644 --- a/lib/filters/loess/Loess.md +++ b/lib/filters/loess/Loess.md @@ -14,9 +14,7 @@ | **Signature** | [loess_signature](loess_signature.md) | - Locally Estimated Scatterplot Smoothing (LOESS) applies a weighted linear regression over a localized window of nearest neighbors. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `Period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SGF](../sgf/Sgf.md), [NW](../nw/Nw.md) | **Complementary:** Lin reg for trend | **Trading note:** Locally Estimated Scatterplot Smoothing; non-parametric regression. Adapts to local data structure. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Locally Estimated Scatterplot Smoothing (LOESS) applies a weighted linear regression over a localized window of nearest neighbors. Unlike simple averaging or global linear regression, LOESS estimates the deterministic trend point-by-point, giving maximum influence to recent data and decaying elegantly at the edges. @@ -113,4 +111,4 @@ Validating against statistical properties and theoretical linear trend reconstru ### Common Pitfalls * **Window Size:** Very small periods (<5) approximate the input noisily. Large periods introduce lag. -* **NaN Propagation:** Standard implementations propagate `NaN`. This implementation stops them dead. +* **NaN Propagation:** Standard implementations propagate `NaN`. This implementation stops them dead. \ No newline at end of file diff --git a/lib/filters/modf/Modf.md b/lib/filters/modf/Modf.md index 520f624e..9efffc15 100644 --- a/lib/filters/modf/Modf.md +++ b/lib/filters/modf/Modf.md @@ -14,9 +14,7 @@ | **Signature** | [modf_signature](modf_signature.md) | - MODF is a dual-path adaptive filter that maintains separate upper and lower EMA bands with conditional state selection. -- Parameterized by `period`, `beta` (default 0.8), `feedback` (default false), `fbweight` (default 0.5). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HP](../hp/Hp.md), [BaxterKing](../baxterking/BaxterKing.md) | **Complementary:** Trend indicators | **Trading note:** Mode decomposition filter; separates signal into trend, cyclical, and noise components. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. MODF is a dual-path adaptive filter that maintains separate upper and lower EMA bands with conditional state selection. The upper band snaps up to price when price exceeds it (tracking rallies), while the lower band snaps down when price drops below it (tracking selloffs). An oscillator state variable determines which band is active, and a beta parameter controls the blend between filter mode (smooth tracking) and trailing-stop mode (step-like following). An optional feedback loop blends the filter's output back into its input for additional smoothing. Developed by alexgrover (CPO at LuxAlgo). @@ -158,4 +156,4 @@ Fully recursive — no SIMD path available. Batch throughput: ~26-30 cy/bar scal ## Resources - alexgrover (LuxAlgo). "Modular Filter" indicator. Published on TradingView. -- Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley. Chapter 6: Adaptive Filters (general framework). +- Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley. Chapter 6: Adaptive Filters (general framework). \ No newline at end of file diff --git a/lib/filters/notch/Notch.md b/lib/filters/notch/Notch.md index 01f32c96..227756b4 100644 --- a/lib/filters/notch/Notch.md +++ b/lib/filters/notch/Notch.md @@ -14,9 +14,7 @@ | **Signature** | [notch_signature](notch_signature.md) | - The Notch Filter is a band-stop filter with a narrow bandwidth. -- Parameterized by `period`, `q` (default 1.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BPF](../bpf/Bpf.md), [Roofing](../roofing/Roofing.md) | **Complementary:** Cycle period detection | **Trading note:** Notch filter; removes a specific frequency. Useful for eliminating known periodic noise. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. > Sometimes the best way to improved signal clarity isn't amplification, but rather the surgical removal of a specific annoyance. @@ -108,4 +106,4 @@ var notch = new Notch(period: 10, q: 1.0); TValue result = notch.Update(new TValue(DateTime.UtcNow, price)); // Static calculation for a full series -TSeries filtered = Notch.Calculate(series, period: 10, q: 1.0); +TSeries filtered = Notch.Calculate(series, period: 10, q: 1.0); \ No newline at end of file diff --git a/lib/filters/nw/Nw.md b/lib/filters/nw/Nw.md index 1f14f6b3..98dccc9b 100644 --- a/lib/filters/nw/Nw.md +++ b/lib/filters/nw/Nw.md @@ -14,9 +14,7 @@ | **Signature** | [nw_signature](nw_signature.md) | - NW computes the Nadaraya-Watson kernel regression estimator with a Gaussian kernel, producing a nonparametric smooth of the price series. -- Parameterized by `period` (default 64), `bandwidth` (default 8.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Loess](../loess/Loess.md), [SGF](../sgf/Sgf.md) | **Complementary:** Bandwidth selection via cross-validation | **Trading note:** Nadaraya-Watson kernel regression; non-parametric smoother with Gaussian kernel. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. NW computes the Nadaraya-Watson kernel regression estimator with a Gaussian kernel, producing a nonparametric smooth of the price series. For each bar, every observation in the lookback window is weighted by a Gaussian function of its temporal distance, with the bandwidth parameter $h$ controlling the effective smoothing radius. Small $h$ tracks price tightly (low bias, high variance); large $h$ smooths heavily (high bias, low variance). This implementation is non-repainting (backward-looking only). @@ -127,4 +125,4 @@ AVX2 dot product on contiguous double array: ~200-250 cy for N=200 vs ~1200 scal - Nadaraya, E.A. (1964). "On Estimating Regression." *Theory of Probability and Its Applications*, 9(1), 141-142. - Watson, G.S. (1964). "Smooth Regression Analysis." *Sankhyā: The Indian Journal of Statistics*, Series A, 26(4), 359-372. -- Wand, M.P. & Jones, M.C. (1995). *Kernel Smoothing*. Chapman & Hall/CRC. Chapter 2: The Density Estimator. +- Wand, M.P. & Jones, M.C. (1995). *Kernel Smoothing*. Chapman & Hall/CRC. Chapter 2: The Density Estimator. \ No newline at end of file diff --git a/lib/filters/oneeuro/OneEuro.md b/lib/filters/oneeuro/OneEuro.md index a6a262cf..b38b6de7 100644 --- a/lib/filters/oneeuro/OneEuro.md +++ b/lib/filters/oneeuro/OneEuro.md @@ -15,9 +15,7 @@ - The **One Euro Filter** (1€ Filter) is a speed-adaptive first-order low-pass filter designed to balance jitter removal against responsiveness. -- Parameterized by `mincutoff` (default 1.0), `beta` (default 0.007), `dcutoff` (default 1.0). -- Output range: Tracks input. -- Requires `1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Kalman](../kalman/Kalman.md), [LMS](../lms/Lms.md) | **Complementary:** ATR for cutoff tuning | **Trading note:** One Euro filter; adaptive low-pass that reduces jitter while preserving quick movements. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The **One Euro Filter** (1€ Filter) is a speed-adaptive first-order low-pass filter designed to balance jitter removal against responsiveness. It uses an adaptive cutoff frequency: at low signal speed, a low cutoff stabilizes the signal by reducing jitter; as speed increases, the cutoff rises to reduce lag. @@ -118,4 +116,4 @@ var smooth = new OneEuro(source, minCutoff: 1.0, beta: 0.007); ## Reference > Casiez, G., Roussel, N., & Vogel, D. (2012). **1€ Filter: A Simple Speed-Based Low-Pass Filter for Noisy Input in Interactive Systems.** *CHI '12*, pp. 2527–2530. -> DOI: [10.1145/2207676.2208639](https://doi.org/10.1145/2207676.2208639) +> DOI: [10.1145/2207676.2208639](https://doi.org/10.1145/2207676.2208639) \ No newline at end of file diff --git a/lib/filters/rls/Rls.md b/lib/filters/rls/Rls.md index 5b236d9c..cb6530ac 100644 --- a/lib/filters/rls/Rls.md +++ b/lib/filters/rls/Rls.md @@ -15,9 +15,7 @@ - The Recursive Least Squares (RLS) adaptive filter is the Rolls-Royce of adaptive FIR filters. -- Parameterized by `order` (default 16), `lambda` (default 0.99). -- Output range: Tracks input. -- Requires `order + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [LMS](../lms/Lms.md), [Kalman](../kalman/Kalman.md) | **Complementary:** Error metrics | **Trading note:** Recursive Least Squares; faster convergence than LMS but higher computational cost. Forgetting factor adapts to regime changes. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -169,4 +167,4 @@ RLS is a custom adaptive filter with no direct equivalent in standard TA librari - Haykin, S. (2002). *Adaptive Filter Theory*. 4th ed. Prentice Hall. Chapters 9-10. - Ljung, L. & Soderstrom, T. (1983). *Theory and Practice of Recursive Identification*. MIT Press. - Sayed, A.H. (2008). *Adaptive Filters*. Wiley-IEEE Press. -- Kalman, R.E. (1960). "A New Approach to Linear Filtering and Prediction Problems." *Journal of Basic Engineering*, 82(1), 35-45. +- Kalman, R.E. (1960). "A New Approach to Linear Filtering and Prediction Problems." *Journal of Basic Engineering*, 82(1), 35-45. \ No newline at end of file diff --git a/lib/filters/rmed/Rmed.md b/lib/filters/rmed/Rmed.md index c1a1d10f..d18c22d2 100644 --- a/lib/filters/rmed/Rmed.md +++ b/lib/filters/rmed/Rmed.md @@ -14,9 +14,7 @@ | **Signature** | [rmed_signature](rmed_signature.md) | - RMED applies exponential smoothing to a 5-bar running median, creating a nonlinear IIR filter that rejects impulsive spike noise while providing sm... -- Parameterized by `period` (default 12). -- Output range: Tracks input. -- Requires **5 bars** of warmup (MedianWindow) before first valid output (IsHot = true). +- **Similar:** [Bilateral](../bilateral/Bilateral.md), [Loess](../loess/Loess.md) | **Complementary:** ATR for volatility | **Trading note:** Running median filter; non-linear, completely removes impulse noise. Preserves edges. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. RMED applies exponential smoothing to a 5-bar running median, creating a nonlinear IIR filter that rejects impulsive spike noise while providing smooth recursive tracking. The median component eliminates outliers that would corrupt any linear filter, while the EMA provides the recursive continuity that a pure median lacks. The EMA constant $\alpha$ is derived from Ehlers' cycle-period formula, connecting the smoothing rate to the dominant cycle length of the data. @@ -133,4 +131,4 @@ Nonlinear median + recursive EMA blocks all meaningful SIMD. Batch throughput: ~ - Ehlers, J.F. (2018). "Recursive Median Filters." *Technical Analysis of Stocks & Commodities*, March 2018. - Tukey, J.W. (1977). *Exploratory Data Analysis*. Addison-Wesley. Chapter 7: Resistant Smoothing. -- Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley. Chapter 3: Smoothing Constants from Cycle Period. +- Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley. Chapter 3: Smoothing Constants from Cycle Period. \ No newline at end of file diff --git a/lib/filters/roofing/Roofing.md b/lib/filters/roofing/Roofing.md index a3caa664..f6a99590 100644 --- a/lib/filters/roofing/Roofing.md +++ b/lib/filters/roofing/Roofing.md @@ -13,9 +13,7 @@ | **PineScript** | [roofing.pine](roofing.pine) | - The **Roofing Filter** is John Ehlers' bandpass architecture designed specifically for oscillator construction. -- Parameterized by `hplength` (default 48), `sslength` (default 10). -- Output range: Oscillates around zero (bandpass behavior). -- Requires `hpLength` bars of warmup before first valid output (IsHot = true). Default: **48 bars**. +- **Similar:** [HPF](../hpf/Hpf.md), [SSF2](../ssf2/Ssf2.md) | **Complementary:** Cycle indicators | **Trading note:** Ehlers' roofing filter; combines high-pass + super smoother. Isolates tradeable cycle band. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The **Roofing Filter** is John Ehlers' bandpass architecture designed specifically for oscillator construction. It cascades a 2nd-order Butterworth Highpass (to strip trend) with a Super Smoother Lowpass (to strip noise), passing only the cyclic energy within a user-defined frequency band. The output oscillates around zero, with zero crossings serving as directional signals. @@ -163,4 +161,4 @@ Roofing.Batch(prices, output, hpLength: 48, ssLength: 10); var source = new TSeries(); var roofingChained = new Roofing(source, hpLength: 48, ssLength: 10); source.Add(new TValue(DateTime.UtcNow, price)); // roofingChained.Last auto-updates -``` +``` \ No newline at end of file diff --git a/lib/filters/sgf/Sgf.md b/lib/filters/sgf/Sgf.md index 5119dd98..9c763e26 100644 --- a/lib/filters/sgf/Sgf.md +++ b/lib/filters/sgf/Sgf.md @@ -14,9 +14,7 @@ | **Signature** | [sgf_signature](sgf_signature.md) | - SGF (Savitzky-Golay Filter) is a digital signal processing technique that smoothes data by fitting successive sub-sets of adjacent data points with... -- Parameterized by `period`, `polyorder` (default 2). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Loess](../loess/Loess.md), [NW](../nw/Nw.md) | **Complementary:** Polynomial order selection | **Trading note:** Savitzky-Golay filter; polynomial smoothing preserving higher moments. Good for derivative estimation. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. SGF (Savitzky-Golay Filter) is a digital signal processing technique that smoothes data by fitting successive sub-sets of adjacent data points with a low-degree polynomial by the method of linear least squares. Unlike standard moving averages that simply average the points, SGF preserves higher moments of the data distribution, such as the area, center of gravity, and line width. This makes it exceptionally good at preserving features of the distribution such as relative maxima and minima and width, which are usually flattened by other smoothing techniques. @@ -124,4 +122,4 @@ var result = sgf.Update(new TValue(DateTime.UtcNow, 100.0)); Sgf.Calculate(inputSpan, outputSpan, period: 21, polyOrder: 4); // Chainable using TValuePublisher -var sgf = new Sgf(source, period: 14); +var sgf = new Sgf(source, period: 14); \ No newline at end of file diff --git a/lib/filters/spbf/Spbf.md b/lib/filters/spbf/Spbf.md index 30f30932..f826e82b 100644 --- a/lib/filters/spbf/Spbf.md +++ b/lib/filters/spbf/Spbf.md @@ -13,9 +13,7 @@ | **PineScript** | [spbf.pine](spbf.pine) | - The **Super Passband Filter** is John Ehlers' wide-band bandpass constructed by differencing two z-transformed EMAs with Ehlers-style smoothing ($\... -- Parameterized by `shortperiod` (default 40), `longperiod` (default 60), `rmsperiod` (default 50). -- Output range: Oscillates around zero. -- Requires `max(longPeriod, rmsPeriod)` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Bilateral](../bilateral/Bilateral.md), [RMed](../rmed/Rmed.md) | **Complementary:** ATR for volatility context | **Trading note:** Spectral bilateral filter; edge-preserving smoother in frequency domain. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The **Super Passband Filter** is John Ehlers' wide-band bandpass constructed by differencing two z-transformed EMAs with Ehlers-style smoothing ($\alpha = 5/N$). It rejects both DC trend and high-frequency noise, passing only the cyclic energy between two EMA-defined cutoff frequencies. The output oscillates around zero, with an RMS trigger envelope providing signal/noise discrimination. @@ -183,4 +181,4 @@ Spbf.BatchWithRms(prices, pb, rms, shortPeriod: 40, longPeriod: 60, rmsPeriod: 5 var source = new TSeries(); var spbfChained = new Spbf(source, shortPeriod: 40, longPeriod: 60, rmsPeriod: 50); source.Add(new TValue(DateTime.UtcNow, price)); // spbfChained.Last auto-updates -``` +``` \ No newline at end of file diff --git a/lib/filters/ssf2/Ssf2.md b/lib/filters/ssf2/Ssf2.md index 8e1c6d5e..f02c6070 100644 --- a/lib/filters/ssf2/Ssf2.md +++ b/lib/filters/ssf2/Ssf2.md @@ -14,9 +14,7 @@ | **Signature** | [ssf2_signature](ssf2_signature.md) | - The 2-Pole Super Smooth Filter (SSF2) is a 2-pole Butterworth filter designed by John Ehlers. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SSF3](../ssf3/Ssf3.md), [Butter2](../butter2/Butter2.md) | **Complementary:** HPF for cycle extraction | **Trading note:** Ehlers' 2-pole Super Smoother; superior to EMA with less lag for same smoothness. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The 2-Pole Super Smooth Filter (SSF2) is a 2-pole Butterworth filter designed by John Ehlers. It offers superior noise reduction compared to standard moving averages while maintaining minimal lag. By using complex conjugate poles, it achieves a "maximally flat" response in the passband, meaning it preserves the trend signal with high fidelity while aggressively suppressing high-frequency noise. @@ -103,4 +101,4 @@ Batch throughput: ~16 cy/bar. ### Common Pitfalls 1. **Initialization**: The filter requires a few bars to stabilize. Per Ehlers' design, the output is set to the input price for the first 4 bars. -2. **Period Selection**: Unlike an SMA, the "Period" $N$ in SSF2 refers to the cutoff wavelength. A period of 10 means it filters out cycles shorter than 10 bars. It is roughly comparable to an EMA of the same length but smoother. +2. **Period Selection**: Unlike an SMA, the "Period" $N$ in SSF2 refers to the cutoff wavelength. A period of 10 means it filters out cycles shorter than 10 bars. It is roughly comparable to an EMA of the same length but smoother. \ No newline at end of file diff --git a/lib/filters/ssf3/Ssf3.md b/lib/filters/ssf3/Ssf3.md index 34479bf9..22a80095 100644 --- a/lib/filters/ssf3/Ssf3.md +++ b/lib/filters/ssf3/Ssf3.md @@ -14,9 +14,7 @@ | **Signature** | [ssf3_signature](ssf3_signature.md) | - The 3-Pole Super Smoother Filter (SSF3) extends Ehlers' Super Smoother concept to third order, providing -60 dB/decade rolloff compared to -40 dB/d... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `6 * period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SSF2](../ssf2/Ssf2.md), [Butter3](../butter3/Butter3.md) | **Complementary:** Cycle analysis | **Trading note:** Ehlers' 3-pole Super Smoother; even smoother than 2-pole but more lag. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The 3-Pole Super Smoother Filter (SSF3) extends Ehlers' Super Smoother concept to third order, providing -60 dB/decade rolloff compared to -40 dB/decade for the 2-pole variant (SSF2). It shares identical pole placement with BUTTER3 but uses a single-sample feedforward (`coef1 * x`) instead of the binomial-weighted 4-sample average (`coef1 * (x + 3x1 + 3x2 + x3)`). This makes SSF3 more responsive to recent price changes while still delivering aggressive high-frequency noise suppression. @@ -140,4 +138,4 @@ Ssf3.Batch(sourceSpan, destSpan, period: 20, initialLast: double.NaN); ## References * Ehlers, John F. "Cybernetic Analysis for Stocks and Futures." Wiley, 2004. -* Ehlers, John F. "Rocket Science for Traders." Wiley, 2001. +* Ehlers, John F. "Rocket Science for Traders." Wiley, 2001. \ No newline at end of file diff --git a/lib/filters/usf/Usf.md b/lib/filters/usf/Usf.md index 869340a7..f21a0c74 100644 --- a/lib/filters/usf/Usf.md +++ b/lib/filters/usf/Usf.md @@ -14,9 +14,7 @@ | **Signature** | [usf_signature](usf_signature.md) | - The Ultimate Smoother Filter (USF) is a zero-lag smoothing filter introduced by John Ehlers in the April 2024 issue of *Technical Analysis of Stock... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SSF2](../ssf2/Ssf2.md), [Kalman](../kalman/Kalman.md) | **Complementary:** ATR for volatility | **Trading note:** Universal Smoothing Filter; combines multiple filter approaches adaptively. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Ultimate Smoother Filter (USF) is a zero-lag smoothing filter introduced by John Ehlers in the April 2024 issue of *Technical Analysis of Stocks & Commodities*. It builds upon the Super Smoother Filter (SSF) by using a high-pass filter to remove high-frequency noise, leaving a smooth low-frequency component with minimal lag. @@ -119,4 +117,4 @@ Console.WriteLine($"Current USF: {usf.Last.Value}"); // Use in a TSeries chain var source = new TSeries(); -var usfSeries = new Usf(source, 20); +var usfSeries = new Usf(source, 20); \ No newline at end of file diff --git a/lib/filters/voss/Voss.md b/lib/filters/voss/Voss.md index 0d32ccef..bdc5e55f 100644 --- a/lib/filters/voss/Voss.md +++ b/lib/filters/voss/Voss.md @@ -13,9 +13,7 @@ | **PineScript** | [voss.pine](voss.pine) | - The Voss Predictive Filter is a two-stage signal processing pipeline that extracts a dominant cycle from noisy price data and then predicts its fut... -- Parameterized by `period` (default 20), `predict` (default 3), `bandwidth` (default 0.25). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BPF](../bpf/Bpf.md), [Roofing](../roofing/Roofing.md) | **Complementary:** Cycle period indicators | **Trading note:** Voss predictive filter; attempts to predict the next cycle value. Zero-lag by design. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -182,4 +180,4 @@ source.Add(new TValue(DateTime.UtcNow, 100.0)); 1. Ehlers, J. F. "A Peek Into the Future." *Technical Analysis of Stocks and Commodities*, August 2019. 2. Voss, H. U. "Anticipating chaotic synchronization." *Physical Review E*, 61(5), 2000. -3. Ehlers, J. F. *Cycle Analytics for Traders*. Wiley, 2013. +3. Ehlers, J. F. *Cycle Analytics for Traders*. Wiley, 2013. \ No newline at end of file diff --git a/lib/filters/wavelet/Wavelet.md b/lib/filters/wavelet/Wavelet.md index e6286825..0c89ebcf 100644 --- a/lib/filters/wavelet/Wavelet.md +++ b/lib/filters/wavelet/Wavelet.md @@ -15,9 +15,7 @@ - The Wavelet Denoising Filter applies an *à trous* (with holes) Haar wavelet decomposition with soft thresholding to remove high-frequency noise fro... -- Parameterized by `levels` (default 4), `threshmult` (default 1.0). -- Output range: Tracks input. -- Requires `2^levels` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SGF](../sgf/Sgf.md), [Modf](../modf/Modf.md) | **Complementary:** Multi-timeframe analysis | **Trading note:** Wavelet denoising; multi-resolution analysis separates signal at different time scales. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -180,4 +178,4 @@ Wavelet denoising has no direct equivalent in standard TA libraries. Validation - Holschneider, M., Kronland-Martinet, R., Morlet, J. & Tchamitchian, P. (1989). "A Real-Time Algorithm for Signal Analysis with the Help of the Wavelet Transform." In *Wavelets: Time-Frequency Methods and Phase Space*, Springer. - Mallat, S. (2009). *A Wavelet Tour of Signal Processing: The Sparse Way*. 3rd ed. Academic Press. - Nason, G.P. (2008). *Wavelet Methods in Statistics with R*. Springer. -- Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley. (Context for financial signal processing filters.) +- Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley. (Context for financial signal processing filters.) \ No newline at end of file diff --git a/lib/filters/wiener/Wiener.md b/lib/filters/wiener/Wiener.md index 2cf57532..743b1718 100644 --- a/lib/filters/wiener/Wiener.md +++ b/lib/filters/wiener/Wiener.md @@ -14,9 +14,7 @@ | **Signature** | [wiener_signature](wiener_signature.md) | - The Wiener Filter is an optimal linear filter that attempts to minimize the mean square error between the estimated random process and the desired ... -- Parameterized by `period`, `smoothperiod` (default 10). -- Output range: Tracks input. -- Requires `Math.Max(period, smoothPeriod)` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Kalman](../kalman/Kalman.md), [RLS](../rls/Rls.md) | **Complementary:** Noise estimation | **Trading note:** Wiener filter; optimal linear filter minimizing MSE. Assumes stationary signals. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Wiener Filter is an optimal linear filter that attempts to minimize the mean square error between the estimated random process and the desired process. In the context of technical analysis, it acts as an adaptive smoothing filter that adjusts its responsiveness based on the local statistical properties of the data (signal-to-noise ratio). When the signal variance is high relative to noise variance, the filter follows the input closely. When noise dominates, it smooths aggressively. @@ -120,4 +118,4 @@ var result = wiener.Update(new TValue(DateTime.UtcNow, 100.0)); // 3. Access results Console.WriteLine($"Filter Value: {result.Value}"); -Console.WriteLine($"Is Hot: {wiener.IsHot}"); +Console.WriteLine($"Is Hot: {wiener.IsHot}"); \ No newline at end of file diff --git a/lib/forecasts/afirma/Afirma.md b/lib/forecasts/afirma/Afirma.md index 8ff49d16..9bc98e04 100644 --- a/lib/forecasts/afirma/Afirma.md +++ b/lib/forecasts/afirma/Afirma.md @@ -13,9 +13,7 @@ | **PineScript** | [afirma.pine](afirma.pine) | - AFIRMA is a Windowed Weighted Moving Average that replaces standard linear weighting with weights derived from signal processing window functions (... -- Parameterized by `period`, `window` (default windowtype.blackmanharris), `leastsquares` (default false). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [TSF](../../trends_FIR/tsf/Tsf.md), [LinReg](../../statistics/linreg/LinReg.md) | **Complementary:** Error metrics for accuracy | **Trading note:** Adaptive FIR Moving Average for forecasting; projects price using optimized FIR coefficients. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. AFIRMA is a Windowed Weighted Moving Average that replaces standard linear weighting with weights derived from signal processing window functions (Hanning, Hamming, Blackman, Blackman-Harris). This approach achieves specific frequency response characteristics tailored to noise reduction. @@ -202,4 +200,4 @@ For identical period, different windows trade smoothness for responsiveness: ## References - Harris, F. J. (1978). "On the use of windows for harmonic analysis with the discrete Fourier transform." *Proceedings of the IEEE*, 66(1), 51-83. -- Nuttall, A. H. (1981). "Some windows with very good sidelobe behavior." *IEEE Transactions on Acoustics, Speech, and Signal Processing*, 29(1), 84-91. +- Nuttall, A. H. (1981). "Some windows with very good sidelobe behavior." *IEEE Transactions on Acoustics, Speech, and Signal Processing*, 29(1), 84-91. \ No newline at end of file diff --git a/lib/momentum/asi/Asi.md b/lib/momentum/asi/Asi.md index 847698d3..f0155f21 100644 --- a/lib/momentum/asi/Asi.md +++ b/lib/momentum/asi/Asi.md @@ -13,9 +13,7 @@ | **PineScript** | [asi.pine](asi.pine) | - The Accumulation Swing Index is Wilder's method for separating genuine breakouts from whipsaw noise. -- Parameterized by `limitmove` (default 3.0). -- Output range: Varies (see docs). -- Requires `> 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MOM](../mom/Mom.md), [ROC](../roc/Roc.md) | **Complementary:** Volume for confirmation | **Trading note:** Accumulation Swing Index; Wilder's cumulative swing index. Confirms breakouts from chart patterns. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Accumulation Swing Index is Wilder's method for separating genuine breakouts from whipsaw noise. Each bar computes a Swing Index value by comparing current OHLC prices to the previous bar, scaled by a user-supplied limit move parameter T. The cumulative sum of these SI values — the ASI — forms a "phantom" price line whose peaks and troughs can be compared directly to the price chart. A trendline break on ASI that accompanies a trendline break on price is confirmed; a price break without ASI confirmation is a probable false move. Introduced in Wilder's 1978 book, it predates most modern oscillators by a decade. @@ -189,4 +187,4 @@ Bar2: O=10, H=12, L=9, C=11 - Wilder, J.W. (1978). *New Concepts in Technical Trading Systems*. Trend Research, Greensboro NC. - Murphy, J.J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance, pp. 233–238. -- Kaufman, P.J. (2013). *Trading Systems and Methods*, 5th ed. Wiley, pp. 411–413. +- Kaufman, P.J. (2013). *Trading Systems and Methods*, 5th ed. Wiley, pp. 411–413. \ No newline at end of file diff --git a/lib/momentum/bias/Bias.md b/lib/momentum/bias/Bias.md index c039afb7..1e976a11 100644 --- a/lib/momentum/bias/Bias.md +++ b/lib/momentum/bias/Bias.md @@ -13,9 +13,7 @@ | **PineScript** | [bias.pine](bias.pine) | - The Bias indicator measures the percentage difference between the current price and its Simple Moving Average (SMA). -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ROC](../roc/Roc.md), [CFO](../../oscillators/cfo/Cfo.md) | **Complementary:** Moving average for signal | **Trading note:** Price bias from moving average; (Price−MA)/MA × 100. Mean-reversion signal at extremes. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Bias indicator measures the percentage difference between the current price and its Simple Moving Average (SMA). A positive bias indicates price is above the average (potentially overbought), while negative bias suggests price is below average (potentially oversold). This is one of the simplest yet most effective tools for identifying mean-reversion opportunities. @@ -218,4 +216,4 @@ source.Add(new TValue(DateTime.UtcNow, 100.0)); ## References * TradingView. "Bias Indicator (PineScript)." *TradingView Documentation*. -* Kaufman, P.J. (2013). "Trading Systems and Methods." *Wiley Trading*, 5th Edition. +* Kaufman, P.J. (2013). "Trading Systems and Methods." *Wiley Trading*, 5th Edition. \ No newline at end of file diff --git a/lib/momentum/bop/Bop.md b/lib/momentum/bop/Bop.md index bc8a5c3c..220f14fc 100644 --- a/lib/momentum/bop/Bop.md +++ b/lib/momentum/bop/Bop.md @@ -14,8 +14,6 @@ - The Balance of Power measures buying versus selling pressure by comparing the body (Close minus Open) to the range (High minus Low). - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `> 0` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Balance of Power measures buying versus selling pressure by comparing the body (Close minus Open) to the range (High minus Low). Created by Igor Livshin in 2001, this ratio oscillates between -1 and +1, providing instantaneous momentum readings with zero lag. A stateless indicator: each bar evaluated independently, no memory of previous values required. @@ -290,4 +288,4 @@ foreach (var bar in liveStream) - Livshin, I. (2001). "Balance of Power." *Technical Analysis of Stocks & Commodities*, August 2001. - Investopedia. "Balance of Power (BOP) Indicator." https://www.investopedia.com/terms/b/bop.asp -- Achelis, S. (2000). *Technical Analysis from A to Z*. McGraw-Hill. (General indicator theory) +- Achelis, S. (2000). *Technical Analysis from A to Z*. McGraw-Hill. (General indicator theory) \ No newline at end of file diff --git a/lib/momentum/cci/Cci.md b/lib/momentum/cci/Cci.md index e61839c8..8c9e62cb 100644 --- a/lib/momentum/cci/Cci.md +++ b/lib/momentum/cci/Cci.md @@ -13,9 +13,7 @@ | **PineScript** | [cci.pine](cci.pine) | - The Commodity Channel Index (CCI) is a versatile momentum-based oscillator developed by Donald Lambert in 1980. -- Parameterized by `period` (default 20). -- Output range: Varies (see docs). -- Requires `period` bars (20 default) of warmup before first valid output (IsHot = true). +- **Similar:** [RSI](../rsi/Rsi.md), [Stoch](../../oscillators/stoch/Stoch.md) | **Complementary:** ADX for trend filter | **Trading note:** Commodity Channel Index; measures deviation from statistical mean. ±100 = overbought/oversold. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Overview @@ -140,4 +138,4 @@ O(N) streaming cost per bar. For the default N = 20: ~107 cycles. No incremental | Final CCI scale | Yes | scalar multiply after reduction | | State dependency across bars (SMA) | Partial | prefix sum removes dependency; MAD is fully independent per bar | -AVX2 processes 4 doubles per instruction. For the inner MAD loop of N=20, that is 5 SIMD passes vs 20 scalar iterations — roughly 3× throughput gain. The outer bar loop remains SIMD-friendly since each bar's TP is independent once the window positions are known. +AVX2 processes 4 doubles per instruction. For the inner MAD loop of N=20, that is 5 SIMD passes vs 20 scalar iterations — roughly 3× throughput gain. The outer bar loop remains SIMD-friendly since each bar's TP is independent once the window positions are known. \ No newline at end of file diff --git a/lib/momentum/cfb/Cfb.md b/lib/momentum/cfb/Cfb.md index c71519f7..2b931c88 100644 --- a/lib/momentum/cfb/Cfb.md +++ b/lib/momentum/cfb/Cfb.md @@ -13,9 +13,7 @@ | **PineScript** | [cfb.pine](cfb.pine) | - The Composite Fractal Behavior index measures trend duration by analyzing fractal efficiency across 96 simultaneous lookback periods (2 to 192 bars... -- Parameterized by int[]? lengths = null. -- Output range: Varies (see docs). -- Requires `maxLen` bars (192 default) of warmup before first valid output (IsHot = true). +- **Similar:** [RSI](../rsi/Rsi.md), [CMO](../cmo/Cmo.md) | **Complementary:** Volume for confirmation | **Trading note:** Composite Force Index; combines price change magnitude and direction. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Composite Fractal Behavior index measures trend duration by analyzing fractal efficiency across 96 simultaneous lookback periods (2 to 192 bars by default). Rather than asking "how strong is the trend," CFB asks "how long has the market been moving efficiently." The answer: a single integer representing the dominant trending timeframe. Use CFB to dynamically tune other indicators: instead of RSI(14), use RSI(CFB). @@ -307,4 +305,4 @@ var cfb = new Cfb(customLengths); - Jurik Research. "Composite Fractal Behavior." http://jurikres.com/ - Mandelbrot, B. (1997). *Fractals and Scaling in Finance*. Springer. (Theoretical foundation) -- Peters, E. (1994). *Fractal Market Analysis*. Wiley. (Fractal efficiency concepts) +- Peters, E. (1994). *Fractal Market Analysis*. Wiley. (Fractal efficiency concepts) \ No newline at end of file diff --git a/lib/momentum/cmo/Cmo.md b/lib/momentum/cmo/Cmo.md index 7fdcfb6e..bfa75d11 100644 --- a/lib/momentum/cmo/Cmo.md +++ b/lib/momentum/cmo/Cmo.md @@ -13,9 +13,7 @@ | **PineScript** | [cmo.pine](cmo.pine) | - The Chande Momentum Oscillator (CMO) is a momentum indicator developed by Tushar Chande. -- Parameterized by `period` (default 14). -- Output range: $-100$ to $+100$. -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [RSI](../rsi/Rsi.md), [Stoch](../../oscillators/stoch/Stoch.md) | **Complementary:** Moving average crossover | **Trading note:** Chande Momentum Oscillator; like RSI but uses up−down/up+down formula. Range ±100. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Chande Momentum Oscillator (CMO) is a momentum indicator developed by Tushar Chande. Unlike RSI which uses smoothed averages of gains and losses, CMO uses raw sums of up and down movements, making it more responsive to price changes. The indicator oscillates between -100 and +100. @@ -123,4 +121,4 @@ O(1) per bar. At N = 14 (default), WarmupPeriod = 15 bars (one extra for the ini | Sliding window sum (subtract old, add new) | Yes | vectorizable once prefix sums are built | | Final CMO formula (per bar) | Yes | `VSUBPD`, `VADDPD`, `VDIVPD` | -The classification branch (up vs. down) is the primary SIMD barrier. A branchless formulation using `Vector.ConditionalSelect` replaces the branch with a mask, enabling full vectorization. For N = 14, AVX2 processes 8 bars simultaneously after the prefix-sum setup. +The classification branch (up vs. down) is the primary SIMD barrier. A branchless formulation using `Vector.ConditionalSelect` replaces the branch with a mask, enabling full vectorization. For N = 14, AVX2 processes 8 bars simultaneously after the prefix-sum setup. \ No newline at end of file diff --git a/lib/momentum/macd/Macd.md b/lib/momentum/macd/Macd.md index 4cf1f068..05d86400 100644 --- a/lib/momentum/macd/Macd.md +++ b/lib/momentum/macd/Macd.md @@ -13,9 +13,7 @@ | **PineScript** | [macd.pine](macd.pine) | - The Moving Average Convergence Divergence measures momentum through the relationship between two exponential moving averages. -- Parameterized by `fastperiod` (default 12), `slowperiod` (default 26), `signalperiod` (default 9). -- Output range: Varies (see docs). -- Requires `Max(fast, slow) + signal - 2` bars (33 default) of warmup before first valid output (IsHot = true). +- **Similar:** [PPO](../ppo/Ppo.md), [APO](../../oscillators/apo/Apo.md) | **Complementary:** RSI for divergence confirmation | **Trading note:** Moving Average Convergence Divergence; signal line crossovers and histogram for momentum. Most widely used momentum indicator. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Moving Average Convergence Divergence measures momentum through the relationship between two exponential moving averages. Created by Gerald Appel in 1979, the indicator transforms price into a bounded oscillator that reveals trend strength, direction, and potential reversals. Standard parameters (12, 26, 9) detect monthly and biweekly cycles: the 26-period represents roughly one trading month, the 12-period half that duration. @@ -317,4 +315,4 @@ source.Add(new TValue(DateTime.UtcNow, 100.0)); - Aspray, T. (1986). "MACD Histogram." *Technical Analysis of Stocks & Commodities*. - Murphy, J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. - Pring, M. (2002). *Technical Analysis Explained*. McGraw-Hill. -- Elder, A. (1993). *Trading for a Living*. Wiley. (Discussion of MACD histogram interpretation) +- Elder, A. (1993). *Trading for a Living*. Wiley. (Discussion of MACD histogram interpretation) \ No newline at end of file diff --git a/lib/momentum/mom/Mom.md b/lib/momentum/mom/Mom.md index 18610130..12655eb7 100644 --- a/lib/momentum/mom/Mom.md +++ b/lib/momentum/mom/Mom.md @@ -13,9 +13,7 @@ | **PineScript** | [mom.pine](mom.pine) | - MOM (Momentum) calculates the absolute price difference between the current value and the value N periods ago. -- Parameterized by `period` (default 10). -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ROC](../roc/Roc.md), [Vel](../vel/Vel.md) | **Complementary:** Moving average for smoothing | **Trading note:** Raw momentum: Price(t) − Price(t−n). Simplest momentum measure. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. MOM (Momentum) calculates the absolute price difference between the current value and the value N periods ago. It is the purest expression of directional price movement, returning a signed value in the same units as the input. Positive MOM indicates rising prices; negative indicates falling. This is functionally identical to ROC but with a configurable lookback period (default 10 vs ROC's convention), and maps directly to TA-Lib's `MOM` function. @@ -156,4 +154,4 @@ $$ - Murphy, J. J. (1999). "Technical Analysis of the Financial Markets." New York Institute of Finance. - Appel, G. (2005). "Technical Analysis: Power Tools for Active Investors." FT Press. - TA-Lib documentation: MOM function reference -- TradingView PineScript Reference: ta.mom +- TradingView PineScript Reference: ta.mom \ No newline at end of file diff --git a/lib/momentum/pmo/Pmo.md b/lib/momentum/pmo/Pmo.md index ff5225dc..27a13ea6 100644 --- a/lib/momentum/pmo/Pmo.md +++ b/lib/momentum/pmo/Pmo.md @@ -13,9 +13,7 @@ | **PineScript** | [pmo.pine](pmo.pine) | - PMO (Price Momentum Oscillator), developed by Carl Swenlin at DecisionPoint, is a double-smoothed 1-bar rate of change. -- Parameterized by `timeperiods` (default defaulttimeperiods), `smoothperiods` (default defaultsmoothperiods), `signalperiods` (default defaultsignalperiods). -- Output range: Varies (see docs). -- Requires `timePeriods + smoothPeriods` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MACD](../macd/Macd.md), [TSI](../tsi/Tsi.md) | **Complementary:** Signal line for crossovers | **Trading note:** Price Momentum Oscillator; double-smoothed ROC. Decisionpoint.com creation. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. PMO (Price Momentum Oscillator), developed by Carl Swenlin at DecisionPoint, is a double-smoothed 1-bar rate of change. It applies two custom EMA passes to a percentage ROC, producing a momentum oscillator that is smoother than raw ROC yet more responsive than triple-smoothed alternatives like TRIX. The custom EMA uses $\alpha = 2/N$ rather than the standard $2/(N+1)$, and seeds with the SMA of the first N values. PMO oscillates around zero: positive values indicate upward momentum, negative values indicate downward momentum. @@ -163,4 +161,4 @@ $$ - Swenlin, C. "DecisionPoint Price Momentum Oscillator (PMO)." DecisionPoint.com. - StockCharts.com: "DecisionPoint Price Momentum Oscillator (PMO)" Technical Analysis documentation. -- Murphy, J. J. (1999). "Technical Analysis of the Financial Markets." New York Institute of Finance. +- Murphy, J. J. (1999). "Technical Analysis of the Financial Markets." New York Institute of Finance. \ No newline at end of file diff --git a/lib/momentum/ppo/Ppo.md b/lib/momentum/ppo/Ppo.md index 27e43d8b..e469da6e 100644 --- a/lib/momentum/ppo/Ppo.md +++ b/lib/momentum/ppo/Ppo.md @@ -13,9 +13,7 @@ | **PineScript** | [ppo.pine](ppo.pine) | - PPO (Percentage Price Oscillator) measures the percentage difference between a fast EMA and a slow EMA. -- Parameterized by `fastPeriod` (default 12), `slowPeriod` (default 26), `signalPeriod` (default 9). -- Output range: Varies (see docs). -- Requires `slowPeriod + signalPeriod` bars (35 default) of warmup before first valid output (IsHot = true). +- **Similar:** [MACD](../macd/Macd.md), [APO](../../oscillators/apo/Apo.md) | **Complementary:** Volume oscillator | **Trading note:** Percentage Price Oscillator; MACD expressed as percentage. Comparable across instruments. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. PPO (Percentage Price Oscillator) measures the percentage difference between a fast EMA and a slow EMA. It is functionally equivalent to MACD normalized by the slow EMA, producing values that are comparable across instruments with different price levels. The implementation outputs three components: the PPO line, a signal line (EMA of PPO), and a histogram (PPO minus Signal). @@ -168,4 +166,4 @@ $$ - Appel, G. (2005). "Technical Analysis: Power Tools for Active Investors." FT Press. - Murphy, J. J. (1999). "Technical Analysis of the Financial Markets." New York Institute of Finance. - StockCharts.com: "Percentage Price Oscillator (PPO)" Technical Analysis documentation. -- TA-Lib documentation: PPO function reference. +- TA-Lib documentation: PPO function reference. \ No newline at end of file diff --git a/lib/momentum/prs/Prs.md b/lib/momentum/prs/Prs.md index 2c23088f..912dbf6e 100644 --- a/lib/momentum/prs/Prs.md +++ b/lib/momentum/prs/Prs.md @@ -13,9 +13,7 @@ | **PineScript** | [prs.pine](prs.pine) | - **Category:** Momentum **Also known as:** Relative Strength Comparison, Price Ratio, Performance Ratio -- Parameterized by `smoothperiod` (default 1). -- Output range: Varies (see docs). -- Requires `smoothPeriod` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ROC](../roc/Roc.md), [Bias](../bias/Bias.md) | **Complementary:** Relative strength vs benchmark | **Trading note:** Price Relative Strength; ratio or spread between two series. Sector rotation tool. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. **Category:** Momentum @@ -133,4 +131,4 @@ The SIMD bottleneck is the recursive EMA. A batch-mode implementation can precom - **ROC/ROCP/ROCR:** Single-asset rate of change variants - **RSI:** Single-asset momentum oscillator - **Beta:** Statistical measure of relative volatility -- **Correlation:** Measures how two assets move together +- **Correlation:** Measures how two assets move together \ No newline at end of file diff --git a/lib/momentum/roc/Roc.md b/lib/momentum/roc/Roc.md index 746acf0e..1a1c1ce4 100644 --- a/lib/momentum/roc/Roc.md +++ b/lib/momentum/roc/Roc.md @@ -13,9 +13,7 @@ | **PineScript** | [roc.pine](roc.pine) | - ROC (Rate of Change) calculates the absolute price difference between the current value and the value N periods ago. -- Parameterized by `period` (default 9). -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ROCP](../rocp/Rocp.md), [MOM](../mom/Mom.md) | **Complementary:** Moving average for smoothing | **Trading note:** Rate of Change; percentage price change over n periods. Unbounded oscillator. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ROC (Rate of Change) calculates the absolute price difference between the current value and the value N periods ago. This is the most basic form of momentum measurement, returning the raw price change in the same units as the input data. Unlike ROCP (percentage) or ROCR (ratio), ROC preserves the original scale, making it directly interpretable in dollar/point terms. @@ -154,4 +152,4 @@ The span-based calculation is a simple loop with no dependencies between iterati - Pring, M. J. (2014). "Technical Analysis Explained." McGraw-Hill. - Murphy, J. J. (1999). "Technical Analysis of the Financial Markets." New York Institute of Finance. -- TradingView PineScript Reference: ta.roc, ta.mom +- TradingView PineScript Reference: ta.roc, ta.mom \ No newline at end of file diff --git a/lib/momentum/rocp/Rocp.md b/lib/momentum/rocp/Rocp.md index 5e98712b..c2e46093 100644 --- a/lib/momentum/rocp/Rocp.md +++ b/lib/momentum/rocp/Rocp.md @@ -13,9 +13,7 @@ | **PineScript** | [rocp.pine](rocp.pine) | - ROCP (Rate of Change Percentage) calculates the percentage change between the current value and the value N periods ago. -- Parameterized by `period` (default 9). -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ROC](../roc/Roc.md), [ROCR](../rocr/Rocr.md) | **Complementary:** Volume ROC | **Trading note:** Rate of Change Percentage; decimal form of ROC (0.05 = 5%). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ROCP (Rate of Change Percentage) calculates the percentage change between the current value and the value N periods ago. This is the most commonly used form of rate of change, expressing change in percentage terms that are directly interpretable (e.g., 5.0 = 5% increase). @@ -135,4 +133,4 @@ $$ - Pring, M. J. (2014). "Technical Analysis Explained." McGraw-Hill. - Murphy, J. J. (1999). "Technical Analysis of the Financial Markets." -- TA-Lib Documentation: ROCP function +- TA-Lib Documentation: ROCP function \ No newline at end of file diff --git a/lib/momentum/rocr/Rocr.md b/lib/momentum/rocr/Rocr.md index de2384fa..54f2d5f2 100644 --- a/lib/momentum/rocr/Rocr.md +++ b/lib/momentum/rocr/Rocr.md @@ -13,9 +13,7 @@ | **PineScript** | [rocr.pine](rocr.pine) | - ROCR (Rate of Change Ratio) calculates the ratio between the current value and the value N periods ago. -- Parameterized by `period` (default 9). -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ROC](../roc/Roc.md), [ROCP](../rocp/Rocp.md) | **Complementary:** Trend filters | **Trading note:** Rate of Change Ratio; Price(t)/Price(t−n). Ratio form centered on 1.0. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ROCR (Rate of Change Ratio) calculates the ratio between the current value and the value N periods ago. Values hover around 1.0, with values above 1.0 indicating price increase and values below 1.0 indicating price decrease. Unlike ROC (absolute) or ROCP (percentage), ROCR provides a dimensionless multiplier that directly shows the price ratio. @@ -159,4 +157,4 @@ The span-based calculation is a simple loop with no dependencies between iterati - Pring, M. J. (2014). "Technical Analysis Explained." McGraw-Hill. - Murphy, J. J. (1999). "Technical Analysis of the Financial Markets." New York Institute of Finance. -- TA-Lib Documentation: ROCR function +- TA-Lib Documentation: ROCR function \ No newline at end of file diff --git a/lib/momentum/rsi/Rsi.md b/lib/momentum/rsi/Rsi.md index a2756fb6..122bc4d5 100644 --- a/lib/momentum/rsi/Rsi.md +++ b/lib/momentum/rsi/Rsi.md @@ -13,9 +13,7 @@ | **PineScript** | [rsi.pine](rsi.pine) | - The Relative Strength Index measures the speed and magnitude of price changes. -- Parameterized by `period` (default 14). -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [CMO](../cmo/Cmo.md), [Stoch](../../oscillators/stoch/Stoch.md) | **Complementary:** MACD for trend confirmation | **Trading note:** Wilder's RSI; 70/30 overbought/oversold. Divergences signal reversals. 14-period standard. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Relative Strength Index measures the speed and magnitude of price changes. Introduced by J. Welles Wilder Jr. in 1978, it oscillates between 0 and 100, identifying overbought and oversold conditions. The "Relative Strength" name is misleading: RSI measures internal strength (price versus itself) not relative strength (asset versus benchmark). Wilder knew this. He kept the name anyway. Marketing, perhaps. @@ -234,4 +232,4 @@ rsi.Prime(historicalPrices); // Ready for live data - Wilder, J. W. (1978). *New Concepts in Technical Trading Systems*. Trend Research. Chapter: Relative Strength Index. - Constance Brown. (1999). *Technical Analysis for the Trading Professional*. McGraw-Hill. (RSI divergence patterns) -- Cutler, David. (1991). "RSI Revisited." *Technical Analysis of Stocks & Commodities*. (Smoothed RSI variants) +- Cutler, David. (1991). "RSI Revisited." *Technical Analysis of Stocks & Commodities*. (Smoothed RSI variants) \ No newline at end of file diff --git a/lib/momentum/rsx/Rsx.md b/lib/momentum/rsx/Rsx.md index cd154394..a89dec06 100644 --- a/lib/momentum/rsx/Rsx.md +++ b/lib/momentum/rsx/Rsx.md @@ -13,9 +13,7 @@ | **PineScript** | [rsx.pine](rsx.pine) | - Mark Jurik's RSX represents the pinnacle of bounded momentum oscillator design. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [RSI](../rsi/Rsi.md), [CMO](../cmo/Cmo.md) | **Complementary:** Bollinger Bands for volatility | **Trading note:** Jurik RSX; smoother version of RSI with less noise. Same 0–100 scale. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Mark Jurik's RSX represents the pinnacle of bounded momentum oscillator design. Standard RSI suffers from a fundamental paradox: raw RSI produces jagged noise triggering false signals at overbought/oversold boundaries, but smoothing introduces unacceptable lag that delays turning points. RSX solves this through cascaded IIR filter topology that eliminates high-frequency noise while preserving linear phase response. The result: output so smooth it resembles a sine wave, yet turns precisely at market extrema with zero effective lag. @@ -317,4 +315,4 @@ rsx.Pub += (sender, args) => - Jurik, M. (1990s). "RSX: Relative Strength Quality Index." Jurik Research. Proprietary documentation. - Ehlers, J. F. (2001). *Rocket Science for Traders*. Wiley. IIR filter design principles. - ProRealCode. "Jurik RSX Implementation." https://www.prorealcode.com/prorealtime-indicators/jurik-rsx/ -- Scribd. "Jurik RSX Algorithm Reference." https://scribd.com/document/253633684/Jurik-RSX +- Scribd. "Jurik RSX Algorithm Reference." https://scribd.com/document/253633684/Jurik-RSX \ No newline at end of file diff --git a/lib/momentum/sam/Sam.md b/lib/momentum/sam/Sam.md index 5d103846..351c948c 100644 --- a/lib/momentum/sam/Sam.md +++ b/lib/momentum/sam/Sam.md @@ -13,9 +13,7 @@ | **PineScript** | [sam.pine](sam.pine) | - The Smoothed Adaptive Momentum oscillator measures price momentum over an adaptively determined lookback period equal to the dominant cycle length,... -- Parameterized by `alpha` (default 0.07), `cutoff` (default 8). -- Output range: Varies (see docs). -- Requires `MaxCyclePeriod * 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MOM](../mom/Mom.md), [ROC](../roc/Roc.md) | **Complementary:** Moving average for trend | **Trading note:** Simple Accumulative Momentum; cumulative sum of momentum values. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Smoothed Adaptive Momentum oscillator measures price momentum over an adaptively determined lookback period equal to the dominant cycle length, then smooths the result with a 2-pole Super Smoother filter. Unlike fixed-period momentum indicators (ROC, TRIX) that use an arbitrary lookback, SAM measures the dominant cycle via Ehlers' Homodyne Discriminator and uses that cycle length as the momentum window, ensuring that the momentum measurement always spans exactly one full cycle. This eliminates the half-cycle phase distortion that plagues fixed-period momentum, producing a zero-lag momentum oscillator that naturally adapts to changing market rhythm. @@ -148,4 +146,4 @@ O(1) per bar. The `ATAN2` call dominates (~25 cycles on modern x86). WarmupPerio | Super Smoother | No | 2-pole IIR; z-transform has poles inside unit circle, inherently serial | | Adaptive indexing (ring buffer) | No | Index depends on computed dcPeriod | -SAM cannot be meaningfully vectorized — every stage except the FIR smoother has a data dependency that threads through the recursive EMA states. The dominant SIMD opportunity is the batch computation of candidate FIR outputs using strided AVX2 loads, but the downstream homodyne feedback loop negates it. Batch mode runs the same scalar kernel as streaming. +SAM cannot be meaningfully vectorized — every stage except the FIR smoother has a data dependency that threads through the recursive EMA states. The dominant SIMD opportunity is the batch computation of candidate FIR outputs using strided AVX2 loads, but the downstream homodyne feedback loop negates it. Batch mode runs the same scalar kernel as streaming. \ No newline at end of file diff --git a/lib/momentum/tsi/Tsi.md b/lib/momentum/tsi/Tsi.md index 27cd775f..691768ee 100644 --- a/lib/momentum/tsi/Tsi.md +++ b/lib/momentum/tsi/Tsi.md @@ -13,9 +13,7 @@ | **PineScript** | [tsi.pine](tsi.pine) | - The True Strength Index (TSI) is a momentum oscillator developed by William Blau that uses double-smoothed exponential moving averages of price mom... -- Parameterized by `longPeriod` (default 25), `shortPeriod` (default 13), `signalPeriod` (default 13). -- Output range: $-100$ to $+100$. -- Requires `longPeriod + shortPeriod + signalPeriod` bars (51 default) of warmup before first valid output (IsHot = true). +- **Similar:** [MACD](../macd/Macd.md), [PMO](../pmo/Pmo.md) | **Complementary:** Signal line crossovers | **Trading note:** True Strength Index; double-smoothed momentum ratio. Range ±100. Good for divergence analysis. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The True Strength Index (TSI) is a momentum oscillator developed by William Blau that uses double-smoothed exponential moving averages of price momentum to reduce noise and identify trend strength and direction. @@ -147,4 +145,4 @@ Cross-validated against: - Blau, William. "Momentum, Direction, and Divergence." Wiley, 1995 - Blau, William. "True Strength Index." Technical Analysis of Stocks & Commodities, 1991 -- [TradingView TSI Documentation](https://www.tradingview.com/support/solutions/43000502302-true-strength-index-tsi/) +- [TradingView TSI Documentation](https://www.tradingview.com/support/solutions/43000502302-true-strength-index-tsi/) \ No newline at end of file diff --git a/lib/momentum/vel/Vel.md b/lib/momentum/vel/Vel.md index 96962b8f..6f7e991c 100644 --- a/lib/momentum/vel/Vel.md +++ b/lib/momentum/vel/Vel.md @@ -13,9 +13,7 @@ | **PineScript** | [vel.pine](vel.pine) | - Jurik Velocity (VEL) measures price rate-of-change through the differential between two weighted moving averages with distinct inertia profiles. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MOM](../mom/Mom.md), [ROC](../roc/Roc.md) | **Complementary:** Acceleration for second derivative | **Trading note:** Velocity; first derivative of price. Positive = rising, zero-crossing = inflection. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Jurik Velocity (VEL) measures price rate-of-change through the differential between two weighted moving averages with distinct inertia profiles. Standard momentum ($P_t - P_{t-n}$) amplifies noise: single outlier bars create false signals. VEL exploits the different convergence speeds of Parabolic Weighted Moving Average (PWMA) and linear Weighted Moving Average (WMA) to isolate clean velocity information. The quadratic weighting of PWMA responds faster than linear WMA; their difference captures acceleration without bar-to-bar noise. @@ -307,4 +305,4 @@ foreach (var bar in bars) - Jurik, M. (1990s). "Jurik Velocity (VEL)." Jurik Research. Proprietary documentation. - Kaufman, P. J. (2013). *Trading Systems and Methods*. 5th ed. Wiley. Chapter on weighted moving averages. -- Ehlers, J. F. (2001). *Rocket Science for Traders*. Wiley. Filter design principles. +- Ehlers, J. F. (2001). *Rocket Science for Traders*. Wiley. Filter design principles. \ No newline at end of file diff --git a/lib/numerics/accel/Accel.md b/lib/numerics/accel/Accel.md index c6df3aae..f8808eba 100644 --- a/lib/numerics/accel/Accel.md +++ b/lib/numerics/accel/Accel.md @@ -14,8 +14,6 @@ - ACCEL measures the rate of change of velocity—the acceleration of a time series. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `3` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ACCEL measures the rate of change of velocity—the acceleration of a time series. As the second derivative, it reveals momentum shifts before they manifest in price direction. Positive acceleration means velocity is increasing (trend strengthening); negative means velocity is decreasing (trend weakening). This O(1) streaming implementation uses FMA optimization and SIMD batch processing. @@ -187,4 +185,4 @@ ACCEL is a fundamental operation. Validation confirms exact match with manual ca - Newton, Isaac. (1687). "Philosophiæ Naturalis Principia Mathematica." - Numerical Methods: Finite Difference Approximations. -- Murphy, John J. (1999). "Technical Analysis of the Financial Markets." +- Murphy, John J. (1999). "Technical Analysis of the Financial Markets." \ No newline at end of file diff --git a/lib/numerics/betadist/Betadist.md b/lib/numerics/betadist/Betadist.md index fe858680..302a26fb 100644 --- a/lib/numerics/betadist/Betadist.md +++ b/lib/numerics/betadist/Betadist.md @@ -13,9 +13,7 @@ | **PineScript** | [betadist.pine](betadist.pine) | - BETADIST computes the cumulative distribution function of the Beta distribution applied to a min-max normalized price series. -- Parameterized by `period` (default 50), `alpha` (default 2.0), `beta` (default 2.0). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Beta distribution; models bounded random variables. Used for win-rate analysis and position sizing. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. BETADIST computes the cumulative distribution function of the Beta distribution applied to a min-max normalized price series. The source price is first normalized to $[0, 1]$ over a lookback window, then passed through the regularized incomplete beta function $I_x(\alpha, \beta)$ to produce a probability-mapped oscillator. The two shape parameters $\alpha$ and $\beta$ control the nonlinear mapping: symmetric parameters ($\alpha = \beta$) produce a sigmoid-like transformation centered at 0.5, while asymmetric parameters skew the mapping to emphasize extremes in either direction. @@ -92,4 +90,4 @@ Transcendental math blocks SIMD. Batch is a simple scalar loop. For large datase - Abramowitz, M. & Stegun, I. (1964). *Handbook of Mathematical Functions*, Chapter 26 - Press, W. et al. (2007). *Numerical Recipes*, 3rd ed. Cambridge, §6.4 (Incomplete Beta Function) -- PineScript reference: [`betadist.pine`](betadist.pine) +- PineScript reference: [`betadist.pine`](betadist.pine) \ No newline at end of file diff --git a/lib/numerics/binomdist/Binomdist.md b/lib/numerics/binomdist/Binomdist.md index 3aa93430..b37a4103 100644 --- a/lib/numerics/binomdist/Binomdist.md +++ b/lib/numerics/binomdist/Binomdist.md @@ -13,9 +13,7 @@ | **PineScript** | [binomdist.pine](binomdist.pine) | - BINOMDIST computes the cumulative distribution function of the Binomial distribution, mapping a min-max normalized price to a success probability $... -- Parameterized by `period` (default 50), `trials` (default 20), `threshold` (default 10). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Binomial distribution; models success/failure sequences. Win streak probability in trading. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. BINOMDIST computes the cumulative distribution function of the Binomial distribution, mapping a min-max normalized price to a success probability $p$ and evaluating $P(X \leq k)$ for $X \sim \text{Binomial}(n, p)$. The normalized price position within its lookback range determines the probability of success per trial, while the trial count $n$ and threshold $k$ control the shape of the CDF response. The output is a $[0, 1]$ bounded oscillator where values near 0 indicate the price-derived probability makes $k$ or fewer successes very unlikely (bullish pressure), and values near 1 indicate $k$ successes are very likely (established range). @@ -86,4 +84,4 @@ PMF batch can use SVML exp vectorization. CDF must remain scalar. - Bernoulli, J. (1713). *Ars Conjectandi* - Press, W. et al. (2007). *Numerical Recipes*, 3rd ed., §6.2 (Incomplete Beta as alternative) -- PineScript reference: [`binomdist.pine`](binomdist.pine) +- PineScript reference: [`binomdist.pine`](binomdist.pine) \ No newline at end of file diff --git a/lib/numerics/change/Change.md b/lib/numerics/change/Change.md index f0eb0277..cf881829 100644 --- a/lib/numerics/change/Change.md +++ b/lib/numerics/change/Change.md @@ -13,9 +13,7 @@ | **PineScript** | [change.pine](change.pine) | - CHANGE calculates the percentage change between the current value and a value N periods ago. -- Parameterized by `period` (default 1). -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Simple price change (difference); foundation for momentum and rate-of-change calculations. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. CHANGE calculates the percentage change between the current value and a value N periods ago. This fundamental indicator forms the basis for momentum analysis, rate of change calculations, and relative performance comparisons. @@ -92,4 +90,4 @@ var smaChange = new Change(new Sma(20), 5); ## References - Murphy, J. (1999). "Technical Analysis of the Financial Markets." New York Institute of Finance. -- Pring, M. (2002). "Technical Analysis Explained." McGraw-Hill. +- Pring, M. (2002). "Technical Analysis Explained." McGraw-Hill. \ No newline at end of file diff --git a/lib/numerics/cwt/Cwt.md b/lib/numerics/cwt/Cwt.md index c8542d53..37f1b309 100644 --- a/lib/numerics/cwt/Cwt.md +++ b/lib/numerics/cwt/Cwt.md @@ -13,9 +13,7 @@ | **PineScript** | [cwt.pine](cwt.pine) | - CWT computes the magnitude of the Continuous Wavelet Transform at a specified scale using the Morlet wavelet, providing a time-frequency decomposit... -- Parameterized by `scale` (default 10.0), `omega0` (default 6.0). -- Output range: Varies (see docs). -- Requires windowSize (2K+1) bars of warmup before first valid output (IsHot = true), where K = round(3 × scale). +- **Similar:** [DWT](../dwt/Dwt.md), [FFT](../fft/Fft.md) | **Trading note:** Continuous Wavelet Transform; multi-resolution time-frequency analysis for cycle detection. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. CWT computes the magnitude of the Continuous Wavelet Transform at a specified scale using the Morlet wavelet, providing a time-frequency decomposition that measures the energy content of a specific frequency band at each point in time. Unlike Fourier analysis which loses time localization, the wavelet transform maintains both time and frequency information simultaneously. The output is a non-negative magnitude series where peaks indicate strong presence of the target frequency (determined by the scale parameter) and troughs indicate absence of that frequency component. @@ -97,4 +95,4 @@ Strong SIMD candidate for batch: inner products are FMA-vectorizable. AVX2 proce - Morlet, J. et al. (1982). "Wave propagation and sampling theory." *Geophysics*, 47(2): 203-236 - Torrence, C. & Compo, G.P. (1998). "A Practical Guide to Wavelet Analysis." *Bulletin of the American Meteorological Society* -- PineScript reference: [`cwt.pine`](cwt.pine) +- PineScript reference: [`cwt.pine`](cwt.pine) \ No newline at end of file diff --git a/lib/numerics/decay/Decay.md b/lib/numerics/decay/Decay.md index 774f21d0..21559849 100644 --- a/lib/numerics/decay/Decay.md +++ b/lib/numerics/decay/Decay.md @@ -13,9 +13,7 @@ | **PineScript** | [decay.pine](decay.pine) | - DECAY (Linear Decay) tracks the maximum of the current input and the previous output minus a fixed absolute step of `1/period`. -- Parameterized by `period` (default 5). -- Output range: Same as input — this is an overlay indicator. -- Requires `1` bar of warmup before first valid output (IsHot = true). +- **Similar:** [EDecay](../edecay/Edecay.md) | **Trading note:** Linear decay function; models signal fading over time. Used for recency-weighted calculations. - Validated against Tulip Indicators `ti_decay` reference algorithm. DECAY implements the Tulip Indicators `ti_decay` function. When price is above the decayed level, output snaps to price. When price falls below, the output decays linearly at a rate of `1/period` per bar, creating a ceiling that gradually descends. This produces a one-sided envelope that hugs price from above. @@ -149,4 +147,4 @@ reaching zero after $k = v \cdot p$ bars (assuming $v > 0$). ## References - Tulip Indicators Library: https://tulipindicators.org/decay -- Kegel, L. "Tulip Indicators" — Open-source C library of technical indicators. +- Kegel, L. "Tulip Indicators" — Open-source C library of technical indicators. \ No newline at end of file diff --git a/lib/numerics/dwt/Dwt.md b/lib/numerics/dwt/Dwt.md index 5408274e..52e363d7 100644 --- a/lib/numerics/dwt/Dwt.md +++ b/lib/numerics/dwt/Dwt.md @@ -13,9 +13,7 @@ | **PineScript** | [dwt.pine](dwt.pine) | - The Discrete Wavelet Transform decomposes a price series into multi-resolution frequency components using the a trous (with holes) stationary Haar ... -- Parameterized by `levels` (default 4), `output` (default 0). -- Output range: Varies (see docs). -- Requires `bufferSize` bars of warmup before first valid output (IsHot = true). +- **Similar:** [CWT](../cwt/Cwt.md), [FFT](../fft/Fft.md) | **Trading note:** Discrete Wavelet Transform; decomposes signal into frequency bands at different scales. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Discrete Wavelet Transform decomposes a price series into multi-resolution frequency components using the a trous (with holes) stationary Haar wavelet. Unlike decimated DWT, the stationary variant preserves time alignment at every scale, producing an approximation (trend) and detail coefficients (noise/cycles) at each decomposition level. Each level doubles the effective receptive field: level $L$ captures structure at $2^L$ bars. With 1-8 levels and $O(L)$ per-bar cost, DWT provides a complete multi-scale decomposition that cleanly separates trend from noise without the phase distortion inherent in moving-average cascades. @@ -111,4 +109,4 @@ First decomposition level fully SIMD. Deeper levels become too small for effecti - Daubechies, I. "Ten Lectures on Wavelets." SIAM, 1992. - Holschneider, M. et al. "A Real-Time Algorithm for Signal Analysis with the Help of the Wavelet Transform." Wavelets: Time-Frequency Methods and Phase Space, 1989. - Percival, D. & Walden, A. "Wavelet Methods for Time Series Analysis." Cambridge University Press, 2000. -- Gencay, R., Selcuk, F. & Whitcher, B. "An Introduction to Wavelets and Other Filtering Methods in Finance and Economics." Academic Press, 2002. +- Gencay, R., Selcuk, F. & Whitcher, B. "An Introduction to Wavelets and Other Filtering Methods in Finance and Economics." Academic Press, 2002. \ No newline at end of file diff --git a/lib/numerics/edecay/Edecay.md b/lib/numerics/edecay/Edecay.md index 85355592..ed58feb3 100644 --- a/lib/numerics/edecay/Edecay.md +++ b/lib/numerics/edecay/Edecay.md @@ -13,9 +13,7 @@ | **PineScript** | [edecay.pine](edecay.pine) | - EDECAY (Exponential Decay) tracks the maximum of the current input and the previous output multiplied by a decay factor of `(period-1)/period`. -- Parameterized by `period` (default 5). -- Output range: Same as input — this is an overlay indicator. -- Requires `1` bar of warmup before first valid output (IsHot = true). +- **Similar:** [Decay](../decay/Decay.md) | **Trading note:** Exponential decay; faster initial fading than linear. Natural half-life model for signal importance. - Validated against Tulip Indicators `ti_edecay` reference algorithm. EDECAY implements the exponential decaying function. When price is above the decayed level, output snaps to price. When price falls below, the output decays exponentially by multiplying by `(period-1)/period` per bar, creating a ceiling that gradually descends. Unlike linear DECAY which subtracts a fixed amount, EDECAY's multiplicative factor produces a proportional decay rate. @@ -161,4 +159,4 @@ The output asymptotically approaches zero but never reaches it ($v > 0$). ## References - Tulip Indicators Library: https://tulipindicators.org/edecay -- Kegel, L. "Tulip Indicators" — Open-source C library of technical indicators. +- Kegel, L. "Tulip Indicators" — Open-source C library of technical indicators. \ No newline at end of file diff --git a/lib/numerics/expdist/Expdist.md b/lib/numerics/expdist/Expdist.md index b44bccac..e16b1ad6 100644 --- a/lib/numerics/expdist/Expdist.md +++ b/lib/numerics/expdist/Expdist.md @@ -13,9 +13,7 @@ | **PineScript** | [expdist.pine](expdist.pine) | - The Exponential Distribution CDF transforms a min-max normalized price into the cumulative distribution function of the exponential distribution, p... -- Parameterized by `period` (default 50), `lambda` (default 3.0). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Exponential distribution; models time between events. Used for trade arrival rate analysis. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Exponential Distribution CDF transforms a min-max normalized price into the cumulative distribution function of the exponential distribution, producing an output in $[0, 1]$. The exponential distribution models memoryless waiting times: the probability that a normalized value falls below a threshold depends only on the rate parameter $\lambda$, not on any history. Higher $\lambda$ values compress the CDF curve toward zero, making the indicator more sensitive to small normalized deviations. With $O(N)$ normalization and $O(1)$ CDF evaluation, EXPDIST provides a nonlinear percentile ranking that emphasizes the lower end of the price range while compressing the upper end. @@ -114,4 +112,4 @@ With SVML exp: 4 outputs per AVX2 cycle. Without SVML: scalar loop but still O(1 - Erlang, A.K. "The Theory of Probabilities and Telephone Conversations." Nyt Tidsskrift for Matematik B, 1909. - Johnson, N.L., Kotz, S. & Balakrishnan, N. "Continuous Univariate Distributions, Vol. 1." Wiley, 1994. - Ross, S. "Introduction to Probability Models." Academic Press, 12th edition, 2019. -- Cont, R. "Empirical Properties of Asset Returns: Stylized Facts and Statistical Issues." Quantitative Finance, 2001. +- Cont, R. "Empirical Properties of Asset Returns: Stylized Facts and Statistical Issues." Quantitative Finance, 2001. \ No newline at end of file diff --git a/lib/numerics/exptrans/Exptrans.md b/lib/numerics/exptrans/Exptrans.md index 67bd3791..2e825e7a 100644 --- a/lib/numerics/exptrans/Exptrans.md +++ b/lib/numerics/exptrans/Exptrans.md @@ -14,8 +14,6 @@ - The Exponential (EXP) transformer applies the natural exponential function $e^x$ to each value in a time series. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `0` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Exponential (EXP) transformer applies the natural exponential function $e^x$ to each value in a time series. As the inverse of the natural logarithm, it converts additive relationships back to multiplicative ones, making it essential for reconstructing price levels from log-returns and implementing models that assume log-normal distributions. @@ -197,4 +195,4 @@ var recovered = exp.Update(logPrice); // ≈ 150.0 - Euler, L. (1748). *Introductio in analysin infinitorum*. - Maor, E. (1994). *e: The Story of a Number*. Princeton University Press. -- Hull, J. (2018). *Options, Futures, and Other Derivatives*. Pearson. (Black-Scholes applications) +- Hull, J. (2018). *Options, Futures, and Other Derivatives*. Pearson. (Black-Scholes applications) \ No newline at end of file diff --git a/lib/numerics/fdist/Fdist.md b/lib/numerics/fdist/Fdist.md index 172474e2..e1c74743 100644 --- a/lib/numerics/fdist/Fdist.md +++ b/lib/numerics/fdist/Fdist.md @@ -13,9 +13,7 @@ | **PineScript** | [fdist.pine](fdist.pine) | - The F-Distribution CDF transforms a min-max normalized price into the cumulative distribution function of the F-distribution (Fisher-Snedecor distr... -- Parameterized by `d1` (default 1), `d2` (default 1), `period` (default 14). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Trading note:** F-distribution; used in ANOVA and regression significance tests. Compares model variances. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The F-Distribution CDF transforms a min-max normalized price into the cumulative distribution function of the F-distribution (Fisher-Snedecor distribution), producing an output in $[0, 1]$. The F-distribution arises as the ratio of two chi-squared random variables divided by their respective degrees of freedom, making it the natural distribution for variance ratio tests. By mapping normalized price through the regularized incomplete beta function with parameters tied to degrees of freedom $d_1$ and $d_2$, FDIST provides a probabilistic ranking that is asymmetric: the CDF shape changes qualitatively depending on whether $d_1 < d_2$, $d_1 = d_2$, or $d_1 > d_2$, giving traders control over the nonlinear response curve. @@ -115,4 +113,4 @@ No SIMD benefit for the core evaluation. Outer loop across observations parallel - Snedecor, G.W. "Calculation and Interpretation of Analysis of Variance and Covariance." Collegiate Press, 1934. - Press, W.H. et al. "Numerical Recipes: The Art of Scientific Computing." 3rd edition, Cambridge University Press, 2007. Chapter 6.4 (Incomplete Beta Function). - Lo, A. & MacKinlay, A.C. "Stock Market Prices Do Not Follow Random Walks: Evidence from a Simple Specification Test." Review of Financial Studies, 1988. -- Lentz, W.J. "Generating Bessel Functions in Mie Scattering Calculations Using Continued Fractions." Applied Optics, 1976. +- Lentz, W.J. "Generating Bessel Functions in Mie Scattering Calculations Using Continued Fractions." Applied Optics, 1976. \ No newline at end of file diff --git a/lib/numerics/fft/Fft.md b/lib/numerics/fft/Fft.md index ba0a10ca..da32ef1a 100644 --- a/lib/numerics/fft/Fft.md +++ b/lib/numerics/fft/Fft.md @@ -13,10 +13,8 @@ | **PineScript** | [fft.pine](fft.pine) | - The FFT indicator computes the dominant cycle period in a price series using a radix-2 Cooley-Tukey Fast Fourier Transform with a Hanning window. -- Parameterized by `windowSize` (default 64), `minPeriod` (default 4), `maxPeriod` (default 32). -- Output range: [minPeriod, maxPeriod] bars. -- Requires windowSize bars of warmup before first valid output (IsHot = true). - True $O(N \log N)$ radix-2 FFT with bit-reversal permutation and Cooley-Tukey butterflies. +- **Similar:** [IFFT](../ifft/Ifft.md), [CWT](../cwt/Cwt.md) | **Trading note:** Fast Fourier Transform; identifies dominant frequencies/cycles in price data. Foundation of spectral analysis. The FFT indicator computes the dominant cycle period in a price series using a true radix-2 Cooley-Tukey Fast Fourier Transform with a Hanning window. Rather than outputting frequency-domain magnitudes, it returns the estimated dominant cycle period in bars, making it directly usable as an adaptive period input for other indicators. The implementation uses an in-place iterative radix-2 FFT with bit-reversal permutation and Cooley-Tukey butterfly operations, achieving $O(N \log N)$ complexity. Parabolic interpolation on the magnitude spectrum provides sub-bin frequency resolution. With window sizes restricted to powers of two (32, 64, or 128), the indicator achieves precise cycle detection within user-specified period bounds with pre-allocated work arrays for zero-allocation streaming. @@ -157,4 +155,4 @@ Moderate SIMD potential: butterfly FMA operations are vectorizable within each s - Ehlers, J.F. "Rocket Science for Traders." Wiley, 2001. - Harris, F.J. "On the Use of Windows for Harmonic Analysis with the Discrete Fourier Transform." *Proc. IEEE*, 1978. - Oppenheim, A.V. & Schafer, R.W. "Discrete-Time Signal Processing." 3rd edition, Pearson, 2010. -- PineScript reference: [`fft.pine`](fft.pine) +- PineScript reference: [`fft.pine`](fft.pine) \ No newline at end of file diff --git a/lib/numerics/gammadist/Gammadist.md b/lib/numerics/gammadist/Gammadist.md index b20bebf0..18de96d8 100644 --- a/lib/numerics/gammadist/Gammadist.md +++ b/lib/numerics/gammadist/Gammadist.md @@ -13,9 +13,7 @@ | **PineScript** | [gammadist.pine](gammadist.pine) | - The Gamma Distribution CDF transforms a min-max normalized price into the cumulative distribution function of the gamma distribution, producing an ... -- Parameterized by `alpha` (default 2.0), `beta` (default 1.0), `period` (default 14). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Gamma distribution; models waiting times and aggregate claims. Used in risk modeling. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Gamma Distribution CDF transforms a min-max normalized price into the cumulative distribution function of the gamma distribution, producing an output in $[0, 1]$. The gamma distribution generalizes the exponential distribution by adding a shape parameter $\alpha$ that controls whether the PDF is monotonically decreasing ($\alpha < 1$), exponential ($\alpha = 1$), or bell-shaped with a right skew ($\alpha > 1$). Combined with a rate parameter $\beta$ that scales the normalized input, GAMMADIST provides a flexible nonlinear mapping with controllable asymmetry. The CDF is computed via the regularized lower incomplete gamma function using series expansion or Lentz continued fraction, selecting the faster-converging method based on the argument relative to the shape parameter. @@ -120,4 +118,4 @@ No practical SIMD benefit. Parallelism via PLINQ on the outer observation loop. - Lanczos, C. "A Precision Approximation of the Gamma Function." SIAM J. Numerical Analysis B, 1964. - Press, W.H. et al. "Numerical Recipes: The Art of Scientific Computing." 3rd edition, Cambridge University Press, 2007. Chapter 6.2 (Incomplete Gamma Function). - Lentz, W.J. "Generating Bessel Functions in Mie Scattering Calculations Using Continued Fractions." Applied Optics, 1976. -- Johnson, N.L., Kotz, S. & Balakrishnan, N. "Continuous Univariate Distributions, Vol. 1." Wiley, 1994. +- Johnson, N.L., Kotz, S. & Balakrishnan, N. "Continuous Univariate Distributions, Vol. 1." Wiley, 1994. \ No newline at end of file diff --git a/lib/numerics/highest/Highest.md b/lib/numerics/highest/Highest.md index 26c9d18a..b0b6c669 100644 --- a/lib/numerics/highest/Highest.md +++ b/lib/numerics/highest/Highest.md @@ -13,9 +13,7 @@ | **PineScript** | [highest.pine](highest.pine) | - HIGHEST calculates the maximum value over a rolling lookback window. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Lowest](../lowest/Lowest.md), [MaxIndex](../maxindex/Maxindex.md) | **Trading note:** Rolling maximum; identifies resistance levels and breakout points. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HIGHEST calculates the maximum value over a rolling lookback window. This O(1) amortized streaming implementation uses a monotonic deque algorithm, enabling real-time updates without re-scanning the entire window. Validated against TA-Lib MAX and Tulip max functions. @@ -149,4 +147,4 @@ For batch processing, SIMD can parallelize comparisons within segments. However, - Tarjan, Robert E. (1985). "Amortized Computational Complexity." SIAM Journal on Algebraic Discrete Methods. - Lemire, Daniel. (2006). "Streaming Maximum-Minimum Filter Using No More than Three Comparisons per Element." -- TA-Lib: MAX function documentation. +- TA-Lib: MAX function documentation. \ No newline at end of file diff --git a/lib/numerics/ifft/Ifft.md b/lib/numerics/ifft/Ifft.md index 21d9dada..10c753d6 100644 --- a/lib/numerics/ifft/Ifft.md +++ b/lib/numerics/ifft/Ifft.md @@ -13,10 +13,8 @@ | **PineScript** | [ifft.pine](ifft.pine) | - The IFFT indicator reconstructs a smoothed version of the price series using a true forward FFT → spectral truncation → inverse FFT pipeline. -- Parameterized by `windowSize` (default 64), `numHarmonics` (default 5). -- Output range: Varies (overlays on price chart). -- Requires windowSize bars of warmup before first valid output (IsHot = true). - True $O(N \log N)$ radix-2 FFT/IFFT with bit-reversal permutation and Cooley-Tukey butterflies. +- **Similar:** [FFT](../fft/Fft.md) | **Trading note:** Inverse FFT; reconstructs filtered time-domain signal from frequency domain. Used with FFT for spectral filtering. The IFFT indicator reconstructs a smoothed version of the price series by performing a true radix-2 forward FFT, zeroing frequency bins above the specified number of harmonics (spectral truncation), then applying a true inverse FFT to reconstruct the filtered time-domain signal. The result is a spectral low-pass filter that preserves the dominant cyclical components while discarding high-frequency noise. By controlling the number of retained harmonics $H$, the user adjusts the smoothness/responsiveness trade-off: $H = 1$ yields a near-sinusoidal trend, while $H = N/2$ reproduces the original (windowed) signal. The indicator overlays on price and provides a frequency-domain alternative to conventional moving averages. @@ -141,4 +139,4 @@ Good SIMD potential: both FFT passes are vectorizable. Expected 2× speedup over - Ehlers, J.F. "Cycle Analytics for Traders." Wiley, 2013. - Oppenheim, A.V. & Schafer, R.W. "Discrete-Time Signal Processing." 3rd edition, Pearson, 2010. - Bloomfield, P. "Fourier Analysis of Time Series: An Introduction." 2nd edition, Wiley, 2000. -- PineScript reference: [`ifft.pine`](ifft.pine) +- PineScript reference: [`ifft.pine`](ifft.pine) \ No newline at end of file diff --git a/lib/numerics/jerk/Jerk.md b/lib/numerics/jerk/Jerk.md index 71e5ebdb..ce839943 100644 --- a/lib/numerics/jerk/Jerk.md +++ b/lib/numerics/jerk/Jerk.md @@ -14,8 +14,6 @@ - JERK measures the rate of change of acceleration—called "jerk" in physics. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `4` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. JERK measures the rate of change of acceleration—called "jerk" in physics. As the third derivative, it detects changes in momentum dynamics before they appear in acceleration, velocity, or price. A positive jerk means acceleration is increasing; negative means acceleration is decreasing. This O(1) streaming implementation uses dual FMA optimization and SIMD batch processing for four-point calculations. @@ -211,4 +209,4 @@ JERK is a fundamental operation. Validation confirms exact match with manual cal - Newton, Isaac. (1687). "Philosophiæ Naturalis Principia Mathematica." - Numerical Methods: Finite Difference Approximations. -- Eager, David et al. (2016). "Beyond velocity and acceleration: jerk, snap and higher derivatives." European Journal of Physics. +- Eager, David et al. (2016). "Beyond velocity and acceleration: jerk, snap and higher derivatives." European Journal of Physics. \ No newline at end of file diff --git a/lib/numerics/lineartrans/Lineartrans.md b/lib/numerics/lineartrans/Lineartrans.md index b2aeaf38..54eb21dc 100644 --- a/lib/numerics/lineartrans/Lineartrans.md +++ b/lib/numerics/lineartrans/Lineartrans.md @@ -13,9 +13,7 @@ | **PineScript** | [lineartrans.pine](lineartrans.pine) | - The Linear transformer applies an affine transformation $y = \text{slope} \cdot x + \text{intercept}$ to each value in a time series. -- Parameterized by `slope` (default 1.0), `intercept` (default 0.0). -- Output range: Varies (see docs). -- Requires `0` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Linear transformation; scales and shifts values. Used for indicator normalization and rescaling. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Linear transformer applies an affine transformation $y = \text{slope} \cdot x + \text{intercept}$ to each value in a time series. This fundamental operation enables scaling, offsetting, unit conversion, and normalization—the building blocks for preparing data for analysis or combining signals from different sources. @@ -227,4 +225,4 @@ var offset = new Lineartrans(scale, 1.0, 10.0); // Chain: scale then add 10 - Strang, G. (2016). *Introduction to Linear Algebra*. Wellesley-Cambridge Press. - Goldberg, D. (1991). "What Every Computer Scientist Should Know About Floating-Point Arithmetic." *ACM Computing Surveys*. -- Intel Corporation. (2023). *Intel 64 and IA-32 Architectures Optimization Reference Manual*. (FMA instruction details) +- Intel Corporation. (2023). *Intel 64 and IA-32 Architectures Optimization Reference Manual*. (FMA instruction details) \ No newline at end of file diff --git a/lib/numerics/lognormdist/Lognormdist.md b/lib/numerics/lognormdist/Lognormdist.md index 9e96fc87..9c8134c6 100644 --- a/lib/numerics/lognormdist/Lognormdist.md +++ b/lib/numerics/lognormdist/Lognormdist.md @@ -13,9 +13,7 @@ | **PineScript** | [lognormdist.pine](lognormdist.pine) | - The Log-Normal Distribution CDF transforms a min-max normalized price into the cumulative distribution function of the log-normal distribution, pro... -- Parameterized by `mu` (default 0.0), `sigma` (default 1.0), `period` (default 14). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Log-normal distribution; models multiplicative processes like returns. Foundation of Black-Scholes. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Log-Normal Distribution CDF transforms a min-max normalized price into the cumulative distribution function of the log-normal distribution, producing an output in $[0, 1]$. A random variable $X$ is log-normally distributed when $\ln(X)$ follows a normal distribution. This makes the log-normal CDF natural for financial data, where multiplicative returns (log-returns) are approximately normally distributed. The indicator min-max normalizes the source to $(0, 1]$, takes the natural logarithm, standardizes by parameters $\mu$ and $\sigma$, then evaluates the standard normal CDF. The result emphasizes values near the bottom of the recent range (where the logarithm diverges) and compresses values near the top. @@ -118,4 +116,4 @@ Limited vectorization — erfc blocks full SIMD. With SVML log: partial vectoriz - Aitchison, J. & Brown, J.A.C. "The Lognormal Distribution." Cambridge University Press, 1957. - Black, F. & Scholes, M. "The Pricing of Options and Corporate Liabilities." Journal of Political Economy, 1973. - Abramowitz, M. & Stegun, I. "Handbook of Mathematical Functions." NBS Applied Mathematics Series 55, 1964. Formula 7.1.26. -- Limpert, E., Stahel, W. & Abbt, M. "Log-normal Distributions across the Sciences: Keys and Clues." BioScience, 2001. +- Limpert, E., Stahel, W. & Abbt, M. "Log-normal Distributions across the Sciences: Keys and Clues." BioScience, 2001. \ No newline at end of file diff --git a/lib/numerics/logtrans/Logtrans.md b/lib/numerics/logtrans/Logtrans.md index 62d0de82..c422c869 100644 --- a/lib/numerics/logtrans/Logtrans.md +++ b/lib/numerics/logtrans/Logtrans.md @@ -14,8 +14,6 @@ - The LOG transformer applies the natural logarithm function $\ln(x)$ to input values. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `0` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The LOG transformer applies the natural logarithm function $\ln(x)$ to input values. This point-wise transformation compresses large values and expands small ones, making it essential for analyzing multiplicative processes like compounded returns. @@ -138,4 +136,4 @@ var logTransform = new Logtrans(priceSource); ## References - Wilmott, P. (2006). "Paul Wilmott on Quantitative Finance." Wiley. -- Hull, J. (2018). "Options, Futures, and Other Derivatives." Pearson. +- Hull, J. (2018). "Options, Futures, and Other Derivatives." Pearson. \ No newline at end of file diff --git a/lib/numerics/lowest/Lowest.md b/lib/numerics/lowest/Lowest.md index 92573df1..6935ab27 100644 --- a/lib/numerics/lowest/Lowest.md +++ b/lib/numerics/lowest/Lowest.md @@ -13,9 +13,7 @@ | **PineScript** | [lowest.pine](lowest.pine) | - LOWEST calculates the minimum value over a rolling lookback window. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Highest](../highest/Highest.md), [MinIndex](../minindex/Minindex.md) | **Trading note:** Rolling minimum; identifies support levels and breakdown points. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. LOWEST calculates the minimum value over a rolling lookback window. This O(1) amortized streaming implementation uses a monotonic deque algorithm, enabling real-time updates without re-scanning the entire window. Validated against TA-Lib MIN and Tulip min functions. @@ -149,4 +147,4 @@ For batch processing, SIMD can parallelize comparisons within segments. However, - Tarjan, Robert E. (1985). "Amortized Computational Complexity." SIAM Journal on Algebraic Discrete Methods. - Lemire, Daniel. (2006). "Streaming Maximum-Minimum Filter Using No More than Three Comparisons per Element." -- TA-Lib: MIN function documentation. +- TA-Lib: MIN function documentation. \ No newline at end of file diff --git a/lib/numerics/maxindex/Maxindex.md b/lib/numerics/maxindex/Maxindex.md index dbb25982..e6b469d1 100644 --- a/lib/numerics/maxindex/Maxindex.md +++ b/lib/numerics/maxindex/Maxindex.md @@ -12,11 +12,9 @@ | **Warmup** | `period` bars | - MAXINDEX finds the position (index) of the maximum value within a rolling lookback window. -- Parameterized by `period` (minimum 2). - Streaming mode outputs bars-ago offset (0 = current bar holds the max, period-1 = oldest bar). - Batch span mode outputs absolute array indices (TA-Lib MAXINDEX compatible). - Tie-breaking: last occurrence wins (most recent bar, `>=` comparison). -- Requires `period` bars of warmup before first valid output (IsHot = true). - Cross-validation: `source[Maxindex.Batch[i]] == Highest.Batch[i]` for all bars after warmup. MAXINDEX identifies the position of the maximum value within a rolling window. While HIGHEST tells you the peak *value*, MAXINDEX tells you *where* that peak is relative to the current bar. This is essential for pattern recognition, timing analysis, and detecting how "stale" a high is. @@ -162,4 +160,4 @@ Streaming uses a linear scan of the RingBuffer, which is O(period) per bar — a - TA-Lib: MAXINDEX function documentation. - Lemire, Daniel. (2006). "Streaming Maximum-Minimum Filter Using No More than Three Comparisons per Element." -- Tarjan, Robert E. (1985). "Amortized Computational Complexity." SIAM Journal on Algebraic Discrete Methods. +- Tarjan, Robert E. (1985). "Amortized Computational Complexity." SIAM Journal on Algebraic Discrete Methods. \ No newline at end of file diff --git a/lib/numerics/minindex/Minindex.md b/lib/numerics/minindex/Minindex.md index 6ac561f2..bd305301 100644 --- a/lib/numerics/minindex/Minindex.md +++ b/lib/numerics/minindex/Minindex.md @@ -12,11 +12,9 @@ | **Warmup** | `period` bars | - MININDEX finds the position (index) of the minimum value within a rolling lookback window. -- Parameterized by `period` (minimum 2). - Streaming mode outputs bars-ago offset (0 = current bar holds the min, period-1 = oldest bar). - Batch span mode outputs absolute array indices (TA-Lib MININDEX compatible). - Tie-breaking: last occurrence wins (most recent bar, `<=` comparison). -- Requires `period` bars of warmup before first valid output (IsHot = true). - Cross-validation: `source[Minindex.Batch[i]] == Lowest.Batch[i]` for all bars after warmup. MININDEX identifies the position of the minimum value within a rolling window. While LOWEST tells you the trough *value*, MININDEX tells you *where* that trough is relative to the current bar. This is essential for support analysis, timing studies, and detecting how "stale" a low is. @@ -162,4 +160,4 @@ Streaming uses a linear scan of the RingBuffer, which is O(period) per bar — a - TA-Lib: MININDEX function documentation. - Lemire, Daniel. (2006). "Streaming Maximum-Minimum Filter Using No More than Three Comparisons per Element." -- Tarjan, Robert E. (1985). "Amortized Computational Complexity." SIAM Journal on Algebraic Discrete Methods. +- Tarjan, Robert E. (1985). "Amortized Computational Complexity." SIAM Journal on Algebraic Discrete Methods. \ No newline at end of file diff --git a/lib/numerics/normalize/Normalize.md b/lib/numerics/normalize/Normalize.md index d3e6f77f..37bb090f 100644 --- a/lib/numerics/normalize/Normalize.md +++ b/lib/numerics/normalize/Normalize.md @@ -13,9 +13,7 @@ | **PineScript** | [normalize.pine](normalize.pine) | - The Normalize transformer applies min-max scaling to map any value series into the bounded range [0, 1] based on the observed minimum and maximum w... -- Parameterized by `period` (default 14). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Min-max normalization to [0,1]; makes indicators comparable across different scales. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Normalize transformer applies min-max scaling to map any value series into the bounded range [0, 1] based on the observed minimum and maximum within a rolling lookback window. This technique is fundamental for feature scaling, creating bounded oscillators, and comparing series with different magnitudes. @@ -231,4 +229,4 @@ Normalize.Calculate(prices, normalized, period: 20); - Aksoy, S., & Haralick, R. M. (2001). "Feature normalization and likelihood-based similarity measures for image retrieval." *Pattern Recognition Letters*. - Patro, S., & Sahu, K. K. (2015). "Normalization: A preprocessing stage." *IARJSET*. -- Géron, A. (2019). *Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow*. O'Reilly Media. +- Géron, A. (2019). *Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow*. O'Reilly Media. \ No newline at end of file diff --git a/lib/numerics/normdist/Normdist.md b/lib/numerics/normdist/Normdist.md index d29d97b5..a00ac247 100644 --- a/lib/numerics/normdist/Normdist.md +++ b/lib/numerics/normdist/Normdist.md @@ -13,9 +13,7 @@ | **PineScript** | [normdist.pine](normdist.pine) | - The Normal Distribution CDF transforms a z-score normalized price into the cumulative distribution function of the Gaussian distribution, producing... -- Parameterized by `mu` (default 0.0), `sigma` (default 1.0), `period` (default 14). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Normal (Gaussian) distribution; foundational for z-scores, confidence intervals, and VaR calculations. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Normal Distribution CDF transforms a z-score normalized price into the cumulative distribution function of the Gaussian distribution, producing an output in $[0, 1]$. Unlike other distribution indicators in this library that use min-max normalization, NORMDIST computes a rolling mean and standard deviation over the lookback window, converting the raw price to a z-score, then applies optional $\mu$ and $\sigma$ parameters for further shaping. The result represents the probability that a standard normal random variable would fall at or below the observed z-score. This makes NORMDIST a direct percentile ranking under the assumption of normally distributed returns, with the output naturally centered at 0.5 when the price is at its rolling mean. @@ -137,4 +135,4 @@ The Horner polynomial evaluation in erfc() is SIMD-vectorizable. Expected 3× ba - Abramowitz, M. & Stegun, I. "Handbook of Mathematical Functions." NBS Applied Mathematics Series 55, 1964. Formulas 7.1.25-7.1.28. - Markowitz, H. "Portfolio Selection." Journal of Finance, 1952. - Johnson, N.L., Kotz, S. & Balakrishnan, N. "Continuous Univariate Distributions, Vol. 1." Wiley, 1994. -- Hart, J.F. et al. "Computer Approximations." Wiley, 1968. +- Hart, J.F. et al. "Computer Approximations." Wiley, 1968. \ No newline at end of file diff --git a/lib/numerics/poissondist/Poissondist.md b/lib/numerics/poissondist/Poissondist.md index 0f5eea67..f96dba7b 100644 --- a/lib/numerics/poissondist/Poissondist.md +++ b/lib/numerics/poissondist/Poissondist.md @@ -13,9 +13,7 @@ | **PineScript** | [poissondist.pine](poissondist.pine) | - The Poisson Distribution CDF computes the probability $P(X \le k)$ for a Poisson random variable whose rate parameter $\lambda$ is derived from the... -- Parameterized by `lambda` (default 1.0), `period` (default 14), `threshold` (default 5). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Poisson distribution; models count of rare events. Trade signal frequency analysis. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Poisson Distribution CDF computes the probability $P(X \le k)$ for a Poisson random variable whose rate parameter $\lambda$ is derived from the min-max normalized price. The Poisson distribution models the number of events in a fixed interval given a constant average rate, making it natural for count-based financial metrics (trade arrivals, tick counts, order flow). The implementation maps normalized price to $\lambda$ via a scale factor, then evaluates the CDF using the identity $P(X \le k) = 1 - P(k+1, \lambda)$ where $P(a, x)$ is the regularized lower incomplete gamma function. This reuses the same Lanczos log-gamma and series/continued-fraction infrastructure as GAMMADIST. @@ -116,4 +114,4 @@ PMF batch: partial SIMD with SVML. CDF must be scalar. For large lambda, Normal - Bortkiewicz, L. "Das Gesetz der kleinen Zahlen." Teubner, 1898. - Merton, R.C. "Option Pricing When Underlying Stock Returns Are Discontinuous." Journal of Financial Economics, 1976. - O'Hara, M. "Market Microstructure Theory." Blackwell, 1995. -- Press, W.H. et al. "Numerical Recipes: The Art of Scientific Computing." 3rd edition, Cambridge University Press, 2007. Chapter 6.2. +- Press, W.H. et al. "Numerical Recipes: The Art of Scientific Computing." 3rd edition, Cambridge University Press, 2007. Chapter 6.2. \ No newline at end of file diff --git a/lib/numerics/relu/Relu.md b/lib/numerics/relu/Relu.md index fdec1475..18bf063e 100644 --- a/lib/numerics/relu/Relu.md +++ b/lib/numerics/relu/Relu.md @@ -14,8 +14,6 @@ - The Rectified Linear Unit (ReLU) activation function applies `max(0, x)` to each value, passing positive inputs unchanged while zeroing negative ones. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `0` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Rectified Linear Unit (ReLU) activation function applies `max(0, x)` to each value, passing positive inputs unchanged while zeroing negative ones. Its simplicity belies its importance: ReLU enabled the training of deep neural networks by mitigating vanishing gradients, and its computational efficiency makes it the default activation for most architectures. @@ -183,4 +181,4 @@ Relu.Calculate(source.AsSpan(), output.AsSpan()); - Nair, V. & Hinton, G. (2010). "Rectified Linear Units Improve Restricted Boltzmann Machines." *ICML*. - Glorot, X., Bordes, A., & Bengio, Y. (2011). "Deep Sparse Rectifier Neural Networks." *AISTATS*. -- Goodfellow, I., Bengio, Y., & Courville, A. (2016). *Deep Learning*. MIT Press. +- Goodfellow, I., Bengio, Y., & Courville, A. (2016). *Deep Learning*. MIT Press. \ No newline at end of file diff --git a/lib/numerics/sigmoid/Sigmoid.md b/lib/numerics/sigmoid/Sigmoid.md index c067c995..86d58740 100644 --- a/lib/numerics/sigmoid/Sigmoid.md +++ b/lib/numerics/sigmoid/Sigmoid.md @@ -13,9 +13,7 @@ | **PineScript** | [sigmoid.pine](sigmoid.pine) | - The Sigmoid (Logistic) transformer maps any real-valued input to the bounded range (0, 1) using the standard logistic function. -- Parameterized by `k` (default 1.0), `x0` (default 0.0). -- Output range: Varies (see docs). -- Requires `0` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Sigmoid function; maps values to (0,1). Used for probability-like scaling of indicator outputs. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Sigmoid (Logistic) transformer maps any real-valued input to the bounded range (0, 1) using the standard logistic function. Its characteristic S-shaped curve makes it indispensable for probability estimation, neural network activations, and any scenario requiring bounded outputs from unbounded inputs. @@ -227,4 +225,4 @@ Sigmoid.Calculate(inputs, outputs, k: 1.0, x0: 0.0); - Verhulst, P.-F. (1838). "Notice sur la loi que la population suit dans son accroissement." *Correspondance Mathématique et Physique*. - Rumelhart, D., Hinton, G., & Williams, R. (1986). "Learning representations by back-propagating errors." *Nature*. -- Bishop, C. (2006). *Pattern Recognition and Machine Learning*. Springer. +- Bishop, C. (2006). *Pattern Recognition and Machine Learning*. Springer. \ No newline at end of file diff --git a/lib/numerics/slope/Slope.md b/lib/numerics/slope/Slope.md index 7f90c287..5aa23431 100644 --- a/lib/numerics/slope/Slope.md +++ b/lib/numerics/slope/Slope.md @@ -14,8 +14,6 @@ - SLOPE measures the instantaneous rate of change—the velocity of a time series. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `2` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. SLOPE measures the instantaneous rate of change—the velocity of a time series. As the first derivative, it answers the fundamental question: how fast is the value changing right now? A positive slope means ascending; negative means descending; zero means flat. This O(1) streaming implementation uses SIMD optimization for batch calculations and handles bar corrections via state rollback. @@ -160,4 +158,4 @@ SLOPE is a fundamental operation. Validation confirms exact match with manual ca ## References - Newton, Isaac. (1687). "Philosophiæ Naturalis Principia Mathematica." -- Numerical Methods: Finite Difference Approximations. +- Numerical Methods: Finite Difference Approximations. \ No newline at end of file diff --git a/lib/numerics/sqrttrans/Sqrttrans.md b/lib/numerics/sqrttrans/Sqrttrans.md index 4819a7eb..141a88a9 100644 --- a/lib/numerics/sqrttrans/Sqrttrans.md +++ b/lib/numerics/sqrttrans/Sqrttrans.md @@ -14,8 +14,6 @@ - The Square Root (SQRT) transformer applies $\sqrt{x}$ to each value in a time series. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `0` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Square Root (SQRT) transformer applies $\sqrt{x}$ to each value in a time series. This variance-stabilizing transformation compresses ranges where volatility scales with magnitude, making it useful for heteroscedastic data where standard deviation increases with price level. @@ -209,4 +207,4 @@ var recovered = Sqrttrans.Calculate(squared); - Box, G.E.P., & Cox, D.R. (1964). "An Analysis of Transformations." *Journal of the Royal Statistical Society, Series B*, 26(2), 211-252. - Tukey, J.W. (1977). *Exploratory Data Analysis*. Addison-Wesley. (Variance-stabilizing transformations) -- IEEE 754-2019. *Standard for Floating-Point Arithmetic*. (sqrt specification) +- IEEE 754-2019. *Standard for Floating-Point Arithmetic*. (sqrt specification) \ No newline at end of file diff --git a/lib/numerics/tdist/Tdist.md b/lib/numerics/tdist/Tdist.md index 204aaa83..fa1b2ae2 100644 --- a/lib/numerics/tdist/Tdist.md +++ b/lib/numerics/tdist/Tdist.md @@ -13,9 +13,7 @@ | **PineScript** | [tdist.pine](tdist.pine) | - The Student's t-Distribution CDF transforms a min-max normalized price into the cumulative distribution function of Student's t-distribution, produ... -- Parameterized by `nu` (default 10), `period` (default 14). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Student's t-distribution; used for hypothesis testing with small samples. Fatter tails than normal. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Student's t-Distribution CDF transforms a min-max normalized price into the cumulative distribution function of Student's t-distribution, producing an output in $[0, 1]$. The t-distribution is the normal distribution's heavier-tailed cousin: as degrees of freedom $\nu$ increase, it converges to the Gaussian; at low $\nu$ it accommodates extreme values that the normal distribution would assign negligible probability. The implementation normalizes price to $[0, 1]$, maps to a t-statistic via linear scaling to $[-3, +3]$, then evaluates the CDF through the regularized incomplete beta function. This makes TDIST a robust percentile ranking that is less sensitive to outliers than NORMDIST. @@ -129,4 +127,4 @@ Dominated by sequential CF solver. Outer loop PLINQ for bulk p-value computation - Mandelbrot, B. "The Variation of Certain Speculative Prices." Journal of Business, 1963. - Fama, E.F. "The Behavior of Stock-Market Prices." Journal of Business, 1965. - Bollerslev, T. "Generalized Autoregressive Conditional Heteroskedasticity." Journal of Econometrics, 1986. -- Press, W.H. et al. "Numerical Recipes: The Art of Scientific Computing." 3rd edition, Cambridge University Press, 2007. Chapter 6.4. +- Press, W.H. et al. "Numerical Recipes: The Art of Scientific Computing." 3rd edition, Cambridge University Press, 2007. Chapter 6.4. \ No newline at end of file diff --git a/lib/numerics/weibulldist/Weibulldist.md b/lib/numerics/weibulldist/Weibulldist.md index 4e8ec5d7..e3764b31 100644 --- a/lib/numerics/weibulldist/Weibulldist.md +++ b/lib/numerics/weibulldist/Weibulldist.md @@ -13,9 +13,7 @@ | **PineScript** | [weibulldist.pine](weibulldist.pine) | - The Weibull Distribution CDF transforms a min-max normalized price into the cumulative distribution function of the Weibull distribution, producing... -- Parameterized by `k` (default 1.5), `lambda` (default 1.0), `period` (default 14). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Weibull distribution; flexible lifetime/reliability model. Used for drawdown duration analysis. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Weibull Distribution CDF transforms a min-max normalized price into the cumulative distribution function of the Weibull distribution, producing an output in $[0, 1]$. The Weibull distribution is a flexible two-parameter family that subsumes the exponential distribution ($k = 1$) and approximates the normal distribution ($k \approx 3.6$) as special cases. Its closed-form CDF requires only `pow` and `exp`, making it the computationally cheapest distribution indicator after EXPDIST. The shape parameter $k$ controls the CDF curvature: $k < 1$ produces a concave curve (rapid initial rise), $k = 1$ gives the exponential, $k = 2$ produces the Rayleigh distribution, and $k > 3$ creates an S-shaped curve approaching Gaussian behavior. @@ -130,4 +128,4 @@ With SVML: nearly full vectorization. Without SVML: scalar loop but trivially pa - Frechet, M. "Sur la loi de probabilite de l'ecart maximum." Ann. Soc. Polon. Math., 1927. - Rinne, H. "The Weibull Distribution: A Handbook." CRC Press, 2009. - Abernethy, R.B. "The New Weibull Handbook." 5th edition, 2006. -- Johnson, N.L., Kotz, S. & Balakrishnan, N. "Continuous Univariate Distributions, Vol. 1." Wiley, 1994. +- Johnson, N.L., Kotz, S. & Balakrishnan, N. "Continuous Univariate Distributions, Vol. 1." Wiley, 1994. \ No newline at end of file diff --git a/lib/oscillators/bbi/Bbi.md b/lib/oscillators/bbi/Bbi.md index 8b1b111e..b144f954 100644 --- a/lib/oscillators/bbi/Bbi.md +++ b/lib/oscillators/bbi/Bbi.md @@ -13,9 +13,7 @@ | **PineScript** | [bbi.pine](bbi.pine) | - BBI (Bulls Bears Index) computes the arithmetic mean of four Simple Moving Averages with geometrically spaced periods (3, 6, 12, 24 by default). -- Parameterized by `p1` (default defaultp1), `p2` (default defaultp2), `p3` (default defaultp3), `p4` (default defaultp4). -- Output range: Varies (see docs). -- Requires `Math.Max(Math.Max(p1, p2), Math.Max(p3, p4))` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BBB](../bbb/Bbb.md), [BBS](../bbs/Bbs.md) | **Complementary:** RSI for overbought/oversold | **Trading note:** Bollinger Band %B indicator; position within bands. >1 = above upper, <0 = below lower. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. BBI (Bulls Bears Index) computes the arithmetic mean of four Simple Moving Averages with geometrically spaced periods (3, 6, 12, 24 by default). The result is a price-overlay line that captures trend consensus across ultra-short, short, medium, and long timeframes simultaneously. Price above BBI signals bullish dominance; price below BBI signals bearish control. The crossover point marks the regime boundary between long and short markets. @@ -147,4 +145,4 @@ Fully SIMD-vectorizable. AVX2 achieves ~4× throughput for large arrays. - TradingView. "BBI - Bull and Bear Index." Community Scripts. (Standard implementation reference.) - Chinese Securities Association. Technical analysis indicator specifications. (Origin of 3/6/12/24 period convention.) -- Binance Square. "BBI Indicator Usage Tutorial." (Modern application to cryptocurrency markets.) +- Binance Square. "BBI Indicator Usage Tutorial." (Modern application to cryptocurrency markets.) \ No newline at end of file diff --git a/lib/oscillators/brar/Brar.md b/lib/oscillators/brar/Brar.md index 305ecc29..3dc37c10 100644 --- a/lib/oscillators/brar/Brar.md +++ b/lib/oscillators/brar/Brar.md @@ -13,9 +13,7 @@ | **PineScript** | [brar.pine](brar.pine) | - BRAR is a dual-output sentiment oscillator from the Japanese technical analysis tradition that decomposes market pressure into two independent rati... -- Parameterized by `period` (default 26). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ERI](../eri/Eri.md), [FI](../fi/Fi.md) | **Complementary:** Volume | **Trading note:** BRAR (Buying/Selling Power); AR measures opening vs H/L, BR measures close vs H/L. Popular in Asian markets. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. BRAR is a dual-output sentiment oscillator from the Japanese technical analysis tradition that decomposes market pressure into two independent ratios: BR (Buying Ratio), which measures upside thrust relative to the previous close, and AR (Atmosphere Ratio), which measures intraday range asymmetry relative to the open. Both outputs oscillate around an equilibrium of 100, where values above 100 signal dominance of the measured pressure and values below 100 signal weakness. The default lookback of 26 bars (one Japanese trading month) produces stable readings with 4 additions per bar in streaming mode. @@ -190,4 +188,4 @@ Validation strategy: generate synthetic OHLC data via GBM, compute BRAR through - Nison, Steve. (1991). *Japanese Candlestick Charting Techniques*. New York Institute of Finance. - Nison, Steve. (1994). *Beyond Candlesticks: New Japanese Charting Techniques Revealed*. John Wiley and Sons. - Morris, Gregory L. (2006). *Candlestick Charting Explained*. 3rd Edition. McGraw-Hill. -- Taiwan Stock Exchange Technical Analysis Committee. (2003). *Technical Analysis Reference Manual* (技術分析參考手冊). TWSE Publications. +- Taiwan Stock Exchange Technical Analysis Committee. (2003). *Technical Analysis Reference Manual* (技術分析參考手冊). TWSE Publications. \ No newline at end of file diff --git a/lib/oscillators/coppock/Coppock.md b/lib/oscillators/coppock/Coppock.md index d2b28c3d..6efa1349 100644 --- a/lib/oscillators/coppock/Coppock.md +++ b/lib/oscillators/coppock/Coppock.md @@ -13,9 +13,7 @@ | **PineScript** | [coppock.pine](coppock.pine) | - The Coppock Curve is a long-term momentum oscillator that applies a Weighted Moving Average to the sum of two Rate of Change calculations at differ... -- Parameterized by `longRoc` (default 14), `shortRoc` (default 11), `wmaPeriod` (default 10). -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [MACD](../../momentum/macd/Macd.md), [KST](../kst/Kst.md) | **Complementary:** Trend confirmation | **Trading note:** Coppock Curve; designed for monthly S&P 500 buy signals. WMA of summed ROCs. Zero-line crossover. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Coppock Curve is a long-term momentum oscillator that applies a Weighted Moving Average to the sum of two Rate of Change calculations at different lookback periods. Originally designed for monthly charts to identify major market bottoms, it produces a single oscillating line where zero-line crossovers from below signal long-term buying opportunities. The dual-ROC architecture captures both intermediate and longer-term momentum dynamics in a single smoothed output. @@ -109,4 +107,4 @@ Both ROC and WMA are non-recursive and fully vectorizable. AVX2 dot-product acce - Coppock, E.S.C. (1962). "A Guide to the Use of Coppock Curve." *Barron's* - Kirkpatrick, C. & Dahlquist, J. (2010). *Technical Analysis*, Chapter 15: Momentum -- PineScript reference: [`coppock.pine`](coppock.pine) +- PineScript reference: [`coppock.pine`](coppock.pine) \ No newline at end of file diff --git a/lib/oscillators/crsi/Crsi.md b/lib/oscillators/crsi/Crsi.md index 98739f76..d7321104 100644 --- a/lib/oscillators/crsi/Crsi.md +++ b/lib/oscillators/crsi/Crsi.md @@ -13,9 +13,7 @@ | **PineScript** | [crsi.pine](crsi.pine) | - Connors RSI is a composite momentum oscillator that combines three independent measurements of price behavior into a single bounded (0-100) output:... -- Parameterized by `rsiperiod` (default 3), `streakperiod` (default 2), `rankperiod` (default 100). -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [RSI](../../momentum/rsi/Rsi.md), [StochRSI](../stochrsi/Stochrsi.md) | **Complementary:** Volume | **Trading note:** Connors RSI; combines RSI, streak RSI, and percentile rank. Short-term mean-reversion signal. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Connors RSI is a composite momentum oscillator that combines three independent measurements of price behavior into a single bounded (0-100) output: a short-term RSI of price, an RSI of the consecutive up/down streak length, and a percentile rank of the current rate of change within its recent history. The equal-weighted average of these three components produces a mean-reverting oscillator where extreme readings (above 90 or below 10) identify statistically overbought or oversold conditions with higher reliability than single-component RSI alone. @@ -114,4 +112,4 @@ PercentRank scan is the only sub-step with meaningful SIMD acceleration potentia - Connors, L. & Alvarez, C. (2012). *An Introduction to ConnorsRSI*. TradingMarkets - Connors, L. (2009). *Short-Term Trading Strategies That Work*. TradingMarkets -- PineScript reference: [`crsi.pine`](crsi.pine) +- PineScript reference: [`crsi.pine`](crsi.pine) \ No newline at end of file diff --git a/lib/oscillators/cti/Cti.md b/lib/oscillators/cti/Cti.md index 783f52da..0dd37178 100644 --- a/lib/oscillators/cti/Cti.md +++ b/lib/oscillators/cti/Cti.md @@ -13,9 +13,7 @@ | **PineScript** | [cti.pine](cti.pine) | - The Correlation Trend Indicator computes the Pearson correlation coefficient between the price series and a linear time index over a rolling window... -- Parameterized by `period` (default 20). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [LinReg](../../statistics/linreg/LinReg.md), [CFO](../cfo/Cfo.md) | **Complementary:** ADX | **Trading note:** Correlation Trend Indicator; Pearson correlation of price vs time. +1 = perfect uptrend, −1 = downtrend. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Correlation Trend Indicator computes the Pearson correlation coefficient between the price series and a linear time index over a rolling window, producing a bounded oscillator in the range $[-1, +1]$. Values near $+1$ indicate a strong linear uptrend, values near $-1$ indicate a strong linear downtrend, and values near zero indicate no linear trend relationship. The implementation achieves O(1) complexity per bar through incremental running sums that avoid recomputing the full correlation on each update. @@ -110,4 +108,4 @@ Fully vectorizable in batch mode. Prefix-sum trick converts O(N²) naive to O(N) - Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley - Pearson, K. (1895). "Notes on Regression and Inheritance in the Case of Two Parents." *Proceedings of the Royal Society of London* -- PineScript reference: [`cti.pine`](cti.pine) +- PineScript reference: [`cti.pine`](cti.pine) \ No newline at end of file diff --git a/lib/oscillators/deco/Deco.md b/lib/oscillators/deco/Deco.md index 9acbd067..349d52e2 100644 --- a/lib/oscillators/deco/Deco.md +++ b/lib/oscillators/deco/Deco.md @@ -13,9 +13,7 @@ | **PineScript** | [deco.pine](deco.pine) | - The Decycler Oscillator (DECO) is a DSP-based oscillator developed by John F. -- Parameterized by `shortperiod` (default 30), `longperiod` (default 60). -- Output range: $0$ to $1$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [DPO](../dpo/Dpo.md), [Reflex](../reflex/Reflex.md) | **Complementary:** Cycle analysis | **Trading note:** Ehlers' Decycler Oscillator; removes trend to isolate cycle component for timing. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Overview @@ -135,4 +133,4 @@ Fully vectorizable in batch. Regression and correlation both benefit from AVX2 V ## References 1. Ehlers, J. F. (2015). "Decyclers." *Technical Analysis of Stocks & Commodities*, September 2015. -2. Ehlers, J. F. (2013). *Cycle Analytics for Traders*. Wiley. Chapter 4. +2. Ehlers, J. F. (2013). *Cycle Analytics for Traders*. Wiley. Chapter 4. \ No newline at end of file diff --git a/lib/oscillators/dem/Dem.md b/lib/oscillators/dem/Dem.md index 80a953b1..51ca18af 100644 --- a/lib/oscillators/dem/Dem.md +++ b/lib/oscillators/dem/Dem.md @@ -13,9 +13,7 @@ | **PineScript** | [dem.pine](dem.pine) | - DEM (DeMarker Oscillator) is a bounded [0, 1] momentum oscillator that measures sequential demand pressure by comparing each bar's high and low aga... -- Parameterized by `period` (default 14). -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MACD](../../momentum/macd/Macd.md), [AO](../ao/Ao.md) | **Complementary:** Volume | **Trading note:** DeMarker; compares current high/low to previous. Overbought >0.7, oversold <0.3. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. DEM (DeMarker Oscillator) is a bounded [0, 1] momentum oscillator that measures sequential demand pressure by comparing each bar's high and low against the previous bar's high and low. It isolates bullish demand momentum in the numerator and bearish supply pressure in the denominator, then normalizes their ratio with SMA smoothing over a configurable period. Values near 0.7 signal overbought exhaustion; values near 0.3 signal oversold exhaustion. Neither external library in common use (TA-Lib, Skender, Tulip, Ooples) implements DeMarker, so self-consistency tests against batch/streaming/span modes serve as the primary validation. @@ -206,4 +204,4 @@ Validation relies on self-consistency checks: - DeMark, Tom (1994). *The New Science of Technical Analysis*. John Wiley & Sons. ISBN 0-471-03548-3. - DeMark, Tom (1997). *New Market Timing Techniques*. John Wiley & Sons. ISBN 0-471-14970-5. - Colby, Robert W. (2003). *The Encyclopedia of Technical Market Indicators* (2nd ed.). McGraw-Hill. Entry: "DeMark Indicators." -- Pring, Martin J. (2002). *Technical Analysis Explained* (4th ed.). McGraw-Hill. Chapter on oscillator construction methodology. +- Pring, Martin J. (2002). *Technical Analysis Explained* (4th ed.). McGraw-Hill. Chapter on oscillator construction methodology. \ No newline at end of file diff --git a/lib/oscillators/dosc/Dosc.md b/lib/oscillators/dosc/Dosc.md index 6edfc156..b835d8bc 100644 --- a/lib/oscillators/dosc/Dosc.md +++ b/lib/oscillators/dosc/Dosc.md @@ -13,9 +13,7 @@ | **PineScript** | [dosc.pine](dosc.pine) | - The Derivative Oscillator applies a four-stage signal processing pipeline to extract momentum inflection points: RSI via Wilder's smoothing, double... -- Parameterized by `rsiperiod` (default 14), `ema1period` (default 5), `ema2period` (default 3), `sigperiod` (default 9). -- Output range: Varies (see docs). -- Requires `rsiPeriod + sigPeriod` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MACD](../../momentum/macd/Macd.md), [PPO](../../momentum/ppo/Ppo.md) | **Complementary:** Volume | **Trading note:** Derivative Oscillator; RSI smoothed with EMA, then differenced. Catches RSI turning points early. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Derivative Oscillator applies a four-stage signal processing pipeline to extract momentum inflection points: RSI via Wilder's smoothing, double EMA smoothing of the RSI, an SMA signal line of the double-smoothed result, and finally the difference between the smoothed RSI and its signal. The histogram output crosses zero at momentum turning points, offering earlier signals than raw RSI by isolating the rate of change of the smoothed momentum rather than the momentum level itself. @@ -108,4 +106,4 @@ Fully SIMD-vectorizable. AVX2 achieves near-4× throughput. - Brown, C. (1994). *Technical Analysis for the Trading Professional*. McGraw-Hill - Brown, C. (1999). *Technical Analysis for the Trading Professional*, 2nd ed. McGraw-Hill -- PineScript reference: [`dosc.pine`](dosc.pine) +- PineScript reference: [`dosc.pine`](dosc.pine) \ No newline at end of file diff --git a/lib/oscillators/dymoi/Dymoi.md b/lib/oscillators/dymoi/Dymoi.md index a2202324..c4d82858 100644 --- a/lib/oscillators/dymoi/Dymoi.md +++ b/lib/oscillators/dymoi/Dymoi.md @@ -13,9 +13,7 @@ | **PineScript** | [dymoi.pine](dymoi.pine) | - DYMOI is a volatility-adaptive RSI: when recent price swings are large relative to longer-term swings, the RSI period shortens and the indicator be... -- Parameterized by `baseperiod` (default 14), `shortperiod` (default 5), `longperiod` (default 10), `minperiod` (default 3), `maxperiod` (default 30). -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [RSI](../../momentum/rsi/Rsi.md), [Stoch](../stoch/Stoch.md) | **Complementary:** ATR | **Trading note:** Dynamic Momentum Index; RSI with variable lookback based on volatility. Faster in calm, slower in volatile markets. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. DYMOI is a volatility-adaptive RSI: when recent price swings are large relative to longer-term swings, the RSI period shortens and the indicator becomes more responsive; when price action tightens, the period extends and the output smooths. The result is an oscillator that self-adjusts its sensitivity to the market's current state, avoiding both the lag of long fixed-period RSIs in trending regimes and the noise of short-period RSIs in ranging ones. @@ -217,4 +215,4 @@ No external C# library (Skender, TA-Lib, Tulip, Ooples) implements DYMOI. Valida - Chande, T. & Kroll, S. (1994). *The New Technical Trader*. John Wiley & Sons. Ch. 3: Dynamic Momentum Index. - Wilder, J.W. (1978). *New Concepts in Technical Trading Systems*. Trend Research. (RSI original source) -- Connors, L. & Alvarez, C. (2012). *An Introduction to ConnorsRSI*. TradingMarkets. (CRSI comparison reference) +- Connors, L. & Alvarez, C. (2012). *An Introduction to ConnorsRSI*. TradingMarkets. (CRSI comparison reference) \ No newline at end of file diff --git a/lib/oscillators/gator/Gator.md b/lib/oscillators/gator/Gator.md index 7cd4f09d..3fc9e1ea 100644 --- a/lib/oscillators/gator/Gator.md +++ b/lib/oscillators/gator/Gator.md @@ -13,9 +13,7 @@ | **PineScript** | [gator.pine](gator.pine) | - The Williams Gator Oscillator is a dual-histogram visualization of the Alligator indicator's convergence and divergence. -- Parameterized by `jawperiod` (default 13), `jawshift` (default 8), `teethperiod` (default 8), `teethshift` (default 5), `lipsperiod` (default 5), `lipsshift` (default 3). -- Output range: Varies (see docs). -- Requires `Math.Max(jawPeriod + jawShift, Math.Max(teethPeriod + teethShift, lipsPeriod + lipsShift))` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Alligator](../../dynamics/alligator/Alligator.md), [AO](../ao/Ao.md) | **Complementary:** Fractal indicator | **Trading note:** Bill Williams' Gator Oscillator; visualizes Alligator's jaw/teeth/lips convergence as histogram. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Williams Gator Oscillator is a dual-histogram visualization of the Alligator indicator's convergence and divergence. It strips the Alligator's three SMMA lines down to two absolute differences: upper (Jaw minus Teeth) and lower (negative of Teeth minus Lips). The result is a zero-centered oscillator where expanding bars signal trend acceleration and contracting bars signal trend exhaustion. Because it operates on pre-computed SMMA values, the Gator adds zero computational overhead beyond two subtractions, two absolute values, and one sign flip per bar. @@ -217,4 +215,4 @@ Key validation points: - Williams, Bill. *Trading Chaos: Maximize Profits with Proven Technical Techniques.* John Wiley & Sons, 1995. - Williams, Bill. *New Trading Dimensions: How to Profit from Chaos in Stocks, Bonds, and Commodities.* John Wiley & Sons, 1998. - MetaQuotes Software. "Gator Oscillator." *MQL5 Reference.* [mql5.com/en/docs/indicators/igator](https://www.mql5.com/en/docs/indicators/igator) -- PineScript reference: `gator.pine` in indicator directory. +- PineScript reference: `gator.pine` in indicator directory. \ No newline at end of file diff --git a/lib/oscillators/imi/Imi.md b/lib/oscillators/imi/Imi.md index 84a0b864..3368f5c8 100644 --- a/lib/oscillators/imi/Imi.md +++ b/lib/oscillators/imi/Imi.md @@ -13,9 +13,7 @@ | **PineScript** | [imi.pine](imi.pine) | - The Intraday Momentum Index measures buying and selling pressure using the open-to-close relationship within each bar, rather than the close-to-clo... -- Parameterized by `period` (default 14). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [RSI](../../momentum/rsi/Rsi.md), [MFI](../../volume/mfi/Mfi.md) | **Complementary:** Volume | **Trading note:** Intraday Momentum Index; RSI variant using open-close relationship. Measures intrabar conviction. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Intraday Momentum Index measures buying and selling pressure using the open-to-close relationship within each bar, rather than the close-to-close changes used by RSI. Each bar is classified as a gain (close > open) or loss (close < open), with the magnitude being the absolute open-close difference. Rolling sums of gains and losses over the lookback period produce an RSI-like ratio scaled to 0-100. This bridges Japanese candlestick analysis with Western oscillator theory: bullish candles contribute to the gain sum, bearish candles contribute to the loss sum. Unlike RSI, IMI does not require a previous close and uses simple rolling sums rather than exponential smoothing, making it more responsive but noisier. Output is bounded 0-100 with conventional overbought (>70) and oversold (<30) zones. @@ -136,4 +134,4 @@ The conditional accumulation (masked add for up bodies) is SIMD-friendly with AV ## Resources - Chande, T.S. & Kroll, S. — *The New Technical Trader* (John Wiley & Sons, 1994) -- PineScript reference: `imi.pine` in indicator directory +- PineScript reference: `imi.pine` in indicator directory \ No newline at end of file diff --git a/lib/oscillators/kst/Kst.md b/lib/oscillators/kst/Kst.md index d4f58c80..74376d31 100644 --- a/lib/oscillators/kst/Kst.md +++ b/lib/oscillators/kst/Kst.md @@ -15,9 +15,6 @@ + sigPeriod - 2` bars | - The Know Sure Thing is a multi-timeframe momentum oscillator that computes four Rate of Change values at progressively longer lookback periods, smo... -- Parameterized by `r1` (default 10), `r2` (default 15), `r3` (default 20), `r4` (default 30), `s1` (default 10), `s2` (default 10), `s3` (default 10), `s4` (default 15), `sigPeriod` (default 9). -- Output range: Varies (see docs). -- Requires `Math.Max(Math.Max(r1, r2), Math.Max(r3, r4)) + Math.Max(Math.Max(s1, s2), Math.Max(s3, s4)) + sigPeriod - 2` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. @@ -116,4 +113,4 @@ Fully vectorizable in batch mode — no recursive dependencies. AVX2 achieves ~4 - Pring, M.J. (1992). "The KST System." *Technical Analysis of Stocks & Commodities* - Pring, M.J. (2002). *Technical Analysis Explained*, 4th ed. McGraw-Hill -- PineScript reference: [`kst.pine`](kst.pine) +- PineScript reference: [`kst.pine`](kst.pine) \ No newline at end of file diff --git a/lib/oscillators/lrsi/Lrsi.md b/lib/oscillators/lrsi/Lrsi.md index a67406f4..b681cad4 100644 --- a/lib/oscillators/lrsi/Lrsi.md +++ b/lib/oscillators/lrsi/Lrsi.md @@ -13,9 +13,7 @@ | **PineScript** | [lrsi.pine](lrsi.pine) | - Laguerre RSI is an adaptive oscillator invented by John Ehlers that replaces standard RSI's Wilder-smoothed gain/loss averages with a 4-stage casca... -- Parameterized by `gamma` (default 0.5). -- Output range: Varies (see docs). -- Requires `4` bars of warmup before first valid output (IsHot = true). +- **Similar:** [RSI](../../momentum/rsi/Rsi.md), [Fisher](../fisher/Fisher.md) | **Complementary:** Volume | **Trading note:** Laguerre RSI by Ehlers; applies Laguerre filter to RSI calculation. Faster response, fewer whipsaws. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Laguerre RSI is an adaptive oscillator invented by John Ehlers that replaces standard RSI's Wilder-smoothed gain/loss averages with a 4-stage cascaded Laguerre filter. A single γ (gamma) parameter controls the entire responsiveness-smoothness trade-off. Output is dimensionless, always in [0, 1]. No period selection required. @@ -168,4 +166,4 @@ No external C# library implements Laguerre RSI. Validation protocol: - Ehlers, J.F. (2004). *Cybernetic Analysis for Stocks and Futures*. Wiley. Chapter 14. - Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley. Chapter 9 (Laguerre filter foundations). -- Vaidyanathan, P.P. (1993). *Multirate Systems and Filter Banks*. Prentice Hall. (All-pass lattice structures.) +- Vaidyanathan, P.P. (1993). *Multirate Systems and Filter Banks*. Prentice Hall. (All-pass lattice structures.) \ No newline at end of file diff --git a/lib/oscillators/marketfi/Marketfi.md b/lib/oscillators/marketfi/Marketfi.md index a0fa4f50..b3b1753b 100644 --- a/lib/oscillators/marketfi/Marketfi.md +++ b/lib/oscillators/marketfi/Marketfi.md @@ -14,8 +14,6 @@ - The Market Facilitation Index answers a single question with arithmetic directness: how much price moved per unit of volume traded? - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `> 1` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Market Facilitation Index answers a single question with arithmetic directness: how much price moved per unit of volume traded? One division. No lookback period. No smoothing. No parameter to debate. What you get is raw market efficiency — the price range a market delivers for each unit of liquidity consumed. @@ -159,4 +157,4 @@ No external library (TA-Lib, Skender.Stock.Indicators, Tulip, OoplesFinance) imp - Williams, Bill (1995). *Trading Chaos: Applying Expert Techniques to Maximize Your Profits.* Wiley. - Williams, Bill and Justine Gregory-Williams (2004). *Trading Chaos: Maximize Profits with Proven Technical Techniques* (2nd ed.). Wiley. - Kyle, Albert S. (1985). "Continuous Auctions and Insider Trading." *Econometrica*, 53(6), 1315–1335. -- Amihud, Yakov (2002). "Illiquidity and stock returns: cross-section and time-series effects." *Journal of Financial Markets*, 5(1), 31–56. +- Amihud, Yakov (2002). "Illiquidity and stock returns: cross-section and time-series effects." *Journal of Financial Markets*, 5(1), 31–56. \ No newline at end of file diff --git a/lib/oscillators/mstoch/Mstoch.md b/lib/oscillators/mstoch/Mstoch.md index 81c187ee..6f8ef620 100644 --- a/lib/oscillators/mstoch/Mstoch.md +++ b/lib/oscillators/mstoch/Mstoch.md @@ -13,9 +13,7 @@ | **PineScript** | [mstoch.pine](mstoch.pine) | - The MESA Stochastic applies John Ehlers' Roofing Filter as a preprocessing stage before computing a stochastic oscillator, then smooths the stochas... -- Parameterized by `stochlength` (default 20), `hplength` (default 48), `sslength` (default 10). -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [Stoch](../stoch/Stoch.md), [KDJ](../kdj/Kdj.md) | **Complementary:** MACD | **Trading note:** Modified Stochastic; enhanced stochastic oscillator with additional smoothing or lookback variation. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The MESA Stochastic applies John Ehlers' Roofing Filter as a preprocessing stage before computing a stochastic oscillator, then smooths the stochastic output with a Super Smoother. The Roofing Filter removes both low-frequency trend components (via highpass) and high-frequency noise (via Super Smoother), isolating the dominant cycle. The stochastic calculation on this filtered data produces a clean 0-to-1 oscillator that responds to cycle turning points rather than trend or noise, with substantially reduced whipsaw compared to conventional stochastic indicators. @@ -113,4 +111,4 @@ EMA smoothing blocks full vectorization; window extrema and division are SIMD-fr - Ehlers, J.F. (2013). *Cycle Analytics for Traders*. Wiley, Chapter 6 - Ehlers, J.F. (2004). *Cybernetic Analysis for Stocks and Futures*. Wiley -- PineScript reference: [`mstoch.pine`](mstoch.pine) +- PineScript reference: [`mstoch.pine`](mstoch.pine) \ No newline at end of file diff --git a/lib/oscillators/qqe/Qqe.md b/lib/oscillators/qqe/Qqe.md index 9975cde7..a5029499 100644 --- a/lib/oscillators/qqe/Qqe.md +++ b/lib/oscillators/qqe/Qqe.md @@ -13,9 +13,7 @@ | **PineScript** | [qqe.pine](qqe.pine) | - Quantitative Qualitative Estimation applies a multi-stage smoothing pipeline to RSI and then constructs dynamic volatility-based trailing bands aro... -- Parameterized by `rsiPeriod` (default 14), `smoothFactor` (default 5), `qqeFactor` (default 4.236). -- Output range: Varies (see docs). -- Requires `rsiPeriod + smoothFactor + darPeriod * 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [RSI](../../momentum/rsi/Rsi.md), [StochRSI](../stochrsi/Stochrsi.md) | **Complementary:** ATR | **Trading note:** Quantitative Qualitative Estimation; smoothed RSI with dynamic trailing levels. Reduces false signals. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Quantitative Qualitative Estimation applies a multi-stage smoothing pipeline to RSI and then constructs dynamic volatility-based trailing bands around the smoothed result. The output is a dual-line system: the QQE line (smoothed RSI) and a trailing level that follows price directionally, similar to Parabolic SAR logic. Crossovers between the QQE line and its trailing level signal momentum shifts, while crossovers of the QQE line above and below 50 indicate trend direction. The trailing level adapts to volatility through a double-EMA of RSI absolute changes, making band width contract in quiet markets and expand during volatile conditions. @@ -120,4 +118,4 @@ Recursive EMA chains and ratchet state block vectorization. Band arithmetic is v - Wilder, J.W. (1978). *New Concepts in Technical Trading Systems*. Trend Research (RSI foundation) - MetaTrader community documentation on QQE implementation -- PineScript reference: [`qqe.pine`](qqe.pine) +- PineScript reference: [`qqe.pine`](qqe.pine) \ No newline at end of file diff --git a/lib/oscillators/reflex/Reflex.md b/lib/oscillators/reflex/Reflex.md index c0276fbd..87c9bfa3 100644 --- a/lib/oscillators/reflex/Reflex.md +++ b/lib/oscillators/reflex/Reflex.md @@ -13,9 +13,7 @@ | **PineScript** | [reflex.pine](reflex.pine) | - REFLEX is a zero-lag oscillator that measures the reversal tendency of price by comparing a Super-Smoother-filtered price against a linear extrapol... -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Trendflex](../trendflex/Trendflex.md), [Deco](../deco/Deco.md) | **Complementary:** Cycle indicators | **Trading note:** Ehlers' Reflex indicator; cycle-mode oscillator using Super Smoother. Leading turns at zero crossings. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. REFLEX is a zero-lag oscillator that measures the reversal tendency of price by comparing a Super-Smoother-filtered price against a linear extrapolation from $N$ bars ago. The filter computes the slope of the filtered series over the lookback window, projects a straight line, and sums the deviations of the actual filtered values from this projected line. The sum is normalized by an exponential RMS estimate to produce values in roughly $\pm \sigma$ scale. Values above 0 indicate uptrend, below 0 indicate downtrend; crossovers signal potential reversals. @@ -152,4 +150,4 @@ IIR dependencies block bar-parallel SIMD; RMS computation in batch is vectorizab ## Resources - Ehlers, J.F. (2020). "Reflex: A New Zero-Lag Indicator." *Technical Analysis of Stocks & Commodities*, February 2020. -- Ehlers, J.F. (2013). *Cycle Analytics for Traders*. Wiley. Chapter 3: Super Smoothers. +- Ehlers, J.F. (2013). *Cycle Analytics for Traders*. Wiley. Chapter 3: Super Smoothers. \ No newline at end of file diff --git a/lib/oscillators/reverseema/ReverseEma.md b/lib/oscillators/reverseema/ReverseEma.md index 2a783b59..00d7d6ff 100644 --- a/lib/oscillators/reverseema/ReverseEma.md +++ b/lib/oscillators/reverseema/ReverseEma.md @@ -13,9 +13,7 @@ | **PineScript** | [reverseema.pine](reverseema.pine) | - The Reverse EMA applies an 8-stage cascaded Z-transform inversion to a compensated EMA, progressively extracting and subtracting the accumulated la... -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [EMA](../../trends_IIR/ema/ema.md), [Zlema](../../trends_IIR/zlema/zlema.md) | **Complementary:** StdDev | **Trading note:** Reverse-engineers price from EMA; finds the price that would produce a given EMA value. Useful for target levels. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -186,4 +184,4 @@ Self-consistency validation: Streaming, Batch (TSeries), and Span Batch modes pr - Ehlers, J. F. (2017). "Reverse EMA." Technical analysis signal processing concepts. - Ehlers, J. F. (2004). *Cybernetic Analysis for Stocks and Futures*. Wiley. -- Ehlers, J. F. (2001). *Rocket Science for Traders*. Wiley. +- Ehlers, J. F. (2001). *Rocket Science for Traders*. Wiley. \ No newline at end of file diff --git a/lib/oscillators/rvgi/Rvgi.md b/lib/oscillators/rvgi/Rvgi.md index c08781c1..a6106dbc 100644 --- a/lib/oscillators/rvgi/Rvgi.md +++ b/lib/oscillators/rvgi/Rvgi.md @@ -13,9 +13,7 @@ | **PineScript** | [rvgi.pine](rvgi.pine) | - The Relative Vigor Index measures the conviction of a price move by comparing closing strength (close minus open) to the total intrabar range (high... -- Parameterized by `period` (default 10). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [AO](../ao/Ao.md), [Fisher](../fisher/Fisher.md) | **Complementary:** Volume | **Trading note:** Relative Vigor Index; compares close−open to high−low. Rising = bullish vigor. Signal-line crossovers. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Relative Vigor Index measures the conviction of a price move by comparing closing strength (close minus open) to the total intrabar range (high minus low), smoothed through a symmetrically weighted moving average and then averaged over a lookback period. The premise is that in bullish markets, closes tend to occur near highs and opens near lows, producing positive RVGI values, while bearish markets show the opposite pattern. A 4-bar SWMA signal line provides crossover triggers. The indicator oscillates around zero with no fixed bounds. @@ -111,4 +109,4 @@ Fully vectorizable — no recursive dependencies. AVX2 achieves ~4× throughput. - Ehlers, J.F. (2002). *Rocket Science for Traders*. Wiley, Chapter 12 - Ehlers, J.F. (2001). "The Relative Vigor Index." *Technical Analysis of Stocks & Commodities* -- PineScript reference: [`rvgi.pine`](rvgi.pine) +- PineScript reference: [`rvgi.pine`](rvgi.pine) \ No newline at end of file diff --git a/lib/oscillators/squeeze/Squeeze.md b/lib/oscillators/squeeze/Squeeze.md index 2ae682df..2bd7205d 100644 --- a/lib/oscillators/squeeze/Squeeze.md +++ b/lib/oscillators/squeeze/Squeeze.md @@ -13,9 +13,7 @@ | **PineScript** | [squeeze.pine](squeeze.pine) | - Squeeze Momentum combines Bollinger Band and Keltner Channel width analysis to detect low-volatility compression ("squeeze") states, while simultan... -- Parameterized by `period` (default 20), `bbmult` (default 2.0), `kcmult` (default 1.5). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [TTM_Squeeze](../../dynamics/ttm_squeeze/TtmSqueeze.md), [BBB](../bbb/Bbb.md) | **Complementary:** Momentum histogram | **Trading note:** Squeeze indicator; detects low-volatility compression. Bollinger inside Keltner = squeeze on. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Squeeze Momentum combines Bollinger Band and Keltner Channel width analysis to detect low-volatility compression ("squeeze") states, while simultaneously measuring directional momentum via linear regression of a detrended price series. The dual output consists of a momentum histogram and a binary squeeze state indicator. When Bollinger Bands contract inside the Keltner Channel, the market is in a squeeze (coiling volatility); when the squeeze releases, the momentum histogram direction signals the likely breakout direction. The implementation combines five distinct computational stages, each using O(1) streaming techniques. @@ -119,4 +117,4 @@ Mixed: the two IIR passes are sequential; everything else is vectorizable. - Carter, J. (2005). *Mastering the Trade*. McGraw-Hill, Chapter 11 - Bollinger, J. (2001). *Bollinger on Bollinger Bands*. McGraw-Hill -- PineScript reference: [`squeeze.pine`](squeeze.pine) +- PineScript reference: [`squeeze.pine`](squeeze.pine) \ No newline at end of file diff --git a/lib/oscillators/stc/stc.md b/lib/oscillators/stc/stc.md index acfdcf57..97aa082e 100644 --- a/lib/oscillators/stc/stc.md +++ b/lib/oscillators/stc/stc.md @@ -13,9 +13,7 @@ | **PineScript** | [stc.pine](stc.pine) | - The Schaff Trend Cycle is a cyclometric oscillator that applies double-Stochastic normalization to MACD, extracting the cyclical phase hidden withi... -- Parameterized by `kperiod` (default 10), `dperiod` (default 3), `fastlength` (default 23), `slowlength` (default 50), `smoothing` (default stcsmoothing.ema). -- Output range: $0$ to $100$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [MACD](../../momentum/macd/Macd.md), [Stoch](../stoch/Stoch.md) | **Complementary:** ADX | **Trading note:** Schaff Trend Cycle; double Stochastic of MACD. Faster trend detection. 25/75 signal levels. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Schaff Trend Cycle is a cyclometric oscillator that applies double-Stochastic normalization to MACD, extracting the cyclical phase hidden within the trend itself. The recursive normalization produces a bounded 0–100 output that reaches extremes earlier than raw MACD while suppressing Stochastic jitter. Developed for currency markets, STC's tendency to flatline at 0 or 100 during strong trends signals continuation rather than reversal — a feature that distinguishes it from conventional momentum oscillators. Output converges toward a square wave in steady-state trending conditions. diff --git a/lib/oscillators/td_seq/Td_seq.md b/lib/oscillators/td_seq/Td_seq.md index e29248ed..65ff4bc0 100644 --- a/lib/oscillators/td_seq/Td_seq.md +++ b/lib/oscillators/td_seq/Td_seq.md @@ -14,8 +14,6 @@ - TD Sequential is Tom DeMark's exhaustion counting system that identifies potential trend reversals through two phases: a 9-count Setup phase that d... - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `comparePeriod + 1` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. TD Sequential is Tom DeMark's exhaustion counting system that identifies potential trend reversals through two phases: a 9-count Setup phase that detects overextended trends, and a 13-count Countdown phase that pinpoints probable reversal timing. Unlike oscillators that measure momentum magnitude, TD Sequential counts consecutive qualifying bars, producing integer outputs (Setup: $\pm 1$ to $\pm 9$; Countdown: $\pm 1$ to $\pm 13$) that represent the progression toward exhaustion. A completed 9-count Setup followed by a completed 13-count Countdown signals high-probability trend exhaustion. All state is maintained in O(1) scalar variables with no buffers required. @@ -111,4 +109,4 @@ The counter state is inherently sequential. The individual comparisons are vecto - DeMark, T.R. (1994). *The New Science of Technical Analysis*. Wiley - DeMark, T.R. (1997). *New Market Timing Techniques*. Wiley - Bloomberg Terminal: DeMark Indicators (DMRK) implementation reference -- PineScript reference: [`td_seq.pine`](td_seq.pine) +- PineScript reference: [`td_seq.pine`](td_seq.pine) \ No newline at end of file diff --git a/lib/oscillators/trendflex/Trendflex.md b/lib/oscillators/trendflex/Trendflex.md index fefc11a1..1bc2275c 100644 --- a/lib/oscillators/trendflex/Trendflex.md +++ b/lib/oscillators/trendflex/Trendflex.md @@ -13,9 +13,7 @@ | **PineScript** | [trendflex.pine](trendflex.pine) | - The Trendflex indicator combines a 2-pole Butterworth low-pass pre-filter (Super Smoother) with an O(1) cumulative slope measurement and exponentia... -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Reflex](../reflex/Reflex.md), [Deco](../deco/Deco.md) | **Complementary:** ADX | **Trading note:** Ehlers' Trendflex; trend-mode companion to Reflex. Positive = uptrend, negative = downtrend. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -151,4 +149,4 @@ Self-consistency validation: Streaming, Batch (TSeries), and Span Batch modes pr - Ehlers, J. F. (2013). "Trendflex and Reflex." *Cycle Analytics for Traders*. Wiley. - Ehlers, J. F. (2004). *Cybernetic Analysis for Stocks and Futures*. Wiley. -- Ehlers, J. F. (2001). *Rocket Science for Traders*. Wiley. +- Ehlers, J. F. (2001). *Rocket Science for Traders*. Wiley. \ No newline at end of file diff --git a/lib/reversals/chandelier/Chandelier.md b/lib/reversals/chandelier/Chandelier.md index 1e59a0a5..ed0b705d 100644 --- a/lib/reversals/chandelier/Chandelier.md +++ b/lib/reversals/chandelier/Chandelier.md @@ -13,9 +13,7 @@ | **PineScript** | [chandelier.pine](chandelier.pine) | - The Chandelier Exit computes ATR-based trailing stop levels that hang from the highest high (for longs) or rise from the lowest low (for shorts) ov... -- Parameterized by `period` (default 22), `multiplier` (default 3.0). -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [PSAR](../psar/Psar.md), [Super](../../dynamics/super/Super.md) | **Complementary:** ADX for trend strength | **Trading note:** Chandelier Exit; ATR-based trailing stop from highest high. Risk management tool. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Chandelier Exit computes ATR-based trailing stop levels that hang from the highest high (for longs) or rise from the lowest low (for shorts) over a lookback period. It produces two overlay lines: ExitLong (trailing stop for long positions) and ExitShort (trailing stop for short positions). Developed by Charles Le Beau and popularized by Alexander Elder. Default parameters: period 22, multiplier 3.0. @@ -165,4 +163,4 @@ Cross-validation with Skender.Stock.Indicators confirms exact numerical match fo - Le Beau, C., & Lucas, D. (1992). *Technical Traders Guide to Computer Analysis of the Futures Market*. McGraw-Hill. - Elder, A. (2002). *Come Into My Trading Room: A Complete Guide to Trading*. John Wiley & Sons. -- Skender.Stock.Indicators: [`GetChandelier()`](https://dotnet.stockindicators.dev/indicators/Chandelier/) +- Skender.Stock.Indicators: [`GetChandelier()`](https://dotnet.stockindicators.dev/indicators/Chandelier/) \ No newline at end of file diff --git a/lib/reversals/ckstop/Ckstop.md b/lib/reversals/ckstop/Ckstop.md index cd1acf9c..e0486a48 100644 --- a/lib/reversals/ckstop/Ckstop.md +++ b/lib/reversals/ckstop/Ckstop.md @@ -13,9 +13,7 @@ | **PineScript** | [ckstop.pine](ckstop.pine) | - The Chande Kroll Stop computes adaptive trailing stop levels using ATR-smoothed volatility envelopes around rolling extremes. -- Parameterized by `atrPeriod` (default 10), `multiplier` (default 1.0), `stopPeriod` (default 9). -- Output range: Varies (see docs). -- Requires `atrPeriod + stopPeriod` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Chandelier](../chandelier/Chandelier.md), [PSAR](../psar/Psar.md) | **Complementary:** ATR | **Trading note:** Chuck LeBeau's Chandelier stop; ATR trailing stop with configurable multiplier. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Chande Kroll Stop computes adaptive trailing stop levels using ATR-smoothed volatility envelopes around rolling extremes. It produces two lines: StopLong (support) and StopShort (resistance). When price trades above both stops, the trend is bullish. When below both, bearish. Crossovers between the two stops signal potential reversals. @@ -174,4 +172,4 @@ No major TA library implements Chande Kroll Stop, making this a Level 3 validati ## References - Chande, T. S., & Kroll, S. (1994). *The New Technical Trader: Boost Your Profit by Plugging into the Latest Indicators*. John Wiley & Sons. -- TradingView PineScript Reference: [`ta.ckstop()`](https://www.tradingview.com/pine-script-reference/v6/#fun_ta.ckstop) +- TradingView PineScript Reference: [`ta.ckstop()`](https://www.tradingview.com/pine-script-reference/v6/#fun_ta.ckstop) \ No newline at end of file diff --git a/lib/reversals/fractals/Fractals.md b/lib/reversals/fractals/Fractals.md index 605a9d4e..5e78a00d 100644 --- a/lib/reversals/fractals/Fractals.md +++ b/lib/reversals/fractals/Fractals.md @@ -14,8 +14,6 @@ - Williams Fractals detect local price extremes using a strict five-bar pattern: an Up Fractal marks a bar whose high exceeds the highs of the two ba... - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Williams Fractals detect local price extremes using a strict five-bar pattern: an Up Fractal marks a bar whose high exceeds the highs of the two bars before and after it; a Down Fractal marks a bar whose low undercuts the lows of the two bars before and after it. No parameters, no smoothing, no lag compensation. The pattern either exists or it does not. Developed by Bill Williams and published in *Trading Chaos* (1995). @@ -171,4 +169,4 @@ Cross-validation with Skender.Stock.Indicators uses `GetFractal(windowSpan: 2)`. - Williams, B. M. (2004). *Trading Chaos: Maximize Profits with Proven Technical Techniques* (2nd ed.). John Wiley and Sons. - Mandelbrot, B. B. (1982). *The Fractal Geometry of Nature*. W. H. Freeman. - TradingView PineScript Reference: [`ta.pivothigh()`](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.pivothigh), [`ta.pivotlow()`](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.pivotlow) -- Skender.Stock.Indicators: [`GetFractal()`](https://dotnet.stockindicators.dev/indicators/Fractal/) +- Skender.Stock.Indicators: [`GetFractal()`](https://dotnet.stockindicators.dev/indicators/Fractal/) \ No newline at end of file diff --git a/lib/reversals/pivot/Pivot.md b/lib/reversals/pivot/Pivot.md index c4800afa..7cb15bfd 100644 --- a/lib/reversals/pivot/Pivot.md +++ b/lib/reversals/pivot/Pivot.md @@ -14,8 +14,6 @@ - Classic Pivot Points calculate seven horizontal support and resistance levels from the previous bar's high, low, and close. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `2` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Classic Pivot Points calculate seven horizontal support and resistance levels from the previous bar's high, low, and close. The central pivot point (PP) is the arithmetic mean of HLC; three resistance levels (R1-R3) and three support levels (S1-S3) are derived from PP and the prior bar's range. The formula has been in continuous use since the 1930s among floor traders at commodity exchanges. Zero parameters, zero lag, zero ambiguity. @@ -204,4 +202,4 @@ Mathematical correctness is validated by computing expected values from the form - Weintraub, N. (1996). *Tricks of the Floor Trader*. McGraw-Hill. - Person, J. L. (2004). *A Complete Guide to Technical Trading Tactics: How to Profit Using Pivot Points, Candlesticks & Other Indicators*. John Wiley and Sons. - Wikipedia: [Pivot point (technical analysis)](https://en.wikipedia.org/wiki/Pivot_point_(technical_analysis)) -- TradingView PineScript Reference: [`ta.pivothigh()`](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.pivothigh), [`ta.pivotlow()`](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.pivotlow) +- TradingView PineScript Reference: [`ta.pivothigh()`](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.pivothigh), [`ta.pivotlow()`](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.pivotlow) \ No newline at end of file diff --git a/lib/reversals/pivotcam/Pivotcam.md b/lib/reversals/pivotcam/Pivotcam.md index 2072528c..8af97fd8 100644 --- a/lib/reversals/pivotcam/Pivotcam.md +++ b/lib/reversals/pivotcam/Pivotcam.md @@ -14,8 +14,6 @@ - Camarilla Pivot Points calculate nine horizontal support and resistance levels from the previous bar's high, low, and close. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `2` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Camarilla Pivot Points calculate nine horizontal support and resistance levels from the previous bar's high, low, and close. Unlike classic floor trader pivots that radiate from the PP midpoint, Camarilla levels radiate symmetrically from the previous close using fixed fractions of the prior range. The R3/S3 levels serve as the primary mean-reversion zone; breakouts beyond R4/S4 signal trend continuation. Developed by Nick Scott in 1989 using bond market data, the equation was originally distributed as a shareware Excel plugin. @@ -210,4 +208,4 @@ Mathematical correctness is validated by computing expected values from the Cama - Scott, N. (1989). *The Camarilla Equation*. Originally distributed as Excel shareware. - Person, J. L. (2004). *A Complete Guide to Technical Trading Tactics: How to Profit Using Pivot Points, Candlesticks & Other Indicators*. John Wiley and Sons. - Wikipedia: [Pivot point (technical analysis)](https://en.wikipedia.org/wiki/Pivot_point_(technical_analysis)) -- TradingView: [Camarilla Pivot Points](https://www.tradingview.com/support/solutions/43000521824-pivot-points-standard/) +- TradingView: [Camarilla Pivot Points](https://www.tradingview.com/support/solutions/43000521824-pivot-points-standard/) \ No newline at end of file diff --git a/lib/reversals/pivotdem/Pivotdem.md b/lib/reversals/pivotdem/Pivotdem.md index c8cc1226..0c24a08d 100644 --- a/lib/reversals/pivotdem/Pivotdem.md +++ b/lib/reversals/pivotdem/Pivotdem.md @@ -14,8 +14,6 @@ - DeMark Pivot Points calculate three horizontal support and resistance levels from the previous bar's open, high, low, and close. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `2` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. DeMark Pivot Points calculate three horizontal support and resistance levels from the previous bar's open, high, low, and close. The defining characteristic is a conditional intermediate value X that changes its weighting depending on whether the prior bar closed below, above, or equal to its open. Bearish bars weight the low; bullish bars weight the high; doji bars weight the close. Three levels (PP, R1, S1) emerge from this single conditional calculation. The only pivot variant that uses the open price. @@ -195,4 +193,4 @@ No external libraries implement bar-to-bar DeMark pivot points. Mathematical cor - DeMark, T. R. (1994). *The New Science of Technical Analysis*. John Wiley and Sons. - DeMark, T. R. (1997). *New Market Timing Techniques: Innovative Studies in Market Rhythm and Price Exhaustion*. John Wiley and Sons. - Person, J. L. (2004). *A Complete Guide to Technical Trading Tactics*. John Wiley and Sons. -- Wikipedia: [Pivot point (technical analysis)](https://en.wikipedia.org/wiki/Pivot_point_(technical_analysis)) +- Wikipedia: [Pivot point (technical analysis)](https://en.wikipedia.org/wiki/Pivot_point_(technical_analysis)) \ No newline at end of file diff --git a/lib/reversals/pivotext/Pivotext.md b/lib/reversals/pivotext/Pivotext.md index fc20e577..48aca889 100644 --- a/lib/reversals/pivotext/Pivotext.md +++ b/lib/reversals/pivotext/Pivotext.md @@ -14,8 +14,6 @@ - Extended Traditional Pivot Points calculate eleven horizontal support and resistance levels from the previous bar's high, low, and close. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `2` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Extended Traditional Pivot Points calculate eleven horizontal support and resistance levels from the previous bar's high, low, and close. The core levels (PP, R1-R3, S1-S3) are identical to classic floor trader pivots. The extension adds R4/R5 and S4/S5 levels that project further beyond the prior bar's range, covering extreme move scenarios such as gap opens, news-driven spikes, and trend continuation through multiple prior-range increments. The formula is pure arithmetic with zero parameters. @@ -203,4 +201,4 @@ Mathematical correctness is validated by computing expected values from the exte - Person, J. L. (2004). *A Complete Guide to Technical Trading Tactics: How to Profit Using Pivot Points, Candlesticks & Other Indicators*. John Wiley and Sons. - Wikipedia: [Pivot point (technical analysis)](https://en.wikipedia.org/wiki/Pivot_point_(technical_analysis)) - TradingView: [Pivot Points Standard](https://www.tradingview.com/support/solutions/43000521824-pivot-points-standard/) -- Nison, S. (2001). *Japanese Candlestick Charting Techniques*. Prentice Hall Press. (Discussion of floor trader pivot methodology.) +- Nison, S. (2001). *Japanese Candlestick Charting Techniques*. Prentice Hall Press. (Discussion of floor trader pivot methodology.) \ No newline at end of file diff --git a/lib/reversals/pivotfib/Pivotfib.md b/lib/reversals/pivotfib/Pivotfib.md index 3f992a90..77aa840a 100644 --- a/lib/reversals/pivotfib/Pivotfib.md +++ b/lib/reversals/pivotfib/Pivotfib.md @@ -14,8 +14,6 @@ - Fibonacci Pivot Points apply Fibonacci retracement ratios (38.2%, 61.8%, 100%) to the standard pivot point formula. - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `2` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Overview @@ -118,4 +116,4 @@ Excellent SIMD candidate — all 7 output levels are independent. BatchAll span - **Outputs**: 7 (PP, R1, R2, R3, S1, S2, S3) - **Input**: TBar (OHLCV) - **Complexity**: O(1) per bar -- **Uses FMA**: `Math.FusedMultiplyAdd` for R1/S1/R2/S2 computations +- **Uses FMA**: `Math.FusedMultiplyAdd` for R1/S1/R2/S2 computations \ No newline at end of file diff --git a/lib/reversals/pivotwood/Pivotwood.md b/lib/reversals/pivotwood/Pivotwood.md index 540b84f9..fe238965 100644 --- a/lib/reversals/pivotwood/Pivotwood.md +++ b/lib/reversals/pivotwood/Pivotwood.md @@ -14,8 +14,6 @@ - Woodie's Pivot Points weight the closing price twice in the pivot calculation, biasing the central pivot toward where the market actually settled r... - No configurable parameters; computation is stateless per bar. -- Output range: Varies (see docs). -- Requires `2` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Overview @@ -138,4 +136,4 @@ Full vectorization possible. All output levels computed from previous-bar consta - **Outputs**: 7 (PP, R1, R2, R3, S1, S2, S3) - **Input**: TBar (OHLCV) - **Complexity**: O(1) per bar -- **Uses FMA**: `Math.FusedMultiplyAdd` for R1, S1, R3, S3 computations +- **Uses FMA**: `Math.FusedMultiplyAdd` for R1, S1, R3, S3 computations \ No newline at end of file diff --git a/lib/reversals/psar/Psar.md b/lib/reversals/psar/Psar.md index 6ae90cc3..6c66540d 100644 --- a/lib/reversals/psar/Psar.md +++ b/lib/reversals/psar/Psar.md @@ -13,9 +13,7 @@ | **PineScript** | [psar.pine](psar.pine) | - The Parabolic Stop And Reverse (PSAR) is a trend-following overlay indicator created by J. -- Parameterized by `afStart` (default 0.02), `afIncrement` (default 0.02), `afMax` (default 0.20). -- Output range: Varies (see docs). -- Requires `1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Super](../../dynamics/super/Super.md), [Chandelier](../chandelier/Chandelier.md) | **Complementary:** ADX for trend confirmation | **Trading note:** Wilder's Parabolic SAR; trailing stop that accelerates. Dots flip on reversal. Classic trend-following exit. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -157,4 +155,4 @@ Note: Different libraries may vary on first-bar initialization (close > open vs. - Wilder, J. W. Jr. (1978). *New Concepts in Technical Trading Systems*. Trend Research. ISBN 978-0894590276. - Kaufman, P. J. (2013). *Trading Systems and Methods*, 5th ed. Wiley. Chapter on Parabolic Time/Price System. -- StockCharts.com. "Parabolic SAR." ChartSchool Technical Indicators. +- StockCharts.com. "Parabolic SAR." ChartSchool Technical Indicators. \ No newline at end of file diff --git a/lib/reversals/sarext/Sarext.md b/lib/reversals/sarext/Sarext.md index 854e57ee..f3b1484e 100644 --- a/lib/reversals/sarext/Sarext.md +++ b/lib/reversals/sarext/Sarext.md @@ -16,7 +16,6 @@ - Sign-encoded output: positive = long (SAR below price), negative = short (SAR above price). - Matches TA-Lib `TA_SAREXT` specification with 8 parameters. - Auto-detects initial direction from Directional Movement when `startValue == 0`. -- Requires `2` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib reference implementation. ## Introduction @@ -173,4 +172,4 @@ SAREXT cannot be vectorized. The state machine has data-dependent branches (reve - TA-Lib. "TA_SAREXT — SAR Extended." Open-source technical analysis library. - Wilder, J. W. Jr. (1978). *New Concepts in Technical Trading Systems*. Trend Research. ISBN 978-0894590276. -- Kaufman, P. J. (2013). *Trading Systems and Methods*, 5th ed. Wiley. +- Kaufman, P. J. (2013). *Trading Systems and Methods*, 5th ed. Wiley. \ No newline at end of file diff --git a/lib/reversals/swings/Swings.md b/lib/reversals/swings/Swings.md index 78f8e441..dd706054 100644 --- a/lib/reversals/swings/Swings.md +++ b/lib/reversals/swings/Swings.md @@ -13,9 +13,7 @@ | **PineScript** | [swings.pine](swings.pine) | - Swing High/Low detection identifies local price extremes using a configurable lookback window. -- Parameterized by `lookback` (default 5). -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [Fractal](../../oscillators/fisher/Fisher.md), [ZigZag](../psar/Psar.md) | **Complementary:** Volume for confirmation | **Trading note:** Swing high/low detector; identifies pivots for support/resistance and chart pattern analysis. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Swing High/Low detection identifies local price extremes using a configurable lookback window. A Swing High marks a bar whose high strictly exceeds the highs of all bars within the lookback window on each side. A Swing Low marks a bar whose low is strictly less than all corresponding lows. The lookback parameter controls sensitivity: larger lookback windows require more confirmation and produce fewer, more significant signals. This generalizes Williams' fixed five-bar Fractals into a flexible structural analysis tool. @@ -187,4 +185,4 @@ Mathematical correctness is verified by confirming that every reported SwingHigh - Williams, B. M. (1995). *Trading Chaos: Applying Expert Techniques to Maximize Your Profits*. John Wiley and Sons. - Gann, W. D. (1935). *New Stock Trend Detector*. Financial Guardian Publishing. -- TradingView PineScript Reference: [`ta.pivothigh()`](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.pivothigh), [`ta.pivotlow()`](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.pivotlow) +- TradingView PineScript Reference: [`ta.pivothigh()`](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.pivothigh), [`ta.pivotlow()`](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.pivotlow) \ No newline at end of file diff --git a/lib/reversals/ttm_scalper/TtmScalper.md b/lib/reversals/ttm_scalper/TtmScalper.md index 3832dac1..0d5e78d3 100644 --- a/lib/reversals/ttm_scalper/TtmScalper.md +++ b/lib/reversals/ttm_scalper/TtmScalper.md @@ -13,9 +13,7 @@ | **PineScript** | [ttmscalper.pine](ttmscalper.pine) | - John Carter designed TTM Scalper Alert for quick identification of potential reversal points using a simple three-bar pattern recognition. -- Parameterized by `usecloses` (default false). -- Output range: Varies (see docs). -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [TTM_Trend](../../dynamics/ttm_trend/TtmTrend.md), [Super](../../dynamics/super/Super.md) | **Complementary:** TTM Squeeze | **Trading note:** John Carter's scalper; short-term reversal signals based on pivot analysis. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. > **Pending Implementation** - Placeholder for John Carter's TTM Scalper Alert indicator @@ -110,4 +108,4 @@ O(1) per bar. All state fits in two RingBuffers of size 3. Signal logic is a bra | Signal comparison | Yes | Vector conditional-select for buy/sell | | Output array fill | Yes | Branchless signal assignment | -Limited SIMD benefit due to 3-bar window size — setup cost exceeds savings. The comparison/signal phase is SIMD-friendly for batch output. +Limited SIMD benefit due to 3-bar window size — setup cost exceeds savings. The comparison/signal phase is SIMD-friendly for batch output. \ No newline at end of file diff --git a/lib/statistics/acf/Acf.md b/lib/statistics/acf/Acf.md index e2f9ccc0..a87ed077 100644 --- a/lib/statistics/acf/Acf.md +++ b/lib/statistics/acf/Acf.md @@ -13,9 +13,7 @@ | **PineScript** | [acf.pine](acf.pine) | - The Autocorrelation Function (ACF) measures the correlation of a time series with a lagged copy of itself. -- Parameterized by `period`, `lag` (default 1). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [PACF](../pacf/Pacf.md), [Correlation](../correlation/Correlation.md) | **Trading note:** Autocorrelation function; detects mean-reversion (negative ACF) vs momentum (positive ACF) in returns. - Validated against mathematical properties and theoretical AR-process expectations. The Autocorrelation Function (ACF) measures the correlation of a time series with a lagged copy of itself. It is fundamental for identifying repeating patterns, seasonal effects, and determining the order of time series models like ARMA/ARIMA. @@ -175,4 +173,4 @@ A random walk should have ACF ≈ 0 at all lags. Significant ACF values indicate - Box, G.E.P., Jenkins, G.M. (1970). *Time Series Analysis: Forecasting and Control*. Holden-Day. - Hamilton, J.D. (1994). *Time Series Analysis*. Princeton University Press. -- Yule, G.U. (1927). "On a Method of Investigating Periodicities in Disturbed Series." *Philosophical Transactions of the Royal Society*. +- Yule, G.U. (1927). "On a Method of Investigating Periodicities in Disturbed Series." *Philosophical Transactions of the Royal Society*. \ No newline at end of file diff --git a/lib/statistics/beta/Beta.md b/lib/statistics/beta/Beta.md index 37ba9449..14d7f502 100644 --- a/lib/statistics/beta/Beta.md +++ b/lib/statistics/beta/Beta.md @@ -13,9 +13,7 @@ | **PineScript** | [beta.pine](beta.pine) | - Beta measures the volatility of an asset in relation to the overall market. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Correlation](../correlation/Correlation.md), [Covariance](../covariance/Covariance.md) | **Trading note:** Beta coefficient; measures systematic risk vs benchmark. β>1 = amplifies market moves. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Beta measures the volatility of an asset in relation to the overall market. It's the slope of the regression line between the asset's returns and the market's returns. A beta of 1.0 means the asset moves in lockstep with the market. A beta of 2.0 means the asset is twice as volatile as the market. @@ -109,4 +107,4 @@ var beta = new Beta(20); // (e.g., AAPL price and SPY price) TValue result = beta.Update(assetPrice, marketPrice); -Console.WriteLine($"Beta: {result.Value:F4}"); +Console.WriteLine($"Beta: {result.Value:F4}"); \ No newline at end of file diff --git a/lib/statistics/cma/Cma.md b/lib/statistics/cma/Cma.md index 3b684566..48deeb2e 100644 --- a/lib/statistics/cma/Cma.md +++ b/lib/statistics/cma/Cma.md @@ -13,9 +13,7 @@ | **PineScript** | [cma.pine](cma.pine) | - The Cumulative Moving Average (CMA) calculates the arithmetic mean of ALL data points seen so far, not just a fixed window. -- Parameterized by `source`. -- Output range: Varies (see docs). -- Requires `1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SMA](../../trends_FIR/sma/Sma.md), [EMA](../../trends_IIR/ema/ema.md) | **Trading note:** Cumulative Moving Average; running mean of all data points. Anchored VWAP without volume weighting. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Cumulative Moving Average (CMA) calculates the arithmetic mean of ALL data points seen so far, not just a fixed window. Unlike SMA or EMA which use a sliding window, CMA treats every historical value with equal weight. As the sample size grows, each new value has diminishing impact on the average. @@ -124,4 +122,4 @@ CMA is a fundamental statistical operation rather than a standard TA library ind 1. **Responsiveness**: CMA becomes nearly unresponsive after many values. For a reactive average, use SMA or EMA instead. 2. **Memory of Bad Data**: A single extreme outlier early in the stream permanently affects the average. Consider filtering before feeding CMA. 3. **No Period Parameter**: Unlike SMA/EMA, CMA has no period. It always includes all data. This is by design. -4. **Session Resets**: If you need per-session averages, call `Reset()` at session boundaries. +4. **Session Resets**: If you need per-session averages, call `Reset()` at session boundaries. \ No newline at end of file diff --git a/lib/statistics/cointegration/Cointegration.md b/lib/statistics/cointegration/Cointegration.md index 1a869c4f..b0ebfab2 100644 --- a/lib/statistics/cointegration/Cointegration.md +++ b/lib/statistics/cointegration/Cointegration.md @@ -13,9 +13,7 @@ | **PineScript** | [cointegration.pine](cointegration.pine) | - The Cointegration indicator measures the long-run equilibrium relationship between two price series using the Engle-Granger two-step method with an... -- Parameterized by `period` (default 20). -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Correlation](../correlation/Correlation.md), [Granger](../granger/Granger.md) | **Trading note:** Tests if two series share a long-run equilibrium. Foundation of statistical arbitrage (pairs trading). - Validated against TradingView PineScript reference and statistical property tests. The Cointegration indicator measures the long-run equilibrium relationship between two price series using the Engle-Granger two-step method with an Augmented Dickey-Fuller (ADF) test. Unlike correlation, which measures short-term co-movement, cointegration tests whether two non-stationary series share a common stochastic trend—meaning they may diverge temporarily but are statistically bound to revert to their equilibrium relationship. @@ -286,4 +284,4 @@ coint.Update(101.0, 51.0, isNew: false); // Recalculates without advancing state - Engle, R.F. and Granger, C.W.J. (1987). "Co-integration and Error Correction: Representation, Estimation, and Testing." *Econometrica*, 55(2), 251-276. - Dickey, D.A. and Fuller, W.A. (1979). "Distribution of the Estimators for Autoregressive Time Series with a Unit Root." *Journal of the American Statistical Association*, 74(366), 427-431. - TradingView. "Cointegration Indicator (PineScript)." *TradingView Community Scripts*. -- Vidyamurthy, G. (2004). "Pairs Trading: Quantitative Methods and Analysis." *Wiley Finance*. +- Vidyamurthy, G. (2004). "Pairs Trading: Quantitative Methods and Analysis." *Wiley Finance*. \ No newline at end of file diff --git a/lib/statistics/correlation/Correlation.md b/lib/statistics/correlation/Correlation.md index 45a40828..57315ca5 100644 --- a/lib/statistics/correlation/Correlation.md +++ b/lib/statistics/correlation/Correlation.md @@ -13,9 +13,7 @@ | **PineScript** | [correlation.pine](correlation.pine) | - The Pearson Correlation Coefficient measures the linear relationship between two variables, returning a value from -1 (perfect negative correlation... -- Parameterized by `period` (default 20). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Spearman](../spearman/Spearman.md), [Kendall](../kendall/Kendall.md) | **Trading note:** Pearson correlation; measures linear relationship strength. Used for portfolio diversification and pairs trading. - Validated against TradingView reference behavior and mathematical invariants. The Pearson Correlation Coefficient measures the linear relationship between two variables, returning a value from -1 (perfect negative correlation) to +1 (perfect positive correlation). Zero indicates no linear relationship. This implementation uses running sums for O(1) streaming updates, making it suitable for real-time analysis of price relationships. @@ -281,4 +279,4 @@ corr.Update(101.0, 51.0, isNew: false); // Recalculates without advancing state - Pearson, K. (1895). "Notes on regression and inheritance in the case of two parents." *Proceedings of the Royal Society of London*, 58, 240-242. - TradingView. "ta.correlation() function." *Pine Script Language Reference Manual*. - Vidyamurthy, G. (2004). "Pairs Trading: Quantitative Methods and Analysis." *Wiley Finance*. Chapter on correlation analysis. -- Embrechts, P., McNeil, A., & Straumann, D. (2002). "Correlation and dependence in risk management: properties and pitfalls." *Risk Management: Value at Risk and Beyond*, Cambridge University Press. +- Embrechts, P., McNeil, A., & Straumann, D. (2002). "Correlation and dependence in risk management: properties and pitfalls." *Risk Management: Value at Risk and Beyond*, Cambridge University Press. \ No newline at end of file diff --git a/lib/statistics/covariance/Covariance.md b/lib/statistics/covariance/Covariance.md index 18f26d78..72f38eeb 100644 --- a/lib/statistics/covariance/Covariance.md +++ b/lib/statistics/covariance/Covariance.md @@ -13,9 +13,7 @@ | **PineScript** | [covariance.pine](covariance.pine) | - Covariance measures the joint variability of two random variables. -- Parameterized by `period`, `ispopulation` (default false). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Correlation](../correlation/Correlation.md), [Beta](../beta/Beta.md) | **Trading note:** Rolling covariance; measures how two assets move together. Foundation of portfolio theory. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Covariance measures the joint variability of two random variables. It indicates the direction of the linear relationship between variables. @@ -84,4 +82,4 @@ var cov = new Covariance(20); cov.Update(price1, price2); // Access the result -double result = cov.Last.Value; +double result = cov.Last.Value; \ No newline at end of file diff --git a/lib/statistics/entropy/Entropy.md b/lib/statistics/entropy/Entropy.md index 9acf1807..8088776c 100644 --- a/lib/statistics/entropy/Entropy.md +++ b/lib/statistics/entropy/Entropy.md @@ -13,9 +13,7 @@ | **PineScript** | [entropy.pine](entropy.pine) | - Shannon Entropy measures the unpredictability or randomness of a time series over a sliding window. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Hurst](../hurst/Hurst.md), [StdDev](../stddev/StdDev.md) | **Trading note:** Shannon entropy; measures information content and randomness. High entropy = unpredictable market. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Shannon Entropy measures the unpredictability or randomness of a time series over a sliding window. A low entropy value indicates the series is highly predictable (clustered values), while a high entropy value indicates the data is spread uniformly across its range — maximum randomness. @@ -108,4 +106,4 @@ var series = Entropy.Batch(source, period: 14); // Span mode Entropy.Batch(inputSpan, outputSpan, period: 14); -``` +``` \ No newline at end of file diff --git a/lib/statistics/geomean/Geomean.md b/lib/statistics/geomean/Geomean.md index dbff5508..30ef3012 100644 --- a/lib/statistics/geomean/Geomean.md +++ b/lib/statistics/geomean/Geomean.md @@ -13,9 +13,7 @@ | **PineScript** | [geomean.pine](geomean.pine) | - The Geometric Mean computes the nth root of the product of n positive values over a sliding window. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Harmean](../harmean/Harmean.md), [CMA](../cma/Cma.md) | **Trading note:** Geometric mean; proper average for returns/growth rates. Accounts for compounding. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Geometric Mean computes the nth root of the product of n positive values over a sliding window. Unlike the arithmetic mean, it captures multiplicative relationships and is the correct average for growth rates, ratios, and log-normally distributed data. For financial time series, this means it properly accounts for compounding. @@ -151,4 +149,4 @@ Geomean.Batch(inputSpan, outputSpan, period: 14); - Euclid, *Elements*, Book VI, Proposition 13 (ca. 300 BCE). - Cauchy, A.-L. "Cours d'analyse de l'Ecole royale polytechnique" (1821). First rigorous proof of AM-GM. - Kahan, W. "Pracniques: Further Remarks on Reducing Truncation Errors" (1965). -- PineScript `ta.geomean()` reference implementation. +- PineScript `ta.geomean()` reference implementation. \ No newline at end of file diff --git a/lib/statistics/granger/Granger.md b/lib/statistics/granger/Granger.md index 1b145535..718356a8 100644 --- a/lib/statistics/granger/Granger.md +++ b/lib/statistics/granger/Granger.md @@ -13,9 +13,7 @@ | **PineScript** | [granger.pine](granger.pine) | - The Granger Causality test asks a precise, falsifiable question: does knowing the history of series X improve your ability to predict series Y, bey... -- Parameterized by `period` (default 20). -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Cointegration](../cointegration/Cointegration.md), [Correlation](../correlation/Correlation.md) | **Trading note:** Granger causality test; determines if one time series can forecast another. Lead-lag detection. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -145,4 +143,4 @@ This indicator validates against statistical properties rather than external TA - Granger, C.W.J. (1969). "Investigating Causal Relations by Econometric Models and Cross-spectral Methods." Econometrica, 37(3), 424-438. - Granger, C.W.J. (1980). "Testing for Causality: A Personal Viewpoint." Journal of Economic Dynamics and Control, 2, 329-352. - Hamilton, J.D. (1994). Time Series Analysis. Princeton University Press. Chapter 11. -- Sims, C.A. (1972). "Money, Income, and Causality." American Economic Review, 62(4), 540-552. +- Sims, C.A. (1972). "Money, Income, and Causality." American Economic Review, 62(4), 540-552. \ No newline at end of file diff --git a/lib/statistics/harmean/Harmean.md b/lib/statistics/harmean/Harmean.md index d556be4b..d79d12bf 100644 --- a/lib/statistics/harmean/Harmean.md +++ b/lib/statistics/harmean/Harmean.md @@ -13,9 +13,7 @@ | **PineScript** | [harmean.pine](harmean.pine) | - The Harmonic Mean computes the reciprocal of the arithmetic mean of reciprocals over a sliding window. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Geomean](../geomean/Geomean.md), [CMA](../cma/Cma.md) | **Trading note:** Harmonic mean; appropriate for averaging rates/ratios. Always ≤ geometric mean ≤ arithmetic mean. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Harmonic Mean computes the reciprocal of the arithmetic mean of reciprocals over a sliding window. It is the correct average for quantities defined in terms of rates or ratios (speed, P/E ratios, yield). For financial time series, the harmonic mean gives the largest discount to outliers, making it the most conservative of the three Pythagorean means. @@ -128,4 +126,4 @@ Self-validated against mathematical properties and Wolfram Alpha known values. - Bullen, P.S. "Handbook of Means and Their Inequalities." Kluwer Academic Publishers, 2003. - Ferger, W.F. "The Nature and Use of the Harmonic Mean." Journal of the American Statistical Association, 1931. -- PineScript reference: `lib/statistics/harmean/harmean.pine` +- PineScript reference: `lib/statistics/harmean/harmean.pine` \ No newline at end of file diff --git a/lib/statistics/hurst/Hurst.md b/lib/statistics/hurst/Hurst.md index bbcb11f5..9e552e79 100644 --- a/lib/statistics/hurst/Hurst.md +++ b/lib/statistics/hurst/Hurst.md @@ -13,9 +13,7 @@ | **PineScript** | [hurst.pine](hurst.pine) | - The Hurst Exponent ($H$) quantifies long-range dependence in a time series through Rescaled Range (R/S) analysis. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ACF](../acf/Acf.md), [Entropy](../entropy/Entropy.md) | **Trading note:** Hurst exponent; H>0.5 = trending (persistent), H<0.5 = mean-reverting, H=0.5 = random walk. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -188,4 +186,4 @@ No external library provides a direct R/S-based Hurst exponent for cross-validat - Mandelbrot, B.B. and Wallis, J.R. (1969). "Robustness of the rescaled range R/S in the measurement of noncyclic long run statistical dependence." *Water Resources Research*, 5(5), 967-988. - Peters, E.E. (1994). *Fractal Market Analysis*. Wiley. - Anis, A.A. and Lloyd, E.H. (1976). "The expected value of the adjusted rescaled Hurst range of independent normal summands." *Biometrika*, 63(1), 111-116. -- Lo, A.W. (1991). "Long-term memory in stock market prices." *Econometrica*, 59(5), 1279-1313. +- Lo, A.W. (1991). "Long-term memory in stock market prices." *Econometrica*, 59(5), 1279-1313. \ No newline at end of file diff --git a/lib/statistics/iqr/Iqr.md b/lib/statistics/iqr/Iqr.md index fcf5543b..8281b6c3 100644 --- a/lib/statistics/iqr/Iqr.md +++ b/lib/statistics/iqr/Iqr.md @@ -13,9 +13,7 @@ | **PineScript** | [iqr.pine](iqr.pine) | - The Interquartile Range measures the spread of the middle 50% of a sorted dataset within a rolling window. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [StdDev](../stddev/StdDev.md), [Percentile](../percentile/Percentile.md) | **Trading note:** Interquartile Range; robust dispersion measure (Q3−Q1). Identifies outlier moves. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -167,4 +165,4 @@ No external library implements a streaming rolling IQR with linear interpolation - Tukey, J.W. (1977). *Exploratory Data Analysis*. Addison-Wesley. - Galton, F. (1885). "Statistics by Intercomparison." *Philosophical Magazine*. -- Frigge, M., Hoaglin, D.C., Iglewicz, B. (1989). "Some Implementations of the Boxplot." *The American Statistician*, 43(1), 50-54. +- Frigge, M., Hoaglin, D.C., Iglewicz, B. (1989). "Some Implementations of the Boxplot." *The American Statistician*, 43(1), 50-54. \ No newline at end of file diff --git a/lib/statistics/jb/Jb.md b/lib/statistics/jb/Jb.md index 87973c6c..d7517563 100644 --- a/lib/statistics/jb/Jb.md +++ b/lib/statistics/jb/Jb.md @@ -13,9 +13,7 @@ | **PineScript** | [jb.pine](jb.pine) | - The Jarque-Bera test quantifies departure from normality by combining skewness and excess kurtosis into a single chi-squared statistic. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Kurtosis](../kurtosis/Kurtosis.md), [Skew](../skew/Skew.md) | **Trading note:** Jarque-Bera test; tests if returns are normally distributed. Significant = fat tails present. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Jarque-Bera test quantifies departure from normality by combining skewness and excess kurtosis into a single chi-squared statistic. A rolling JB value near zero means the window looks Gaussian. Values exceeding 5.991 (5% significance) reject normality. Financial returns almost always fail this test, which is precisely why the test matters. @@ -148,4 +146,4 @@ Self-validation: - Jarque, C. M.; Bera, A. K. (1980). "Efficient tests for normality, homoscedasticity and serial independence of regression residuals." *Economics Letters*, 6(3), 255-259. - Bowman, K. O.; Shenton, L. R. (1975). "Omnibus test contours for departures from normality based on √b₁ and b₂." *Biometrika*, 62(2), 243-250. -- PineScript reference: `lib/statistics/jb/jb.pine` +- PineScript reference: `lib/statistics/jb/jb.pine` \ No newline at end of file diff --git a/lib/statistics/kurtosis/Kurtosis.md b/lib/statistics/kurtosis/Kurtosis.md index 017edba0..37b47e32 100644 --- a/lib/statistics/kurtosis/Kurtosis.md +++ b/lib/statistics/kurtosis/Kurtosis.md @@ -13,9 +13,7 @@ | **PineScript** | [kurtosis.pine](kurtosis.pine) | - Kurtosis measures the **tailedness** of a probability distribution. -- Parameterized by `period`, `ispopulation` (default false). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Skew](../skew/Skew.md), [JB](../jb/Jb.md) | **Trading note:** Excess kurtosis; >0 = fat tails (leptokurtic), <0 = thin tails. Measures tail risk in returns. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -143,4 +141,4 @@ O(1) per update using 4th-moment running sums. Numerically sensitive — periodi - Pearson, K. (1905). "Das Fehlergesetz und seine Verallgemeinerungen durch Fechner und Pearson." *Biometrika*, 4(1-2), 169-212. - Mandelbrot, B. (1963). "The Variation of Certain Speculative Prices." *The Journal of Business*, 36(4), 394-419. - Joanes, D. N., & Gill, C. A. (1998). "Comparing measures of sample skewness and kurtosis." *Journal of the Royal Statistical Society: Series D*, 47(1), 183-189. -- DeCarlo, L. T. (1997). "On the meaning and use of kurtosis." *Psychological Methods*, 2(3), 292-307. +- DeCarlo, L. T. (1997). "On the meaning and use of kurtosis." *Psychological Methods*, 2(3), 292-307. \ No newline at end of file diff --git a/lib/statistics/linreg/LinReg.md b/lib/statistics/linreg/LinReg.md index 16b3be15..1f7d7487 100644 --- a/lib/statistics/linreg/LinReg.md +++ b/lib/statistics/linreg/LinReg.md @@ -13,9 +13,7 @@ | **PineScript** | [linreg.pine](linreg.pine) | - The Linear Regression Curve plots the end point of the linear regression line for each bar. -- Parameterized by `period`, `offset` (default 0). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Polyfit](../polyfit/Polyfit.md), [TSF](../../trends_FIR/tsf/Tsf.md) | **Trading note:** Linear regression; slope = trend direction/speed, R² = trend strength. Foundation of many indicators. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Linear Regression Curve plots the end point of the linear regression line for each bar. It fits a straight line $y = mx + b$ to the data points using the least squares method, providing a smoothed representation of the price trend that is more responsive than a Simple Moving Average (SMA). @@ -118,4 +116,4 @@ linreg.Update(new TValue(DateTime.UtcNow, 100.0)); // Access result double value = linreg.Last.Value; double slope = linreg.Slope; -double r2 = linreg.RSquared; +double r2 = linreg.RSquared; \ No newline at end of file diff --git a/lib/statistics/meandev/MeanDev.md b/lib/statistics/meandev/MeanDev.md index 319cf0a2..865e2f37 100644 --- a/lib/statistics/meandev/MeanDev.md +++ b/lib/statistics/meandev/MeanDev.md @@ -13,9 +13,7 @@ | **PineScript** | [meandev.pine](meandev.pine) | - ````markdown -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [StdDev](../stddev/StdDev.md), [IQR](../iqr/Iqr.md) | **Trading note:** Mean deviation (average absolute deviation); more robust than StdDev. Used in CCI calculation. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Mean Deviation (also known as Mean Absolute Deviation or Average Absolute Deviation) measures the average of the absolute deviations from the mean. Unlike Standard Deviation, it does not square the deviations, making it more robust to outliers and more intuitive to interpret. @@ -105,4 +103,4 @@ double value = meanDev.Last.Value; * **StdDev** — Standard Deviation (quadratic weighting of deviations). * **Variance** — Variance (squared deviations from mean). * **Cci** — Commodity Channel Index (uses Mean Deviation as a normalizer). -```` +```` \ No newline at end of file diff --git a/lib/statistics/median/Median.md b/lib/statistics/median/Median.md index c33fea08..c83818c6 100644 --- a/lib/statistics/median/Median.md +++ b/lib/statistics/median/Median.md @@ -13,9 +13,7 @@ | **PineScript** | [median.pine](median.pine) | - The Rolling Median is a robust statistic that represents the middle value of a dataset within a moving window. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Mode](../mode/Mode.md), [Percentile](../percentile/Percentile.md) | **Trading note:** Rolling median; robust central tendency resistant to outliers. Good for support/resistance identification. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Rolling Median is a robust statistic that represents the middle value of a dataset within a moving window. Unlike the Simple Moving Average (SMA), which can be skewed by extreme values, the Median provides a more stable measure of central tendency, making it particularly useful for filtering noise in volatile markets. @@ -82,4 +80,4 @@ O(N) per update. For large N, a dual-heap (min-heap + max-heap) O(log N) structu ### Common Pitfalls * **Quantization**: The median moves in discrete steps (jumps from one value to another) rather than smoothly like an average. -* **Flatlining**: In periods of low volatility, the median can remain constant for many bars, which may be interpreted as a lack of trend. +* **Flatlining**: In periods of low volatility, the median can remain constant for many bars, which may be interpreted as a lack of trend. \ No newline at end of file diff --git a/lib/statistics/mode/Mode.md b/lib/statistics/mode/Mode.md index 99e85241..b1cc3a0a 100644 --- a/lib/statistics/mode/Mode.md +++ b/lib/statistics/mode/Mode.md @@ -13,9 +13,7 @@ | **PineScript** | [mode.pine](mode.pine) | - The **Mode** is a rolling statistical indicator that identifies the most frequently occurring value within a sliding window of recent observations. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Median](../median/Median.md), [Percentile](../percentile/Percentile.md) | **Trading note:** Statistical mode; most frequent value in window. Identifies price levels with highest activity (value area). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -152,4 +150,4 @@ Verified against Wolfram Alpha for static datasets. ## References - PineScript reference: `mode.pine` (exact value comparison, map-based counting) -- Wolfram MathWorld: [Statistical Mode](https://mathworld.wolfram.com/Mode.html) +- Wolfram MathWorld: [Statistical Mode](https://mathworld.wolfram.com/Mode.html) \ No newline at end of file diff --git a/lib/statistics/pacf/Pacf.md b/lib/statistics/pacf/Pacf.md index 29c36cc9..dfadb029 100644 --- a/lib/statistics/pacf/Pacf.md +++ b/lib/statistics/pacf/Pacf.md @@ -13,9 +13,7 @@ | **PineScript** | [pacf.pine](pacf.pine) | - The Partial Autocorrelation Function (PACF) measures the correlation between a time series and its lagged values, after removing the effects of all... -- Parameterized by `period`, `lag` (default 1). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ACF](../acf/Acf.md), [LinReg](../linreg/LinReg.md) | **Trading note:** Partial autocorrelation; isolates direct lag relationships. Used for ARIMA model order selection. - Validated against mathematical properties and Durbin-Levinson recursion expectations. The Partial Autocorrelation Function (PACF) measures the correlation between a time series and its lagged values, after removing the effects of all intermediate lags. While ACF shows total correlation at each lag, PACF isolates the direct correlation, making it essential for AR model identification. @@ -210,4 +208,4 @@ PACF is used in linear prediction and filter design, where the partial correlati - Box, G.E.P., Jenkins, G.M. (1970). *Time Series Analysis: Forecasting and Control*. Holden-Day. - Durbin, J. (1960). "The fitting of time series models." *Review of the International Statistical Institute*, 28, 233-243. - Levinson, N. (1946). "The Wiener RMS error criterion in filter design and prediction." *Journal of Mathematics and Physics*, 25, 261-278. -- Hamilton, J.D. (1994). *Time Series Analysis*. Princeton University Press. +- Hamilton, J.D. (1994). *Time Series Analysis*. Princeton University Press. \ No newline at end of file diff --git a/lib/statistics/percentile/Percentile.md b/lib/statistics/percentile/Percentile.md index 6899e495..4d3f3370 100644 --- a/lib/statistics/percentile/Percentile.md +++ b/lib/statistics/percentile/Percentile.md @@ -13,9 +13,7 @@ | **PineScript** | [percentile.pine](percentile.pine) | - The Rolling Percentile computes the value below which a given percentage of observations fall within a sliding window. -- Parameterized by `period`, `percent` (default 50.0). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Quantile](../quantile/Quantile.md), [Median](../median/Median.md) | **Trading note:** Percentile rank of current value; 90th+ = historically elevated, 10th− = historically depressed. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. > But percentiles, at least, tell you exactly where you stand. @@ -137,4 +135,4 @@ O(N) per update due to sorted-array shift. A skip-list or order-statistics tree - Hyndman, R.J. and Fan, Y. (1996). "Sample Quantiles in Statistical Packages." _The American Statistician_, 50(4), 361-365. - Galton, F. (1885). "Some Results of the Anthropometric Laboratory." _Journal of the Anthropological Institute_, 14, 275-287. - Microsoft Excel Documentation: [PERCENTILE.INC function](https://support.microsoft.com/en-us/office/percentile-inc-function-680f9539-45eb-410b-9a5e-c1355e5fe2ed) -- TradingView PineScript Reference: [ta.percentile_linear_interpolation](https://www.tradingview.com/pine-script-reference/v6/) +- TradingView PineScript Reference: [ta.percentile_linear_interpolation](https://www.tradingview.com/pine-script-reference/v6/) \ No newline at end of file diff --git a/lib/statistics/polyfit/Polyfit.md b/lib/statistics/polyfit/Polyfit.md index 29b83c06..bbb97248 100644 --- a/lib/statistics/polyfit/Polyfit.md +++ b/lib/statistics/polyfit/Polyfit.md @@ -13,9 +13,7 @@ | **PineScript** | [polyfit.pine](polyfit.pine) | - Polynomial Fitting computes a rolling polynomial regression of configurable degree over a lookback window, returning the fitted value at the curren... -- Parameterized by `period`, `degree` (default 2). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [LinReg](../linreg/LinReg.md), [TSF](../../trends_FIR/tsf/Tsf.md) | **Trading note:** Polynomial curve fitting; captures non-linear trends. Higher order = more responsive but risk of overfitting. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Polynomial Fitting computes a rolling polynomial regression of configurable degree over a lookback window, returning the fitted value at the current bar. Degree 1 produces a linear regression endpoint (identical to LSQR), degree 2 produces a quadratic fit that captures curvature, and degree 3 produces a cubic fit that captures inflection points. The implementation solves the normal equations $\mathbf{X}^T\mathbf{X}\mathbf{a} = \mathbf{X}^T\mathbf{y}$ via Gauss-Jordan elimination with partial pivoting, evaluating the resulting polynomial at $x = 1$ (the current bar position). With $O(Nd + d^3)$ complexity per bar where $N$ is the period and $d$ is the degree, POLYFIT provides a general-purpose curve-fitting tool that subsumes linear regression and extends it to arbitrary polynomial order. @@ -134,4 +132,4 @@ Batch span path can vectorize sum accumulation and output projection. Inner loop - Gauss, C.F. "Theoria Motus Corporum Coelestium." 1809. - Golub, G. & Van Loan, C. "Matrix Computations." 4th edition, Johns Hopkins University Press, 2013. - Press, W.H. et al. "Numerical Recipes: The Art of Scientific Computing." 3rd edition, Cambridge University Press, 2007. Chapter 15 (Modeling of Data). -- Draper, N. & Smith, H. "Applied Regression Analysis." 3rd edition, Wiley, 1998. +- Draper, N. & Smith, H. "Applied Regression Analysis." 3rd edition, Wiley, 1998. \ No newline at end of file diff --git a/lib/statistics/quantile/Quantile.md b/lib/statistics/quantile/Quantile.md index 2b1ac97d..de2b7910 100644 --- a/lib/statistics/quantile/Quantile.md +++ b/lib/statistics/quantile/Quantile.md @@ -13,9 +13,7 @@ | **PineScript** | [quantile.pine](quantile.pine) | - The Rolling Quantile computes the value below which a given fraction of observations fall within a sliding window. -- Parameterized by `period`, `quantilelevel` (default 0.25). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Percentile](../percentile/Percentile.md), [IQR](../iqr/Iqr.md) | **Trading note:** Value at specified quantile; Q(0.5) = median, Q(0.95) = 95th percentile for risk analysis. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -140,4 +138,4 @@ O(N) per update. Linear interpolation between adjacent order statistics matches - Hyndman, R.J. and Fan, Y. (1996). "Sample Quantiles in Statistical Packages." *The American Statistician*, 50(4), 361-365. - Galton, F. (1885). "Some Results of the Anthropometric Laboratory." *Journal of the Anthropological Institute*, 14, 275-287. - Microsoft Excel Documentation: [PERCENTILE.INC function](https://support.microsoft.com/en-us/office/percentile-inc-function-680f9539-45eb-410b-9a5e-c1355e5fe2ed) -- TradingView PineScript Reference: [ta.percentile_linear_interpolation](https://www.tradingview.com/pine-script-reference/v6/) +- TradingView PineScript Reference: [ta.percentile_linear_interpolation](https://www.tradingview.com/pine-script-reference/v6/) \ No newline at end of file diff --git a/lib/statistics/skew/Skew.md b/lib/statistics/skew/Skew.md index 79e0e257..577e8aef 100644 --- a/lib/statistics/skew/Skew.md +++ b/lib/statistics/skew/Skew.md @@ -13,9 +13,7 @@ | **PineScript** | [skew.pine](skew.pine) | - Skewness measures the asymmetry of the probability distribution of a real-valued random variable about its mean. -- Parameterized by `period`, `ispopulation` (default false). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Kurtosis](../kurtosis/Kurtosis.md), [JB](../jb/Jb.md) | **Trading note:** Skewness; positive = right tail, negative = left tail. Negative skew in equity returns = crash risk. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Skewness measures the asymmetry of the probability distribution of a real-valued random variable about its mean. It tells you where the "tail" of the distribution is. @@ -104,4 +102,4 @@ var result = skew.Update(new TValue(DateTime.UtcNow, 105.5)); // Result > 0: Positive skew (tail on right) // Result < 0: Negative skew (tail on left) // Result = 0: Symmetric -Console.WriteLine($"Skewness: {result.Value:F4}"); +Console.WriteLine($"Skewness: {result.Value:F4}"); \ No newline at end of file diff --git a/lib/statistics/spearman/Spearman.md b/lib/statistics/spearman/Spearman.md index ebe54958..d619a054 100644 --- a/lib/statistics/spearman/Spearman.md +++ b/lib/statistics/spearman/Spearman.md @@ -13,9 +13,7 @@ | **PineScript** | [spearman.pine](spearman.pine) | - Spearman's ρ (rho) measures the strength and direction of monotonic association between two variables. -- Parameterized by `period` (default 20). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Correlation](../correlation/Correlation.md), [Kendall](../kendall/Kendall.md) | **Trading note:** Spearman rank correlation; non-parametric, detects monotonic (not just linear) relationships. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Spearman's ρ (rho) measures the strength and direction of monotonic association between two variables. Unlike Pearson's correlation, which measures linear relationship, Spearman captures any monotonic relationship. A portfolio of stocks whose returns move monotonically together has different risk than one whose components merely share a linear trend. Spearman detects both. @@ -165,4 +163,4 @@ No external TA library implements Spearman rank correlation. Validation relies o - Spearman, C. (1904). "The Proof and Measurement of Association between Two Things." *American Journal of Psychology*, 15(1), 72-101. - Kendall, M. G., & Gibbons, J. D. (1990). *Rank Correlation Methods*. 5th ed. Oxford University Press. - Croux, C., & Dehon, C. (2010). "Influence Functions of the Spearman and Kendall Correlation Measures." *Statistical Methods & Applications*, 19(4), 497-515. -- Embrechts, P., McNeil, A., & Straumann, D. (2002). "Correlation and Dependence in Risk Management: Properties and Pitfalls." In *Risk Management: Value at Risk and Beyond*, Cambridge University Press. +- Embrechts, P., McNeil, A., & Straumann, D. (2002). "Correlation and Dependence in Risk Management: Properties and Pitfalls." In *Risk Management: Value at Risk and Beyond*, Cambridge University Press. \ No newline at end of file diff --git a/lib/statistics/stddev/StdDev.md b/lib/statistics/stddev/StdDev.md index 2d5bdaaf..d2a4b018 100644 --- a/lib/statistics/stddev/StdDev.md +++ b/lib/statistics/stddev/StdDev.md @@ -13,9 +13,7 @@ | **PineScript** | [stddev.pine](stddev.pine) | - Standard Deviation measures the amount of variation or dispersion of a set of values. -- Parameterized by `period`, `ispopulation` (default false). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Variance](../variance/Variance.md), [MeanDev](../meandev/MeanDev.md) | **Trading note:** Standard deviation; foundational volatility measure. Used in Bollinger Bands, VaR, and Sharpe ratio. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Standard Deviation measures the amount of variation or dispersion of a set of values. A low standard deviation indicates that the values tend to be close to the mean (also called the expected value) of the set, while a high standard deviation indicates that the values are spread out over a wider range. @@ -96,4 +94,4 @@ var stdDev = new StdDev(20, isPopulation: false); var result = stdDev.Update(new TValue(DateTime.UtcNow, 100.0)); // Get the last value -double value = stdDev.Last.Value; +double value = stdDev.Last.Value; \ No newline at end of file diff --git a/lib/statistics/stderr/Stderr.md b/lib/statistics/stderr/Stderr.md index 9f6ac285..21c5946c 100644 --- a/lib/statistics/stderr/Stderr.md +++ b/lib/statistics/stderr/Stderr.md @@ -13,9 +13,7 @@ | **PineScript** | [stderr.pine](stderr.pine) | - `Stderr` computes the standard error of an OLS regression fit over a rolling window. -- Parameterized by `period`. -- Output range: non-negative real values (or 0 during insufficient/degenerate windows). -- Requires `period` bars of warmup before first stable output (`IsHot = true`). +- **Similar:** [StdDev](../stddev/StdDev.md), [LinReg](../linreg/LinReg.md) | **Trading note:** Standard error; precision of the mean estimate. Decreases with sample size. - Validated against an internal brute-force OLS reference implementation. Standard Error of Regression (also called the Standard Error of the Estimate) measures the average distance that the observed values fall from the regression line. It quantifies the typical size of the residuals, providing a direct measure of how well a linear regression model fits the data. @@ -101,4 +99,4 @@ double value = stderr.Last.Value; ## See Also * **LinReg** — Linear Regression Curve (the trend line itself). -- **StdDev** — Standard Deviation (dispersion from the mean, not from a regression line). +- **StdDev** — Standard Deviation (dispersion from the mean, not from a regression line). \ No newline at end of file diff --git a/lib/statistics/sum/Sum.md b/lib/statistics/sum/Sum.md index 257e1a2f..57caafd2 100644 --- a/lib/statistics/sum/Sum.md +++ b/lib/statistics/sum/Sum.md @@ -13,9 +13,7 @@ | **PineScript** | [sum.pine](sum.pine) | - The Sum indicator calculates a rolling window summation using the Kahan-Babuška algorithm (also known as "improved Kahan" or "second-order compensa... -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Trading note:** Rolling sum; cumulative total over lookback window. Building block for many indicators (e.g., OBV, A/D). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Sum indicator calculates a rolling window summation using the Kahan-Babuška algorithm (also known as "improved Kahan" or "second-order compensated summation") for maximum numerical precision. This approach captures rounding errors that even classic Kahan summation misses, making it suitable for numerical libraries, statistics, and trading applications where precision matters. @@ -206,4 +204,4 @@ source.Add(new TValue(DateTime.UtcNow, 100.0)); * Values are similar magnitude * Sequence length is bounded and small * Maximum throughput is critical -* Using `decimal` type instead +* Using `decimal` type instead \ No newline at end of file diff --git a/lib/statistics/theil/Theil.md b/lib/statistics/theil/Theil.md index eb369f55..470d5ef5 100644 --- a/lib/statistics/theil/Theil.md +++ b/lib/statistics/theil/Theil.md @@ -13,9 +13,7 @@ | **PineScript** | [theil.pine](theil.pine) | - The Theil T Index is an information-theoretic measure of inequality (or concentration) within a distribution of positive values. -- Parameterized by `period`. -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Correlation](../correlation/Correlation.md), [LinReg](../linreg/LinReg.md) | **Trading note:** Theil–Sen estimator; robust slope calculation using medians of pairwise slopes. Resistant to outliers. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -150,4 +148,4 @@ No external TA library implements Theil T Index directly. Validation relies on m - Theil, H. (1967). *Economics and Information Theory*. North-Holland Publishing Company. - Cowell, F.A. (2011). *Measuring Inequality*. Oxford University Press. 3rd edition. - Conceicao, P., & Ferreira, P. (2000). "The Young Person's Guide to the Theil Index." UTIP Working Paper No. 14. -- Shorrocks, A.F. (1980). "The Class of Additively Decomposable Inequality Measures." *Econometrica*, 48(3), 613-625. +- Shorrocks, A.F. (1980). "The Class of Additively Decomposable Inequality Measures." *Econometrica*, 48(3), 613-625. \ No newline at end of file diff --git a/lib/statistics/trim/Trim.md b/lib/statistics/trim/Trim.md index f4fcbb2a..ccac8dfa 100644 --- a/lib/statistics/trim/Trim.md +++ b/lib/statistics/trim/Trim.md @@ -13,9 +13,7 @@ | **PineScript** | [trim.pine](trim.pine) | - The Trimmed Mean Moving Average computes a rolling average after discarding a configurable percentage of the most extreme values from each tail of ... -- Parameterized by `period`, `trimpct` (default 10.0). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Wins](../wins/Wins.md), [Median](../median/Median.md) | **Trading note:** Trimmed mean; excludes extreme percentiles. Robust average for volatile data. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Trimmed Mean Moving Average computes a rolling average after discarding a configurable percentage of the most extreme values from each tail of the sorted lookback window. By removing the lowest and highest `trimPct%` of observations, TRIM eliminates the influence of outliers while retaining more information than a pure median. At `trimPct = 0` it degenerates to the SMA; at `trimPct = 50` it becomes the median. The default 10% trim provides a robust central tendency estimator that resists spike contamination with minimal loss of responsiveness, requiring $O(N \log N)$ for the sort plus $O(N)$ for the summation per bar. @@ -127,4 +125,4 @@ No whole-path SIMD; sort blocks vectorization. Batch is a loop of independent so - Tukey, J.W. "Exploratory Data Analysis." Addison-Wesley, 1977. - Huber, P.J. & Ronchetti, E. "Robust Statistics." 2nd edition, Wiley, 2009. - Wilcox, R.R. "Fundamentals of Modern Statistical Methods." 2nd edition, Springer, 2010. -- Bryan, M. & Cecchetti, S. "Measuring Core Inflation." In Monetary Policy, NBER, 1994. +- Bryan, M. & Cecchetti, S. "Measuring Core Inflation." In Monetary Policy, NBER, 1994. \ No newline at end of file diff --git a/lib/statistics/variance/Variance.md b/lib/statistics/variance/Variance.md index dd030729..7d207515 100644 --- a/lib/statistics/variance/Variance.md +++ b/lib/statistics/variance/Variance.md @@ -13,9 +13,7 @@ | **PineScript** | [variance.pine](variance.pine) | - Variance measures how far a set of numbers is spread out from their average value. -- Parameterized by `period`, `ispopulation` (default false). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [StdDev](../stddev/StdDev.md), [MeanDev](../meandev/MeanDev.md) | **Trading note:** Rolling variance; squared deviation from mean. Foundation of portfolio risk calculations. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Variance measures how far a set of numbers is spread out from their average value. In finance, it is a key measure of volatility and risk. @@ -108,4 +106,4 @@ var variance = new Variance(20, isPopulation: false); var result = variance.Update(new TValue(DateTime.UtcNow, 100.0)); // Access the last calculated value -Console.WriteLine($"Variance: {variance.Last.Value}"); +Console.WriteLine($"Variance: {variance.Last.Value}"); \ No newline at end of file diff --git a/lib/statistics/wavg/Wavg.md b/lib/statistics/wavg/Wavg.md index b04c3133..7a776f3f 100644 --- a/lib/statistics/wavg/Wavg.md +++ b/lib/statistics/wavg/Wavg.md @@ -13,9 +13,7 @@ | **PineScript** | [wavg.pine](wavg.pine) | - The Weighted Average computes a rolling linearly-weighted mean where the most recent observation receives weight $N$ and the oldest receives weight... -- Parameterized by `period`. -- Output range: $0$ to $1$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [WMA](../../trends_FIR/wma/wma.md), [EMA](../../trends_IIR/ema/ema.md) | **Trading note:** Weighted average with custom weights; flexible aggregation for composite indicators. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Weighted Average computes a rolling linearly-weighted mean where the most recent observation receives weight $N$ and the oldest receives weight 1, making it mathematically identical to the Weighted Moving Average (WMA) but categorized as a statistical measure. The implementation uses a circular buffer with an $O(1)$ incremental update scheme: rather than recomputing the full weighted sum each bar, it maintains running sums and adjusts them through add/subtract operations as values enter and exit the window. This makes WAVG one of the most efficient weighted estimators available, with constant per-bar cost regardless of the lookback period. @@ -125,4 +123,4 @@ Batch span path benefits from Vector dot product for the weight applicat - Pring, M.J. "Technical Analysis Explained." 5th edition, McGraw-Hill, 2014. - Murphy, J.J. "Technical Analysis of the Financial Markets." New York Institute of Finance, 1999. - Oppenheim, A.V. & Schafer, R.W. "Discrete-Time Signal Processing." 3rd edition, Pearson, 2010. -- Haykin, S. "Adaptive Filter Theory." 5th edition, Pearson, 2013. +- Haykin, S. "Adaptive Filter Theory." 5th edition, Pearson, 2013. \ No newline at end of file diff --git a/lib/statistics/wins/Wins.md b/lib/statistics/wins/Wins.md index 3ecec826..1beaed22 100644 --- a/lib/statistics/wins/Wins.md +++ b/lib/statistics/wins/Wins.md @@ -13,9 +13,7 @@ | **PineScript** | [wins.pine](wins.pine) | - The Winsorized Mean Moving Average computes a rolling average after replacing (not discarding) the most extreme values in each tail with the bounda... -- Parameterized by `period`, `winpct` (default 10.0). -- Output range: Varies (see docs). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Trim](../trim/Trim.md), [Percentile](../percentile/Percentile.md) | **Trading note:** Winsorized mean; replaces extreme values instead of removing them. Preserves sample size. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Winsorized Mean Moving Average computes a rolling average after replacing (not discarding) the most extreme values in each tail with the boundary values at the trim point. Unlike the trimmed mean (TRIM) which removes outliers entirely, Winsorization preserves the full sample size by clamping extreme values to the nearest non-extreme observation. At `winPct = 0` it degenerates to the SMA; at `winPct = 50` all values equal the median pair. The default 10% Winsorization provides a robust central tendency estimator that dampens outlier impact while maintaining the statistical efficiency advantages of the full sample size. @@ -134,4 +132,4 @@ Sort blocks SIMD on the main path. The sum phase can use Vector for mode - Huber, P.J. & Ronchetti, E. "Robust Statistics." 2nd edition, Wiley, 2009. - Wilcox, R.R. "Introduction to Robust Estimation and Hypothesis Testing." 4th edition, Academic Press, 2017. - Fama, E.F. & French, K.R. "Common Risk Factors in the Returns on Stocks and Bonds." Journal of Financial Economics, 1993. -- Dixon, W.J. & Tukey, J.W. "Approximate Behavior of the Distribution of Winsorized t." Technometrics, 1968. +- Dixon, W.J. & Tukey, J.W. "Approximate Behavior of the Distribution of Winsorized t." Technometrics, 1968. \ No newline at end of file diff --git a/lib/statistics/zscore/Zscore.md b/lib/statistics/zscore/Zscore.md index e32ca4f7..0993087e 100644 --- a/lib/statistics/zscore/Zscore.md +++ b/lib/statistics/zscore/Zscore.md @@ -13,9 +13,7 @@ | **PineScript** | [zscore.pine](zscore.pine) | - The Z-Score measures how many population standard deviations a value lies from the rolling mean over a lookback window. -- Parameterized by `period` (default 14). -- Output range: Unbounded. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Normalize](../../numerics/normalize/Normalize.md), [StdDev](../stddev/StdDev.md) | **Trading note:** Z-score; number of standard deviations from mean. ±2σ indicates unusual move. Mean-reversion signal. - Validated against manual computation, PineScript parity, and statistical invariants. ## Introduction @@ -141,4 +139,4 @@ Z-scores are invariant under positive linear transformations. This property make - Pearson, K. (1894). "Contributions to the Mathematical Theory of Evolution." *Philosophical Transactions of the Royal Society.* - TradingView PineScript Reference: [ta.zscore](https://www.tradingview.com/pine-script-reference/v6/) -- Bollinger, J. (2001). *Bollinger on Bollinger Bands.* McGraw-Hill. (Z-score normalization of Bollinger %B) +- Bollinger, J. (2001). *Bollinger on Bollinger Bands.* McGraw-Hill. (Z-score normalization of Bollinger %B) \ No newline at end of file diff --git a/lib/statistics/ztest/Ztest.md b/lib/statistics/ztest/Ztest.md index 4823db55..b15ae139 100644 --- a/lib/statistics/ztest/Ztest.md +++ b/lib/statistics/ztest/Ztest.md @@ -13,9 +13,7 @@ | **PineScript** | [ztest.pine](ztest.pine) | - ZTEST computes the **one-sample t-statistic**, measuring how many standard errors the rolling sample mean deviates from a hypothesized population m... -- Parameterized by `period` (default 30), `mu0` (default 0.0). -- Output range: Unbounded. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [JB](../jb/Jb.md), [Zscore](../zscore/Zscore.md) | **Trading note:** Z-test; tests if sample mean differs from population mean. Used to validate trading edge significance. - Validated against manual computation, PineScript parity, and testable statistical properties. ## Introduction @@ -140,4 +138,4 @@ No external TA libraries implement a one-sample t-test indicator. Validation is - Student (W.S. Gosset), "The Probable Error of a Mean," *Biometrika*, 6(1), 1908, pp. 1-25 - Fisher, R.A., *Statistical Methods for Research Workers*, Oliver and Boyd, 1925 -- PineScript reference: `ztest.pine` in this directory +- PineScript reference: `ztest.pine` in this directory \ No newline at end of file diff --git a/lib/trends_FIR/alma/Alma.Quantower.cs b/lib/trends_FIR/alma/Alma.Quantower.cs index ab90b40e..083fbb34 100644 --- a/lib/trends_FIR/alma/Alma.Quantower.cs +++ b/lib/trends_FIR/alma/Alma.Quantower.cs @@ -5,7 +5,7 @@ using TradingPlatform.BusinessLayer; namespace QuanTAlib; [SkipLocalsInit] -public class AlmaIndicator : Indicator, IWatchlistIndicator +public sealed class AlmaIndicator : Indicator, IWatchlistIndicator { [InputParameter("Period", sortIndex: 1, 1, 1000, 1, 0)] public int Period { get; set; } = 9; @@ -22,32 +22,33 @@ public class AlmaIndicator : Indicator, IWatchlistIndicator [InputParameter("Show cold values", sortIndex: 21)] public bool ShowColdValues { get; set; } = true; - private Alma ma = null!; - protected LineSeries Series; - protected string SourceName = null!; + private Alma _ma = null!; + private readonly LineSeries _series; + private string _sourceName = null!; private Func _priceSelector = null!; public static int MinHistoryDepths => 0; int IWatchlistIndicator.MinHistoryDepths => MinHistoryDepths; - public override string ShortName => $"ALMA {Period}:{SourceName}"; - public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends/alma/Alma.Quantower.cs"; + public override string ShortName => $"ALMA {Period}:{_sourceName}"; + public override string SourceCodeLink => "https://github.com/mihakralj/QuanTAlib/blob/main/lib/trends_FIR/alma/Alma.Quantower.cs"; public AlmaIndicator() { OnBackGround = true; SeparateWindow = false; - SourceName = Source.ToString(); + _sourceName = Source.ToString(); Name = "ALMA - Arnaud Legoux Moving Average"; - Description = "Arnaud Legoux Moving Average"; - Series = new LineSeries(name: $"ALMA {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid); - AddLineSeries(Series); + Description = "Arnaud Legoux Moving Average with Gaussian weighting"; + _series = new LineSeries(name: $"ALMA {Period}", color: IndicatorExtensions.Averages, width: 2, style: LineStyle.Solid); + AddLineSeries(_series); } + [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override void OnInit() { - ma = new Alma(Period, Offset, Sigma); - SourceName = Source.ToString(); + _ma = new Alma(Period, Offset, Sigma); + _sourceName = Source.ToString(); _priceSelector = Source.GetPriceSelector(); base.OnInit(); } @@ -55,10 +56,15 @@ public class AlmaIndicator : Indicator, IWatchlistIndicator [MethodImpl(MethodImplOptions.AggressiveInlining)] protected override void OnUpdate(UpdateArgs args) { + if (args.Reason != UpdateReason.NewBar && args.Reason != UpdateReason.HistoricalBar && args.Reason != UpdateReason.NewTick) + { + return; + } + var item = HistoricalData[Count - 1, SeekOriginHistory.Begin]; + TValue result = _ma.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), args.IsNewBar()); - TValue result = ma.Update(new TValue(item.TimeLeft.Ticks, _priceSelector(item)), isNew: args.IsNewBar()); - - Series.SetValue(result.Value, ma.IsHot, ShowColdValues); + _series.SetValue(result.Value, _ma.IsHot, ShowColdValues); + _series.SetMarker(0, Color.Transparent); } } diff --git a/lib/trends_FIR/alma/Alma.cs b/lib/trends_FIR/alma/Alma.cs index d2d263b8..9363ea0c 100644 --- a/lib/trends_FIR/alma/Alma.cs +++ b/lib/trends_FIR/alma/Alma.cs @@ -1,6 +1,7 @@ -using System.Buffers; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; +using System.Runtime.Intrinsics; +using System.Runtime.Intrinsics.X86; namespace QuanTAlib; @@ -8,10 +9,12 @@ namespace QuanTAlib; /// ALMA: Arnaud Legoux Moving Average /// /// -/// Gaussian-weighted MA with adjustable offset and sigma for responsiveness control. -/// Higher offset (0-1) = more responsive; higher sigma = sharper weights. +/// Gaussian-weighted FIR filter with configurable offset and sigma parameters. +/// The offset controls the peak of the Gaussian (0 = leftmost, 1 = rightmost). +/// The sigma controls the width of the Gaussian curve. /// -/// Calculation: W_i = exp(-(i - m)² / (2s²)) where m = offset × (period-1). +/// Calculation: ALMA = Σ(w_i × P_i) / Σ(w_i) where w_i = exp(-((i - m)²) / (2s²)), +/// m = offset × (period - 1), s = period / sigma. /// /// Detailed documentation [SkipLocalsInit] @@ -21,152 +24,148 @@ public sealed class Alma : AbstractBase private readonly double _offset; private readonly double _sigma; private readonly double[] _weights; - private readonly double _invWeightSum; private readonly RingBuffer _buffer; private readonly ITValuePublisher? _source; - private readonly TValuePublishedHandler? _pubHandler; - private bool _isNew = true; + private readonly TValuePublishedHandler? _handler; private bool _disposed; [StructLayout(LayoutKind.Auto)] - private record struct State(double LastValidValue, bool IsInitialized); + private record struct State(double LastInput, double LastValidValue, bool HasSeenValidData); private State _state; private State _pState; - public bool IsNew => _isNew; - public override bool IsHot => _buffer.IsFull; + /// + /// Default value to use for LastValidValue when no valid data has been seen yet. + /// Defaults to double.NaN to avoid silently introducing zeros. + /// + public double DefaultLastValidValue { get; set; } = double.NaN; /// - /// Creates ALMA with specified parameters. + /// Initializes a new instance of the class. /// - /// Window size (must be > 0) - /// Gaussian offset (0-1, default 0.85). Closer to 1 makes it more responsive. - /// Standard deviation (default 6). Higher values make it sharper. + /// The lookback window size. Must be greater than 0. + /// The Gaussian peak offset (0.0 to 1.0). Default: 0.85. + /// The Gaussian width divisor. Default: 6.0. public Alma(int period, double offset = 0.85, double sigma = 6.0) { if (period <= 0) { throw new ArgumentException("Period must be greater than 0", nameof(period)); } - - if (sigma <= 0) + if (offset < 0.0 || offset > 1.0) + { + throw new ArgumentOutOfRangeException(nameof(offset), offset, "Offset must be between 0.0 and 1.0"); + } + if (sigma <= 0.0) { throw new ArgumentException("Sigma must be greater than 0", nameof(sigma)); } - if (offset < 0 || offset > 1) - { - throw new ArgumentOutOfRangeException(nameof(offset), "Offset must be between 0 and 1"); - } - _period = period; _offset = offset; _sigma = sigma; _buffer = new RingBuffer(period); - _weights = new double[period]; - Name = $"Alma({period}, {offset:F2}, {sigma:F2})"; + _weights = ComputeNormalizedWeights(period, offset, sigma); + Name = $"Alma({period},{offset:F2},{sigma:F1})"; WarmupPeriod = period; - - ComputeWeights(_weights, period, offset, sigma, out _invWeightSum); - _state = new State(double.NaN, IsInitialized: false); } + /// + /// Initializes a new instance of the class with a source publisher. + /// public Alma(ITValuePublisher source, int period, double offset = 0.85, double sigma = 6.0) : this(period, offset, sigma) { _source = source; - _pubHandler = Handle; - _source.Pub += _pubHandler; + _handler = Handle; + source.Pub += _handler; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew); - protected override void Dispose(bool disposing) { if (!_disposed) { - if (disposing && _source != null && _pubHandler != null) + if (disposing && _source != null && _handler != null) { - _source.Pub -= _pubHandler; + _source.Pub -= _handler; } _disposed = true; } base.Dispose(disposing); } - /// - /// Computes Gaussian weights for ALMA. - /// - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void ComputeWeights(Span weights, int period, double offset, double sigma, out double invWeightSum) - { - double m = offset * (period - 1); - double s = period / sigma; - double s2 = 2 * s * s; - double sum = 0; - - for (int i = 0; i < period; i++) - { - double v = i - m; - double w = Math.Exp(-(v * v) / s2); - weights[i] = w; - sum += w; - } - - invWeightSum = 1.0 / sum; - } + public override bool IsHot => _buffer.IsFull; + public bool IsNew { get; private set; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private double GetValidValue(double input) { if (double.IsFinite(input)) { + _state.LastValidValue = input; + _state.HasSeenValidData = true; return input; } - return _state.IsInitialized ? _state.LastValidValue : double.NaN; + return _state.HasSeenValidData ? _state.LastValidValue : DefaultLastValidValue; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private double CalculateWeightedSum() + { + double result = 0; + int count = _buffer.Count; + int weightOffset = _period - count; + int idx = 0; + + foreach (double item in _buffer) + { + result = Math.FusedMultiplyAdd(_weights[weightOffset + idx], item, result); + idx++; + } + + // Normalize for partial windows + if (count < _period) + { + double wSum = 0; + for (int i = weightOffset; i < _period; i++) + { + wSum += _weights[i]; + } + return wSum > 0 ? result / wSum : result; + } + + return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override TValue Update(TValue input, bool isNew = true) { - _isNew = isNew; - return Update(input, isNew, publish: true); - } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private TValue Update(TValue input, bool isNew, bool publish) - { + IsNew = isNew; if (isNew) { + double val = GetValidValue(input.Value); + _buffer.Add(val); + _state.LastInput = val; + _pState = _state; } else { + if (_buffer.Count == 0) + { + throw new InvalidOperationException( + "Cannot call Update with isNew=false when buffer is empty. " + + "The first update must have isNew=true to initialize state."); + } + _state = _pState; + double val = GetValidValue(input.Value); + _buffer.UpdateNewest(val); } - if (double.IsFinite(input.Value)) - { - _state = _state with { LastValidValue = input.Value, IsInitialized = true }; - } - - // Retrieve valid value (handles NaN propagation prevention) - double val = GetValidValue(input.Value); - - _buffer.Add(val, isNew); - - double result = 0; - if (_buffer.Count > 0) - { - result = CalculateWeightedSum(); - } - + double result = CalculateWeightedSum(); Last = new TValue(input.Time, result); - if (publish) - { - PubEvent(Last, isNew); - } + PubEvent(Last, isNew); return Last; } @@ -174,7 +173,7 @@ public sealed class Alma : AbstractBase { if (source.Count == 0) { - return new TSeries([], []); + return []; } int len = source.Count; @@ -189,20 +188,14 @@ public sealed class Alma : AbstractBase Batch(source.Values, vSpan, _period, _offset, _sigma); source.Times.CopyTo(tSpan); - // Restore state - _buffer.Clear(); - _state = default; - - // Replay last part to restore buffer state - int startIndex = Math.Max(0, len - _period); - for (int i = startIndex; i < len; i++) - { - Update(source[i], isNew: true, publish: false); - } + Prime(source.Values); + Last = new TValue(tSpan[len - 1], vSpan[len - 1]); return new TSeries(t, v); } + private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew); + public override void Prime(ReadOnlySpan source, TimeSpan? step = null) { if (source.Length == 0) @@ -210,246 +203,201 @@ public sealed class Alma : AbstractBase return; } - // Reset state - _buffer.Clear(); - _state = default; - _pState = default; + int len = source.Length; + int windowSize = Math.Min(len, _period); + int startIndex = len - windowSize; - int warmupLength = Math.Min(source.Length, WarmupPeriod); - int startIndex = source.Length - warmupLength; - - // Seed LastValidValue from history before warmup window - double lastValid = double.NaN; - for (int i = startIndex - 1; i >= 0; i--) + // Seed LastValidValue + _state.LastValidValue = DefaultLastValidValue; + _state.HasSeenValidData = false; + if (startIndex > 0) { - if (double.IsFinite(source[i])) - { - lastValid = source[i]; - break; - } - } - - // If not found, search in warmup window - if (double.IsNaN(lastValid)) - { - for (int i = startIndex; i < source.Length; i++) + for (int i = startIndex - 1; i >= 0; i--) { if (double.IsFinite(source[i])) { - lastValid = source[i]; + _state.LastValidValue = source[i]; + _state.HasSeenValidData = true; break; } } } - // Initialize state with seeded LastValidValue - if (double.IsFinite(lastValid)) + // Reset buffer and process window + _buffer.Clear(); + for (int i = startIndex; i < len; i++) { - _state = new State(lastValid, IsInitialized: true); + double val = GetValidValue(source[i]); + _buffer.Add(val); + _state.LastInput = val; } - // Feed the warmup data - for (int i = startIndex; i < source.Length; i++) - { - Update(new TValue(DateTime.MinValue, source[i]), isNew: true, publish: false); - } + // Calculate Last + double result = CalculateWeightedSum(); + Last = new TValue(DateTime.MinValue, result); _pState = _state; } - [MethodImpl(MethodImplOptions.AggressiveInlining)] - private double CalculateWeightedSum() + public override void Reset() { - int count = _buffer.Count; - if (count == 0) - { - return 0; - } - - if (count < _period) - { - // Partial buffer: align newest with newest - // Buffer[0] (oldest) -> Weights[period - count] - ReadOnlySpan bufferSpan = _buffer.GetSpan(); - int weightOffset = _period - count; - - // Use DotProduct for partial sum - double sum = bufferSpan.DotProduct(_weights.AsSpan(weightOffset, count)); - - // Calculate weightSum for this subset - double wSum = 0; - for (int i = 0; i < count; i++) - { - wSum += _weights[weightOffset + i]; - } - - return wSum > 0 ? sum / wSum : 0; - } - - // Full buffer: use precomputed _weightSum and SIMD DotProduct - // We use InternalBuffer and StartIndex to avoid allocation and handle wrapping - ReadOnlySpan internalBuf = _buffer.InternalBuffer; - int head = _buffer.StartIndex; - - // Part 1: Oldest to End of Buffer -> InternalBuffer[Head ... Cap-1] - // Matches Weights[0 ... Cap-Head-1] - int part1Len = _period - head; - double sum1 = internalBuf.Slice(head, part1Len).DotProduct(_weights.AsSpan(0, part1Len)); - - // Part 2: Start of Buffer to Newest -> InternalBuffer[0 ... Head-1] - // Matches Weights[Cap-Head ... Cap-1] - double sum2 = internalBuf[..head].DotProduct(_weights.AsSpan(part1Len)); - - return (sum1 + sum2) * _invWeightSum; + _buffer.Clear(); + _state = default; + _pState = default; + Last = default; } + /// + /// Computes ALMA for a TSeries using batch processing. + /// public static TSeries Batch(TSeries source, int period, double offset = 0.85, double sigma = 6.0) { var alma = new Alma(period, offset, sigma); return alma.Update(source); } + /// + /// Computes ALMA for raw spans using batch processing. + /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - public static void Batch(ReadOnlySpan source, Span output, int period, double offset = 0.85, double sigma = 6.0) + public static void Batch(ReadOnlySpan source, Span output, int period, + double offset = 0.85, double sigma = 6.0) { if (period <= 0) { throw new ArgumentException("Period must be greater than 0", nameof(period)); } - - if (sigma <= 0) + if (sigma <= 0.0) { throw new ArgumentException("Sigma must be greater than 0", nameof(sigma)); } - - if (offset < 0 || offset > 1) + if (offset < 0.0 || offset > 1.0) { - throw new ArgumentOutOfRangeException(nameof(offset), "Offset must be between 0 and 1"); + throw new ArgumentOutOfRangeException(nameof(offset), offset, "Offset must be between 0.0 and 1.0"); } - if (source.Length != output.Length) { throw new ArgumentException("Source and output must have the same length", nameof(output)); } - // Allocation Strategy: Stack for small periods, Pool for large - double[]? weightsArray = period > 256 ? ArrayPool.Shared.Rent(period) : null; - Span weights = period <= 256 - ? stackalloc double[period] - : weightsArray!.AsSpan(0, period); - - double[]? bufferArray = period > 256 ? ArrayPool.Shared.Rent(period) : null; - Span buffer = period <= 256 - ? stackalloc double[period] - : bufferArray!.AsSpan(0, period); - - // Precompute weights using shared helper - ComputeWeights(weights, period, offset, sigma, out double invWeightSum); - - int bufferIdx = 0; - int count = 0; - double lastValid = double.NaN; // Start with NaN to detect first valid value - double currentWeightSum = 0; - - try + int len = source.Length; + if (len == 0) { - for (int i = 0; i < source.Length; i++) - { - double val = source[i]; - - // Strict NaN handling: maintain NaN until first valid value - if (double.IsFinite(val)) - { - lastValid = val; - } - else if (double.IsFinite(lastValid)) - { - val = lastValid; - } - else - { - val = 0.0; // Fallback if series starts with NaN - } - - // Add to circular buffer - buffer[bufferIdx] = val; - bufferIdx = (bufferIdx + 1) % period; - - if (count < period) - { - count++; - // Incremental weight sum update for warmup - currentWeightSum += weights[period - count]; - } - - double sum = 0; - - if (count == period) - { - // Buffer is full. bufferIdx points to the oldest element (next write position) - // Split the dot product to handle circular buffer wrap-around - - int part1Len = period - bufferIdx; - - // Part 1: Oldest data (at bufferIdx..End) * Start of Weights - sum += buffer.Slice(bufferIdx, part1Len).DotProduct(weights.Slice(0, part1Len)); - - // Part 2: Newest data (at 0..bufferIdx) * End of Weights - sum += buffer.Slice(0, bufferIdx).DotProduct(weights.Slice(part1Len)); - - output[i] = sum * invWeightSum; - } - else - { - // Partial buffer - int startIdx = (bufferIdx - count + period) % period; - int weightOffset = period - count; - - if (startIdx + count <= period) - { - // Contiguous in buffer - sum = buffer.Slice(startIdx, count).DotProduct(weights.Slice(weightOffset, count)); - } - else - { - // Wrapped in buffer - int part1Len = period - startIdx; - int part2Len = count - part1Len; - - sum = buffer.Slice(startIdx, part1Len).DotProduct(weights.Slice(weightOffset, part1Len)); - sum += buffer.Slice(0, part2Len).DotProduct(weights.Slice(weightOffset + part1Len, part2Len)); - } - - output[i] = currentWeightSum > 0 ? sum / currentWeightSum : 0; - } - } + return; } - finally - { - if (weightsArray != null) - { - ArrayPool.Shared.Return(weightsArray); - } - if (bufferArray != null) - { - ArrayPool.Shared.Return(bufferArray); - } - } + CalculateScalarCore(source, output, period, offset, sigma); } - public static (TSeries Results, Alma Indicator) Calculate(TSeries source, int period, double offset = 0.85, double sigma = 6.0) + /// + /// Computes ALMA and returns both the result series and a warmed-up indicator instance. + /// + public static (TSeries Results, Alma Indicator) Calculate(TSeries source, int period, + double offset = 0.85, double sigma = 6.0) { var indicator = new Alma(period, offset, sigma); TSeries results = indicator.Update(source); return (results, indicator); } - public override void Reset() + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void CalculateScalarCore(ReadOnlySpan source, Span output, + int period, double offset, double sigma) { - _buffer.Clear(); - _state = new State(double.NaN, IsInitialized: false); - _pState = _state; - Last = default; + int len = source.Length; + double[] weights = ComputeNormalizedWeights(period, offset, sigma); + double lastValid = double.NaN; + + Span buffer = period <= 512 ? stackalloc double[period] : new double[period]; + int bufferCount = 0; + int bufferIdx = 0; + + for (int i = 0; i < len; i++) + { + double val = source[i]; + if (double.IsFinite(val)) + { + lastValid = val; + } + else + { + val = lastValid; + } + + // Add to circular buffer + buffer[bufferIdx] = val; + bufferIdx++; + if (bufferIdx >= period) + { + bufferIdx = 0; + } + if (bufferCount < period) + { + bufferCount++; + } + + // Compute weighted sum + double result = 0; + int weightOffset = period - bufferCount; + + if (bufferCount == period) + { + // Full window — iterate from oldest to newest + int readIdx = bufferIdx; // bufferIdx now points to oldest + for (int k = 0; k < period; k++) + { + result = Math.FusedMultiplyAdd(weights[k], buffer[readIdx], result); + readIdx++; + if (readIdx >= period) + { + readIdx = 0; + } + } + } + else + { + // Partial window — use tail weights + double wSum = 0; + for (int k = 0; k < bufferCount; k++) + { + int wi = weightOffset + k; + result = Math.FusedMultiplyAdd(weights[wi], buffer[k], result); + wSum += weights[wi]; + } + result = wSum > 0 ? result / wSum : result; + } + + output[i] = result; + } + } + + /// + /// Pre-computes normalized Gaussian weights for the ALMA filter. + /// Weights are normalized so that their sum equals 1.0. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static double[] ComputeNormalizedWeights(int period, double offset, double sigma) + { + double[] w = new double[period]; + double m = offset * (period - 1); + double s = period / sigma; + double s2 = 2.0 * s * s; + double wSum = 0; + + for (int i = 0; i < period; i++) + { + double d = i - m; + w[i] = Math.Exp(-(d * d) / s2); + wSum += w[i]; + } + + // Normalize weights to sum to 1.0 + double invSum = 1.0 / wSum; + for (int i = 0; i < period; i++) + { + w[i] *= invSum; + } + + return w; } } diff --git a/lib/trends_FIR/alma/Alma.md b/lib/trends_FIR/alma/Alma.md index f3418b85..be6d7180 100644 --- a/lib/trends_FIR/alma/Alma.md +++ b/lib/trends_FIR/alma/Alma.md @@ -14,10 +14,8 @@ | **Signature** | [alma_signature](alma_signature.md) | - ALMA is a Finite Impulse Response (FIR) filter that applies a Gaussian window to price data. -- Parameterized by `period`, `offset` (default 0.85), `sigma` (default 6.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). -- Validated against TA-Lib, Skender, and Tulip reference implementations where available. +- **Similar:** [FWMA](../fwma/fwma.md), [SinEma](../sinema/sinema.md) | **Complementary:** ATR for volatility filter | **Trading note:** Gaussian-weighted FIR filter; offset parameter controls responsiveness vs smoothness tradeoff. +- Validated against Skender, Ooples, and Pandas-TA reference implementations. ALMA is a Finite Impulse Response (FIR) filter that applies a Gaussian window to price data. Unlike the Simple Moving Average (which treats 10-minute-old data with the same reverence as 1-minute-old data) or the Exponential Moving Average (which holds onto history like a hoarder), ALMA allows you to shape the weight distribution precisely. It lets you define the trade-off between smoothness and lag using standard deviation ($\sigma$) and offset, rather than arbitrary periods. @@ -180,4 +178,4 @@ QuanTAlib validates against reference implementations that respect the Gaussian * $\sigma = 1$: The curve is flat. You have reinvented the Simple Moving Average (badly). * $\sigma = 10$: The curve is a needle. You are sampling one specific bar in history. -3. **Cold Start**: ALMA requires a full window ($L$) to be mathematically valid. First $L-1$ bars are convergence noise. Ignore them. +3. **Cold Start**: ALMA requires a full window ($L$) to be mathematically valid. First $L-1$ bars are convergence noise. Ignore them. \ No newline at end of file diff --git a/lib/trends_FIR/blma/Blma.md b/lib/trends_FIR/blma/Blma.md index b9e756f4..d71987f8 100644 --- a/lib/trends_FIR/blma/Blma.md +++ b/lib/trends_FIR/blma/Blma.md @@ -13,11 +13,10 @@ | **PineScript** | [blma.pine](blma.pine) | | **Signature** | [blma_signature](blma_signature.md) | -- The Blackman Window Moving Average (BLMA) applies a triple-cosine window function from digital signal processing to financial time series. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). -- Validated against TA-Lib, Skender, and Tulip reference implementations where available. +- BLMA is a FIR filter that applies a triple-cosine Blackman window function from digital signal processing to financial time series. +- Best suited as a long-term trend filter due to its superior noise suppression (-58 dB sidelobes) at the cost of ~N/2 lag. +- **Similar:** [WMA](../wma/wma.md), [TRIMA](../trima/trima.md) | **Complementary:** Trend confirmation | **Trading note:** Blackman-windowed MA; low sidelobe leakage for clean spectral response. +- Validated against reference implementations using the standard Blackman window formula. The Blackman Window Moving Average (BLMA) applies a triple-cosine window function from digital signal processing to financial time series. Originally developed by **Ralph Beebe Blackman** at Bell Labs in the 1950s for spectral analysis, this filter provides superior noise suppression compared to standard moving averages by minimizing spectral leakage. @@ -119,4 +118,4 @@ BLMA is validated against a reference implementation using the standard Blackman ### Common Pitfalls * **Lag**: BLMA has more lag than EMA or WMA because it suppresses the most recent data. It is a smoothing filter, not a leading indicator. -* **Warmup**: During the first $N$ bars, the window expands dynamically. The full noise-suppression characteristics are only achieved after $N$ bars. +* **Warmup**: During the first $N$ bars, the window expands dynamically. The full noise-suppression characteristics are only achieved after $N$ bars. \ No newline at end of file diff --git a/lib/trends_FIR/bwma/Bwma.md b/lib/trends_FIR/bwma/Bwma.md index 9c39c063..dfa9de4d 100644 --- a/lib/trends_FIR/bwma/Bwma.md +++ b/lib/trends_FIR/bwma/Bwma.md @@ -14,9 +14,7 @@ | **Signature** | [bwma_signature](bwma_signature.md) | - BWMA is a Finite Impulse Response (FIR) filter that applies a Bessel-derived window function to weight price data. -- Parameterized by `period`, `order` (default 0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [GWMA](../gwma/gwma.md), [HanMA](../hanma/hanma.md) | **Complementary:** ATR for volatility | **Trading note:** Blackman-Window MA; FIR filter with Blackman taper. Good spectral leakage suppression. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. BWMA is a Finite Impulse Response (FIR) filter that applies a Bessel-derived window function to weight price data. The weighting follows a parabolic (or higher-order polynomial) profile that emphasizes the center of the lookback window while smoothly tapering to zero at the edges. Unlike rectangular (SMA) or exponential (EMA) weighting, BWMA provides a mathematically smooth transition that reduces spectral leakage and Gibbs phenomenon artifacts. @@ -216,4 +214,4 @@ Self-consistency validation ensures: * [ALMA](../alma/Alma.md) - Gaussian window with adjustable offset * [WMA](../wma/Wma.md) - Linear weighting (triangular window) -* [SINEMA](../sinema/Sinema.md) - Sine-weighted moving average +* [SINEMA](../sinema/Sinema.md) - Sine-weighted moving average \ No newline at end of file diff --git a/lib/trends_FIR/conv/Conv.md b/lib/trends_FIR/conv/Conv.md index 8d7954f3..f8145f93 100644 --- a/lib/trends_FIR/conv/Conv.md +++ b/lib/trends_FIR/conv/Conv.md @@ -13,9 +13,7 @@ | **PineScript** | [conv.pine](conv.pine) | - CONV (Convolution Moving Average) is the ultimate tool for the signal processing purist. -- Parameterized by double[] kernel. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SMA](../sma/Sma.md), [ALMA](../alma/alma.md) | **Trading note:** Convolution operator; applies custom kernel to price. Foundation of all FIR moving averages. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. CONV (Convolution Moving Average) is the ultimate tool for the signal processing purist. It doesn't presume to know what kind of smoothing you need; it simply asks for a kernel (a set of weights) and applies it to the data. Want a Gaussian filter? A Sinc filter? A custom edge-detection filter? CONV runs them all. @@ -112,4 +110,4 @@ Validation is performed by reproducing standard moving averages (SMA, WMA, TRIMA 1. **Kernel Direction**: Our implementation applies the kernel such that the last element of the kernel multiplies the most recent data point. If you import kernels from other DSP libraries, you might need to reverse them. 2. **Normalization**: Kernel weights are *not* automatically normalized. If the sum of the weights is not 1.0, the output scale will be different from the input scale. This is a feature, not a bug (allows for differential filters). -3. **Performance**: A kernel size of 1000 will be 100x slower than a kernel size of 10. Use FFT-based convolution for massive kernels (not implemented here; this is for trading, not searching for extraterrestrial life). +3. **Performance**: A kernel size of 1000 will be 100x slower than a kernel size of 10. Use FFT-based convolution for massive kernels (not implemented here; this is for trading, not searching for extraterrestrial life). \ No newline at end of file diff --git a/lib/trends_FIR/crma/Crma.md b/lib/trends_FIR/crma/Crma.md index 79b381b6..e07398d4 100644 --- a/lib/trends_FIR/crma/Crma.md +++ b/lib/trends_FIR/crma/Crma.md @@ -14,9 +14,7 @@ | **Signature** | [crma_signature](crma_signature.md) | - CRMA fits a degree-3 polynomial $y = a_0 + a_1 x + a_2 x^2 + a_3 x^3$ to the most recent $N$ bars via ordinary least squares, then returns the fitt... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SMA](../sma/Sma.md), [TrIMA](../trima/trima.md) | **Complementary:** Trend strength indicators | **Trading note:** Cubic-Root weighted MA; gentle weighting profile between uniform (SMA) and triangular (TrIMA). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. CRMA fits a degree-3 polynomial $y = a_0 + a_1 x + a_2 x^2 + a_3 x^3$ to the most recent $N$ bars via ordinary least squares, then returns the fitted endpoint value $a_0$. By capturing inflection and curvature that linear and quadratic models miss, CRMA tracks S-shaped reversals and accelerating trends with measurably lower endpoint error than LSMA or QRMA on non-stationary price series. The cost is a 4x4 linear system solve per bar, which is O(1) once power sums are accumulated in O(N). @@ -132,4 +130,4 @@ O(N) per bar. For default N = 14: ~347 cycles. Resync re-computes sums every 100 | 4×4 Gaussian elimination | No | Fixed scalar 64-op system; not worth SIMD setup | | Polynomial evaluation | No | 4-term Horner; scalar is fastest for degree 3 | -Batch throughput for the sum and cross-product phases: AVX2 achieves ~4× scalar. Gaussian elimination and Horner evaluation remain scalar. Net batch speedup for N = 14, large series: approximately 2.5× over fully scalar. +Batch throughput for the sum and cross-product phases: AVX2 achieves ~4× scalar. Gaussian elimination and Horner evaluation remain scalar. Net batch speedup for N = 14, large series: approximately 2.5× over fully scalar. \ No newline at end of file diff --git a/lib/trends_FIR/dwma/Dwma.md b/lib/trends_FIR/dwma/Dwma.md index 36ad7c15..b782f2dd 100644 --- a/lib/trends_FIR/dwma/Dwma.md +++ b/lib/trends_FIR/dwma/Dwma.md @@ -14,9 +14,7 @@ | **Signature** | [dwma_signature](dwma_signature.md) | - DWMA (Double Weighted Moving Average) is exactly what it says on the tin: a Weighted Moving Average of a Weighted Moving Average. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `(period * 2) - 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [WMA](../wma/wma.md), [FWMA](../fwma/fwma.md) | **Complementary:** Volume confirmation | **Trading note:** Distance-Weighted MA; assigns weights based on distance from current bar. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. DWMA (Double Weighted Moving Average) is exactly what it says on the tin: a Weighted Moving Average of a Weighted Moving Average. Unlike DEMA, which tries to *remove* lag, DWMA accepts lag as the price of admission for superior noise reduction. It produces a curve that is incredibly smooth, ideal for identifying long-term trends without getting faked out by market chop. @@ -98,4 +96,4 @@ Validated against chained WMA implementations in standard libraries. 1. **Lag**: This indicator lags. A lot. Do not use it for entry signals on tight timeframes. Use it for trend filtering (e.g., "only buy if price > DWMA"). 2. **Warmup**: It takes roughly $2 \times N$ bars to produce valid data. -3. **Confusion with DEMA**: DEMA = Fast, DWMA = Smooth. Do not mix them up. +3. **Confusion with DEMA**: DEMA = Fast, DWMA = Smooth. Do not mix them up. \ No newline at end of file diff --git a/lib/trends_FIR/fwma/Fwma.md b/lib/trends_FIR/fwma/Fwma.md index ffc1b758..0cc48ad3 100644 --- a/lib/trends_FIR/fwma/Fwma.md +++ b/lib/trends_FIR/fwma/Fwma.md @@ -14,9 +14,7 @@ | **Signature** | [fwma_signature](fwma_signature.md) | - The Fibonacci Weighted Moving Average applies the Fibonacci sequence as FIR filter weights, assigning exponentially growing importance to recent bars. -- Parameterized by `period` (default 10). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [WMA](../wma/wma.md), [DWMA](../dwma/dwma.md) | **Complementary:** Trend strength indicators | **Trading note:** Fibonacci-Weighted MA; weights follow Fibonacci sequence, naturally emphasizing recent data. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Fibonacci Weighted Moving Average applies the Fibonacci sequence as FIR filter weights, assigning exponentially growing importance to recent bars. Where WMA uses linear weights (1, 2, 3, ..., N) and PWMA uses parabolic weights ($1^2, 2^2, ..., N^2$), FWMA uses F(1), F(2), ..., F(N). The Fibonacci growth rate ($\phi \approx 1.618$) produces a weighting profile between exponential and parabolic, giving FWMA a distinctive "golden ratio decay" that concentrates roughly 61.8% of total weight in the most recent third of the window. @@ -196,4 +194,4 @@ For small periods ($N \leq 8$), a single AVX2 register can hold the entire weigh - Fischer, R. (1993). *Fibonacci Applications and Strategies for Traders*. Wiley. - Koshy, T. (2001). *Fibonacci and Lucas Numbers with Applications*. Wiley. - everget (2018). "Fibonacci Weighted Moving Average." TradingView open-source indicator. -- Binet, J. P. M. (1843). "Mémoire sur l'intégration des équations linéaires aux différences finies." *Comptes Rendus*, 17, 563-567. +- Binet, J. P. M. (1843). "Mémoire sur l'intégration des équations linéaires aux différences finies." *Comptes Rendus*, 17, 563-567. \ No newline at end of file diff --git a/lib/trends_FIR/gwma/Gwma.md b/lib/trends_FIR/gwma/Gwma.md index caaaa032..d192f819 100644 --- a/lib/trends_FIR/gwma/Gwma.md +++ b/lib/trends_FIR/gwma/Gwma.md @@ -13,11 +13,12 @@ | **PineScript** | [gwma.pine](gwma.pine) | | **Signature** | [gwma_signature](gwma_signature.md) | -- GWMA is a Finite Impulse Response (FIR) filter that applies a centered Gaussian window to price data. -- Parameterized by `period`, `sigma` (default 0.4). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). -- Validated against TA-Lib, Skender, and Tulip reference implementations where available. +- GWMA is a symmetric FIR filter applying a centered Gaussian window to price data, providing optimal noise reduction with zero phase distortion at the cost of fixed lag equal to half the window length. +- Similar to [ALMA](../alma/Alma.md) (offset Gaussian), [SINEMA](../sinema/Sinema.md) (sine window), and [Kaiser](../kaiser/Kaiser.md) — all windowed FIR filters with different smoothing profiles. +- Pair with RSI or Stochastic to confirm trend strength; GWMA excels at defining trend direction but not momentum. +- The sigma parameter controls weight concentration: lower sigma sharpens the center peak for cycle detection, higher sigma broadens toward SMA-like behavior. +- **Similar:** [ALMA](../alma/alma.md), [WMA](../wma/wma.md) | **Complementary:** Volume indicators | **Trading note:** Gaussian-Weighted MA; bell-curve weights for symmetric smoothing. +- Validated against mathematical definition and PineScript reference implementation. GWMA is a Finite Impulse Response (FIR) filter that applies a centered Gaussian window to price data. Unlike ALMA (which allows shifting the Gaussian peak via an offset parameter), GWMA centers the bell curve at the middle of the lookback window. The sigma parameter controls the width of the Gaussian, determining how sharply the weights decay from the center. @@ -209,4 +210,4 @@ QuanTAlib validates GWMA against its mathematical definition and internal consis 3. **Cold Start**: GWMA requires a full window ($L$) to be mathematically valid. First $L-1$ bars are convergence noise. -4. **Centered vs Offset**: Don't confuse GWMA with ALMA. GWMA always centers the Gaussian; ALMA lets you shift it. If you find yourself wanting offset control, use ALMA instead. +4. **Centered vs Offset**: Don't confuse GWMA with ALMA. GWMA always centers the Gaussian; ALMA lets you shift it. If you find yourself wanting offset control, use ALMA instead. \ No newline at end of file diff --git a/lib/trends_FIR/hamma/Hamma.md b/lib/trends_FIR/hamma/Hamma.md index f3fc02ea..bc00fa9b 100644 --- a/lib/trends_FIR/hamma/Hamma.md +++ b/lib/trends_FIR/hamma/Hamma.md @@ -14,9 +14,7 @@ | **Signature** | [hamma_signature](hamma_signature.md) | - HAMMA is a Finite Impulse Response (FIR) filter that applies a Hamming window to price data. -- Parameterized by `period` (default 10). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HanMA](../hanma/hanma.md), [BWMA](../bwma/Bwma.md) | **Complementary:** ATR for bands | **Trading note:** Hamming-Window MA; FIR filter minimizing sidelobe amplitude. Balance of main lobe width vs leakage. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HAMMA is a Finite Impulse Response (FIR) filter that applies a Hamming window to price data. The Hamming window is a raised cosine with specific coefficients (0.54 and 0.46) chosen to minimize the amplitude of the first side lobe in the frequency domain. This makes it particularly effective at separating the signal (trend) from nearby noise frequencies. @@ -194,4 +192,4 @@ QuanTAlib validates HAMMA against its mathematical definition and internal consi 4. **Small Periods**: With very small periods (e.g., 3), the window shape degenerates. The edge-center-edge pattern becomes less meaningful. Consider period >= 5 for meaningful Hamming characteristics. -5. **Side Lobe Trade-off**: The -43 dB first side lobe comes at the cost of slightly wider main lobe than Hanning. If frequency resolution matters more than side lobe suppression, consider other windows. +5. **Side Lobe Trade-off**: The -43 dB first side lobe comes at the cost of slightly wider main lobe than Hanning. If frequency resolution matters more than side lobe suppression, consider other windows. \ No newline at end of file diff --git a/lib/trends_FIR/hanma/Hanma.md b/lib/trends_FIR/hanma/Hanma.md index bf6428ad..ebfdf84f 100644 --- a/lib/trends_FIR/hanma/Hanma.md +++ b/lib/trends_FIR/hanma/Hanma.md @@ -14,9 +14,7 @@ | **Signature** | [hanma_signature](hanma_signature.md) | - HANMA is a Finite Impulse Response (FIR) filter that applies a Hanning (Hann) window to price data. -- Parameterized by `period` (default 10). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [WMA](../wma/wma.md), [SinEma](../sinema/sinema.md) | **Complementary:** Trend following | **Trading note:** Hann-Windowed MA; cosine-bell window for smooth spectral characteristics. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HANMA is a Finite Impulse Response (FIR) filter that applies a Hanning (Hann) window to price data. The Hanning window is a pure raised cosine with edge weights of exactly zero, which provides excellent side lobe suppression while maintaining a narrower main lobe than Hamming. It's particularly effective when you want to eliminate boundary discontinuities entirely. @@ -197,4 +195,4 @@ QuanTAlib validates HANMA against its mathematical definition and internal consi 5. **Small Periods**: With very small periods (e.g., 3), the window shape degenerates. A period of 3 produces weights [0, 1, 0]—essentially just the middle value. Consider period >= 5 for meaningful Hanning characteristics. -6. **Side Lobe Trade-off**: The -32 dB first side lobe is worse than Hamming's -43 dB, but the narrower main lobe provides better frequency resolution. Choose based on whether you prioritize frequency resolution or side lobe suppression. +6. **Side Lobe Trade-off**: The -32 dB first side lobe is worse than Hamming's -43 dB, but the narrower main lobe provides better frequency resolution. Choose based on whether you prioritize frequency resolution or side lobe suppression. \ No newline at end of file diff --git a/lib/trends_FIR/hend/Hend.md b/lib/trends_FIR/hend/Hend.md index acfc41b9..cb4f6650 100644 --- a/lib/trends_FIR/hend/Hend.md +++ b/lib/trends_FIR/hend/Hend.md @@ -14,9 +14,7 @@ | **Signature** | [hend_signature](hend_signature.md) | - HEND is a symmetric FIR filter derived from the Henderson (1916) closed-form weight formula, designed to pass cubic polynomial trends without disto... -- Parameterized by `period` (default 7). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [LSMA](../lsma/lsma.md), [TSF](../tsf/Tsf.md) | **Complementary:** StdDev | **Trading note:** Henderson MA; used by Australian Bureau of Statistics. Optimal for extracting smooth trend from noisy data. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HEND is a symmetric FIR filter derived from the Henderson (1916) closed-form weight formula, designed to pass cubic polynomial trends without distortion while maximally suppressing irregular noise. Used as the core smoother in the X-11 and X-13ARIMA-SEATS seasonal adjustment frameworks by statistical agencies worldwide, HEND achieves the theoretically optimal trade-off between smoothness (measured by the sum of squared third differences of the weights) and fidelity for cubic trends. Weights can be negative at the edges, giving the filter a bandpass-like property that sharpens trend-cycle extraction. @@ -117,4 +115,4 @@ O(N) per bar. For default N = 7 (5-term odd period): ~31 cycles. For N = 23 (com | Negative-weight handling | Yes | No special treatment needed; signed FMA handles negatives | | Cross-bar independence | Yes | Each bar's output is independent; full outer-loop vectorization | -With AVX2, 4 bars can be processed simultaneously (each is an N-tap dot product). Total batch throughput: ~N/4 cycles per bar for large series. For N = 23 and 1000-bar batch: ~5750 cycles vs ~95000 scalar — approximately 16.5× speedup (memory-bound at larger N). +With AVX2, 4 bars can be processed simultaneously (each is an N-tap dot product). Total batch throughput: ~N/4 cycles per bar for large series. For N = 23 and 1000-bar batch: ~5750 cycles vs ~95000 scalar — approximately 16.5× speedup (memory-bound at larger N). \ No newline at end of file diff --git a/lib/trends_FIR/hma/Hma.md b/lib/trends_FIR/hma/Hma.md index 9a5df7a7..7f354557 100644 --- a/lib/trends_FIR/hma/Hma.md +++ b/lib/trends_FIR/hma/Hma.md @@ -14,9 +14,7 @@ | **Signature** | [hma_signature](hma_signature.md) | - HMA (Hull Moving Average) is a solution to the eternal struggle between smoothness and lag. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period + sqrtPeriod - 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DEMA](../../trends_IIR/dema/dema.md), [TEMA](../../trends_IIR/tema/tema.md) | **Complementary:** Signal line crossover | **Trading note:** Alan Hulls MA; cascades WMAs to nearly eliminate lag while maintaining smoothness. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HMA (Hull Moving Average) is a solution to the eternal struggle between smoothness and lag. Most indicators force you to choose one; HMA gives you both. It achieves this by using weighted moving averages (WMAs) in a clever configuration that cancels out lag while maintaining the smoothing properties of the WMA. @@ -107,4 +105,4 @@ Discrepancies exist due to different rounding methods for integer periods. * **QuanTAlib**: Uses integer truncation (floor) for $N/2$ and $\sqrt{N}$. * **Ooples**: Uses `Math.Round` (nearest integer). -This results in different effective periods for $N=14$ ($\sqrt{14} \approx 3.74 \to 3$ vs $4$) and others where the fractional part $\ge 0.5$. Validation tests match exactly for periods where rounding logic aligns (e.g., $N=9, 20, 50$). +This results in different effective periods for $N=14$ ($\sqrt{14} \approx 3.74 \to 3$ vs $4$) and others where the fractional part $\ge 0.5$. Validation tests match exactly for periods where rounding logic aligns (e.g., $N=9, 20, 50$). \ No newline at end of file diff --git a/lib/trends_FIR/ilrs/Ilrs.md b/lib/trends_FIR/ilrs/Ilrs.md index a5db28a1..679ea7a3 100644 --- a/lib/trends_FIR/ilrs/Ilrs.md +++ b/lib/trends_FIR/ilrs/Ilrs.md @@ -14,9 +14,7 @@ | **Signature** | [ilrs_signature](ilrs_signature.md) | - ILRS computes the linear regression slope over a rolling window, then accumulates it via discrete integration (running sum) to reconstruct a smooth... -- Parameterized by `period` (default 14). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [LSMA](../lsma/lsma.md), [LinReg](../../statistics/linreg/LinReg.md) | **Complementary:** R² for fit quality | **Trading note:** Integral of Linear Regression Slope; smoothed trend derived from cumulative regression. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ILRS computes the linear regression slope over a rolling window, then accumulates it via discrete integration (running sum) to reconstruct a smoothed price-level signal. By differentiating (slope extraction) and reintegrating, ILRS acts as a low-pass filter that preserves trend direction while suppressing high-frequency noise more aggressively than LSMA. The integration step introduces a natural momentum quality: the output continues rising even as slope magnitude diminishes, making ILRS particularly effective for trend-following systems that need early exit signals based on slope deceleration. @@ -140,4 +138,4 @@ O(1) per bar after warmup (the incremental sum pattern removes the N-scan). For | Slope formula | Yes | `VFNMADD`, `VDIVPD` once prefix sums are built | | Integral (prefix sum of slopes) | Partial | Sequential scan; parallel prefix available but overhead > benefit for N < 1000 | -Batch mode can precompute prefix sums vectorially then compute all slopes in parallel. The integral sum remains a sequential dependency. Net speedup for large series: ~2× over scalar. +Batch mode can precompute prefix sums vectorially then compute all slopes in parallel. The integral sum remains a sequential dependency. Net speedup for large series: ~2× over scalar. \ No newline at end of file diff --git a/lib/trends_FIR/kaiser/Kaiser.md b/lib/trends_FIR/kaiser/Kaiser.md index 1a393ec5..aefe9804 100644 --- a/lib/trends_FIR/kaiser/Kaiser.md +++ b/lib/trends_FIR/kaiser/Kaiser.md @@ -14,9 +14,7 @@ | **Signature** | [kaiser_signature](kaiser_signature.md) | - KAISER applies the Kaiser-Bessel window function as FIR filter weights, providing a single parameter ($\beta$) that continuously controls the trade... -- Parameterized by `period` (default 14), `beta` (default 3.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ALMA](../alma/alma.md), [BLMA](../blma/blma.md) | **Complementary:** Cycle analysis | **Trading note:** Kaiser-windowed MA; adjustable sidelobe suppression via beta parameter. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. KAISER applies the Kaiser-Bessel window function as FIR filter weights, providing a single parameter ($\beta$) that continuously controls the trade-off between main lobe width (transition band sharpness) and sidelobe attenuation (stopband rejection). At $\beta = 0$ it degenerates to a rectangular window (SMA); at $\beta \approx 5.65$ it approximates the Blackman window; at $\beta \approx 8.6$ it matches the Hamming window's sidelobe profile. This makes KAISER the most flexible single-parameter window-based moving average, allowing traders to tune frequency selectivity without changing the window length. @@ -133,4 +131,4 @@ O(N) per bar. For default N = 14: ~59 cycles. Weight computation at construction | Symmetric weight exploitation | Yes | Kaiser weights are symmetric: w[i] = w[N-1-i]; SIMD can fuse pairs | | Cross-bar independence | Yes | Each bar fully independent; outer-loop SIMD viable | -Due to symmetric weights (w[i] = w[N-1-i]), the FIR can be folded: each pair (oldest + newest) shares the same weight, halving the multiply count to N/2 FMA. AVX2 batch throughput: approximately N/8 cycles per bar — for N = 14, ~1.75 cycles/bar at peak. +Due to symmetric weights (w[i] = w[N-1-i]), the FIR can be folded: each pair (oldest + newest) shares the same weight, halving the multiply count to N/2 FMA. AVX2 batch throughput: approximately N/8 cycles per bar — for N = 14, ~1.75 cycles/bar at peak. \ No newline at end of file diff --git a/lib/trends_FIR/lanczos/Lanczos.md b/lib/trends_FIR/lanczos/Lanczos.md index 51e63eed..53d35812 100644 --- a/lib/trends_FIR/lanczos/Lanczos.md +++ b/lib/trends_FIR/lanczos/Lanczos.md @@ -14,9 +14,7 @@ | **Signature** | [lanczos_signature](lanczos_signature.md) | - LANCZOS applies the normalized sinc function $\text{sinc}(x) = \sin(\pi x)/(\pi x)$ as a symmetric FIR window, producing a moving average with near... -- Parameterized by `period` (default 14). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SinEma](../sinema/sinema.md), [NyqMA](../nyqma/Nyqma.md) | **Complementary:** FFT for frequency analysis | **Trading note:** Lanczos filter; sinc function with Lanczos window. Near-ideal low-pass with sharp cutoff. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. LANCZOS applies the normalized sinc function $\text{sinc}(x) = \sin(\pi x)/(\pi x)$ as a symmetric FIR window, producing a moving average with near-ideal low-pass frequency characteristics. The sinc function is the impulse response of the perfect brick-wall low-pass filter; windowing it to finite length trades sharp cutoff for practical realizability. The result is a smoother with minimal Gibbs phenomenon ringing and excellent passband flatness, at the cost of small negative sidelobe weights that can cause minor overshooting on sharp price discontinuities. @@ -121,4 +119,4 @@ O(N) per bar. For default N = 14: ~59 cycles. Sinc weights are computed once at | Cross-bar independence | Yes | Batch outer loop: process 4 output bars per AVX2 iteration | | Negative weight handling | Yes | Signed FMA; no branch needed | -AVX2 batch throughput with symmetric folding: ~N/8 cycles per output bar. For N = 14 over 1000-bar batch: ~1750 cycles vs ~59000 cycles scalar (~34× speedup at peak, memory-limited at larger N). +AVX2 batch throughput with symmetric folding: ~N/8 cycles per output bar. For N = 14 over 1000-bar batch: ~1750 cycles vs ~59000 cycles scalar (~34× speedup at peak, memory-limited at larger N). \ No newline at end of file diff --git a/lib/trends_FIR/lsma/Lsma.md b/lib/trends_FIR/lsma/Lsma.md index ccf5546e..392b503a 100644 --- a/lib/trends_FIR/lsma/Lsma.md +++ b/lib/trends_FIR/lsma/Lsma.md @@ -14,9 +14,7 @@ | **Signature** | [lsma_signature](lsma_signature.md) | - LSMA (Least Squares Moving Average), also known as the Moving Linear Regression or Endpoint Moving Average, calculates the least squares regression... -- Parameterized by `period`, `offset` (default 0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [EPMA](../epma/epma.md), [ALMA](../alma/alma.md) | **Complementary:** R-squared for regression quality | **Trading note:** Least Squares MA; linear regression value at current bar, minimizing squared deviations. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. LSMA (Least Squares Moving Average), also known as the Moving Linear Regression or Endpoint Moving Average, calculates the least squares regression line for the preceding time periods. In plain English: it finds the "best fit" line for the data window and tells you where that line ends. @@ -113,4 +111,4 @@ Validated against Skender. 1. **Overshoot**: Because it projects a trend, LSMA will overshoot significantly when the trend reverses. It assumes the trend continues. 2. **Offset**: You can use a positive offset to extrapolate into the future (forecasting), or a negative offset to center the average. -3. **Noise**: It is very sensitive to outliers because it tries to fit a line to them. +3. **Noise**: It is very sensitive to outliers because it tries to fit a line to them. \ No newline at end of file diff --git a/lib/trends_FIR/nlma/Nlma.md b/lib/trends_FIR/nlma/Nlma.md index fafd3fe4..366f189c 100644 --- a/lib/trends_FIR/nlma/Nlma.md +++ b/lib/trends_FIR/nlma/Nlma.md @@ -14,9 +14,7 @@ | **Signature** | [nlma_signature](nlma_signature.md) | - NLMA uses a two-phase damped cosine kernel with $5P - 1$ taps (where $P$ is the user period). -- Parameterized by `period` (default 14). -- Output range: Tracks input. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [ALMA](../alma/alma.md), [GWMA](../gwma/gwma.md) | **Complementary:** ATR for volatility | **Trading note:** Non-Linear MA; adapts weight profile to price behavior. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. NLMA uses a two-phase damped cosine kernel with $5P - 1$ taps (where $P$ is the user period). Phase 1 builds the initial sweep; Phase 2 extends it through multiple cosine cycles. The kernel's negative weights in the mid-section subtract lagged price components, reducing group delay well below what a positive-only SMA of the same length achieves. Normalization by the signed weight sum preserves DC gain of 1.0. The result is a trend-following filter with moderate overshoot but substantially less lag than conventional moving averages. @@ -180,4 +178,4 @@ For period = 14, the 69-weight array (552 bytes) fits in L1 cache. AVX2 batch th - Igorad / TrendLaboratory. "NonLagMA" original MQL4 source code. The canonical reference for the two-phase kernel formula. - Finware Ltd. "FATL/SATL Digital Filters." Technical documentation for FinWare trading software. Inspiration for the negative-weight lag cancellation approach. -- Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley. Chapter 4: FIR Filters with Negative Weights. +- Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley. Chapter 4: FIR Filters with Negative Weights. \ No newline at end of file diff --git a/lib/trends_FIR/nyqma/Nyqma.md b/lib/trends_FIR/nyqma/Nyqma.md index 0280a63e..65644adc 100644 --- a/lib/trends_FIR/nyqma/Nyqma.md +++ b/lib/trends_FIR/nyqma/Nyqma.md @@ -14,9 +14,7 @@ | **Signature** | [nyqma_signature](nyqma_signature.md) | - NYQMA combines a primary LWMA (Linear Weighted Moving Average) with a secondary LWMA applied to the first, using lag-compensating extrapolation: $\... -- Parameterized by `period` (default 89), `nyquistperiod` (default 21). -- Output range: Tracks input. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [Lanczos](../lanczos/Lanczos.md), [SinEma](../sinema/sinema.md) | **Complementary:** Cycle detection | **Trading note:** Nyquist MA; designed around Nyquist frequency. Optimal for eliminating aliased cycles. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. NYQMA combines a primary LWMA (Linear Weighted Moving Average) with a secondary LWMA applied to the first, using lag-compensating extrapolation: $\text{NYQMA} = (1+\alpha) \cdot \text{MA}_1 - \alpha \cdot \text{MA}_2$, where $\alpha = N_2 / (N_1 - N_2)$. The Nyquist constraint $N_2 \leq \lfloor N_1/2 \rfloor$ ensures the second smoothing does not introduce aliasing artifacts into the output. This produces a lag-reduced moving average grounded in sampling theory rather than ad-hoc coefficient tuning. Streaming update is O(1) per bar via composed Wma instances; batch mode uses stackalloc/ArrayPool with FMA in the extrapolation loop. @@ -180,4 +178,4 @@ The $1 \times 10^{-6}$ tolerance for batch vs streaming reflects expected floati - Dürschner, M.G. *Gleitende Durchschnitte 3.0*. (Original NYQMA publication, German language.) - Shannon, C.E. (1949). "Communication in the Presence of Noise." *Proceedings of the IRE*, 37(1), 10-21. - Nyquist, H. (1928). "Certain Topics in Telegraph Transmission Theory." *Transactions of the AIEE*, 47(2), 617-644. -- Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley. (PMA reference for comparison.) +- Ehlers, J.F. (2001). *Rocket Science for Traders*. Wiley. (PMA reference for comparison.) \ No newline at end of file diff --git a/lib/trends_FIR/parzen/Parzen.md b/lib/trends_FIR/parzen/Parzen.md index d0ac4d8d..4f468650 100644 --- a/lib/trends_FIR/parzen/Parzen.md +++ b/lib/trends_FIR/parzen/Parzen.md @@ -14,9 +14,7 @@ | **Signature** | [parzen_signature](parzen_signature.md) | - PARZEN applies the Parzen (de la Vallée-Poussin) window function as FIR filter weights, producing a moving average with exceptional sidelobe suppre... -- Parameterized by `period` (default 14). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [GWMA](../gwma/gwma.md), [BWMA](../bwma/Bwma.md) | **Complementary:** ATR | **Trading note:** Parzen-window MA; piecewise-cubic taper. Very smooth with low spectral leakage. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. PARZEN applies the Parzen (de la Vallée-Poussin) window function as FIR filter weights, producing a moving average with exceptional sidelobe suppression ($-24$ dB/octave rolloff) and a smooth bell-shaped kernel. The Parzen window is the self-convolution of two triangular (Bartlett) windows at half-length, which guarantees continuous first and second derivatives at all points. This makes it one of the few windows whose frequency response has no discontinuities in its first three derivatives, yielding the fastest sidelobe decay rate among common windows without requiring the computational cost of Bessel functions (Kaiser) or specialized polynomials (Henderson). @@ -131,4 +129,4 @@ O(N) per bar. For default N = 14: ~59 cycles. No negative weights — normalizat | Parzen symmetry | Yes | Symmetric window: w[i] = w[N-1-i]; fold for N/2 FMAs | | Cross-bar independence | Yes | Full outer-loop SIMD viable | -Symmetric folding halves the multiply count. AVX2 batch throughput: ~N/8 cycles per output bar. Non-negative weights avoid any masking overhead, giving slightly cleaner codegen than sinc-based filters. +Symmetric folding halves the multiply count. AVX2 batch throughput: ~N/8 cycles per output bar. Non-negative weights avoid any masking overhead, giving slightly cleaner codegen than sinc-based filters. \ No newline at end of file diff --git a/lib/trends_FIR/pma/Pma.md b/lib/trends_FIR/pma/Pma.md index 172ed402..3acde0fd 100644 --- a/lib/trends_FIR/pma/Pma.md +++ b/lib/trends_FIR/pma/Pma.md @@ -14,9 +14,7 @@ | **Signature** | [pma_signature](pma_signature.md) | - PMA (Predictive Moving Average) is a lag-cancellation filter that uses linear extrapolation of dual WMA (Weighted Moving Average) cascades to predi... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `(period * 2) - 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [LSMA](../lsma/lsma.md), [Polyfit](../../statistics/polyfit/Polyfit.md) | **Complementary:** R² for trend quality | **Trading note:** Polynomial MA; fits nth-degree polynomial. Captures curves better than linear regression. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. PMA (Predictive Moving Average) is a lag-cancellation filter that uses linear extrapolation of dual WMA (Weighted Moving Average) cascades to predict price direction. It produces two outputs: the PMA line (extrapolated trend) and a Trigger line for crossover signals. Default period is 7 per Ehlers' original specification. @@ -190,4 +188,4 @@ PMA has no direct equivalent in external libraries. Validation uses component co - Ehlers, J.F. (2004). *Cybernetic Analysis for Stocks and Futures*. John Wiley and Sons. - Ehlers, J.F. (2001). "MESA Adaptive Moving Average." *Technical Analysis of Stocks and Commodities*, September 2001. - Mulloy, P.G. (1994). "Smoothing Data with Faster Moving Averages." *Technical Analysis of Stocks and Commodities*, February 1994. -- Richardson, L.F. (1911). "The Approximate Arithmetical Solution by Finite Differences of Physical Problems." *Philosophical Transactions of the Royal Society A*, 210: 307-357. +- Richardson, L.F. (1911). "The Approximate Arithmetical Solution by Finite Differences of Physical Problems." *Philosophical Transactions of the Royal Society A*, 210: 307-357. \ No newline at end of file diff --git a/lib/trends_FIR/pwma/Pwma.md b/lib/trends_FIR/pwma/Pwma.md index e74ebec1..14cf6e19 100644 --- a/lib/trends_FIR/pwma/Pwma.md +++ b/lib/trends_FIR/pwma/Pwma.md @@ -14,9 +14,7 @@ | **Signature** | [pwma_signature](pwma_signature.md) | - PWMA (Parabolic Weighted Moving Average) applies a parabolic ($i^2$) weighting scheme to the data window. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [FWMA](../fwma/fwma.md), [WMA](../wma/wma.md) | **Complementary:** Trend filters | **Trading note:** Pascal-Weighted MA; weights from Pascals triangle for smooth, symmetric kernel. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. PWMA (Parabolic Weighted Moving Average) applies a parabolic ($i^2$) weighting scheme to the data window. This assigns massive importance to the most recent data points while still technically including the older data. It's like a WMA on steroids. @@ -96,4 +94,4 @@ Validated against Ooples. | **Skender** | N/A | Not implemented | | **TA-Lib** | N/A | Not implemented | -| **Tulip** | N/A | Not implemented. | +| **Tulip** | N/A | Not implemented. | \ No newline at end of file diff --git a/lib/trends_FIR/qrma/Qrma.md b/lib/trends_FIR/qrma/Qrma.md index 0f1cb9f4..93c70099 100644 --- a/lib/trends_FIR/qrma/Qrma.md +++ b/lib/trends_FIR/qrma/Qrma.md @@ -14,9 +14,7 @@ | **Signature** | [qrma_signature](qrma_signature.md) | - QRMA fits a second-degree polynomial $y = a + bx + cx^2$ to the most recent $N$ bars via ordinary least squares, then returns the fitted value at t... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [LSMA](../lsma/lsma.md), [PMA](../pma/Pma.md) | **Complementary:** Trend indicators | **Trading note:** Quadratic Regression MA; 2nd-order polynomial fit. Captures parabolic acceleration. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. QRMA fits a second-degree polynomial $y = a + bx + cx^2$ to the most recent $N$ bars via ordinary least squares, then returns the fitted value at the endpoint (newest bar). By capturing curvature that LSMA (degree-1) misses, QRMA provides meaningfully better tracking of accelerating or decelerating price trends. The 3x3 normal-equation system is solved via Cramer's rule in O(1) after an O(N) data accumulation pass, making it computationally efficient and suitable for streaming applications. @@ -140,4 +138,4 @@ O(N) per bar from power sum accumulation. For default N = 14: ~214 cycles. Compa | Cramer 3×3 solve | No | Fixed 30-op scalar system; SIMD setup overhead exceeds benefit | | Quadratic evaluation (Horner) | No | 2 FMAs; scalar fastest at degree 2 | -Batch speedup for the sum accumulation phases: ~3× with AVX2. Solve and evaluation phases remain scalar. Net batch speedup for large series: approximately 2× over fully scalar. +Batch speedup for the sum accumulation phases: ~3× with AVX2. Solve and evaluation phases remain scalar. Net batch speedup for large series: approximately 2× over fully scalar. \ No newline at end of file diff --git a/lib/trends_FIR/rain/Rain.md b/lib/trends_FIR/rain/Rain.md index 8b08eef7..67de736f 100644 --- a/lib/trends_FIR/rain/Rain.md +++ b/lib/trends_FIR/rain/Rain.md @@ -14,9 +14,7 @@ | **Signature** | [rain_signature](rain_signature.md) | - RAIN recursively applies SMA 10 times, producing 10 layers of progressively smoother price representation, then computes a weighted average across ... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [ALMA](../alma/alma.md), [FWMA](../fwma/fwma.md) | **Complementary:** ATR | **Trading note:** Raised-cosine MA; smooth taper at edges. Good sidelobe suppression for noise reduction. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. RAIN recursively applies SMA 10 times, producing 10 layers of progressively smoother price representation, then computes a weighted average across all layers. Layers 1-4 receive weights 5, 4, 3, 2 (emphasizing the more responsive layers), while layers 5-10 each receive weight 1, for a total divisor of 20. This multi-scale composition produces a moving average that responds to short-term price changes through the lightly smoothed upper layers while maintaining stability through the heavily smoothed lower layers. @@ -134,4 +132,4 @@ O(1) per bar. Each of the 10 SMA layers is O(1); the composite sum is 10 FMA ope | Weighted composite | Yes | 10-element dot product; fits in 2–3 AVX2 registers | | Cross-bar independence | Yes | Outer loop fully vectorizable: 4 output bars per pass | -Because all 10 SMA layers are independent, the entire computation can be vectorized across layers AND across bars simultaneously. AVX2 can process 4 bars per pass, each bar updating all 10 layers via 10-register prefix sums. Estimated batch speedup for large series: ~6× over scalar. +Because all 10 SMA layers are independent, the entire computation can be vectorized across layers AND across bars simultaneously. AVX2 can process 4 bars per pass, each bar updating all 10 layers via 10-register prefix sums. Estimated batch speedup for large series: ~6× over scalar. \ No newline at end of file diff --git a/lib/trends_FIR/rwma/Rwma.md b/lib/trends_FIR/rwma/Rwma.md index f8379c1c..dcbfa34a 100644 --- a/lib/trends_FIR/rwma/Rwma.md +++ b/lib/trends_FIR/rwma/Rwma.md @@ -13,9 +13,7 @@ | **PineScript** | [rwma.pine](rwma.pine) | - RWMA weights each bar's contribution to the average by its price range (high minus low), giving greater influence to volatile bars and less to narr... -- Parameterized by `period` (default 14). -- Output range: Tracks input. -- Requires `> period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [WMA](../wma/wma.md), [EMA](../../trends_IIR/ema/ema.md) | **Trading note:** Right-weighted MA; concentrates weight on recent data while maintaining FIR structure. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. RWMA weights each bar's contribution to the average by its price range (high minus low), giving greater influence to volatile bars and less to narrow-range, indecisive bars. The logic: a bar with a large range represents stronger price discovery and carries more informational content than a low-range doji. This produces a moving average that gravitates toward prices established during high-activity periods, naturally incorporating volatility as a relevance signal without requiring a separate volatility indicator. @@ -120,4 +118,4 @@ O(1) per bar. The division is the dominant cost. Resync every 1000 bars prevents | Prefix sum of range | Partial | Same as above | | Final division | Yes | `VDIVPD` after prefix sums built; zero-guard via `VCMPPD` + blend | -Both prefix sums can be built with AVX2 prefix-scan kernels. Once built, all N sliding-window divisions can be computed in parallel. Batch speedup: approximately 4× over scalar for large series. +Both prefix sums can be built with AVX2 prefix-scan kernels. Once built, all N sliding-window divisions can be computed in parallel. Batch speedup: approximately 4× over scalar for large series. \ No newline at end of file diff --git a/lib/trends_FIR/sgma/Sgma.md b/lib/trends_FIR/sgma/Sgma.md index e727d4fe..c18c9ec4 100644 --- a/lib/trends_FIR/sgma/Sgma.md +++ b/lib/trends_FIR/sgma/Sgma.md @@ -14,9 +14,7 @@ | **Signature** | [sgma_signature](sgma_signature.md) | - SGMA is a Finite Impulse Response (FIR) filter that uses polynomial fitting to smooth data while preserving higher moments (peaks, valleys, and inf... -- Parameterized by `period` (default 9), `degree` (default 2). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SGF](../../filters/sgf/Sgf.md), [LSMA](../lsma/lsma.md) | **Trading note:** Savitzky-Golay MA; polynomial smoothing that preserves higher moments. Good for derivative estimation. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. SGMA is a Finite Impulse Response (FIR) filter that uses polynomial fitting to smooth data while preserving higher moments (peaks, valleys, and inflection points). Unlike the Simple Moving Average (which flattens everything) or the Exponential Moving Average (which introduces phase lag), SGMA uses polynomial weighting to maintain the original signal's shape characteristics. @@ -195,4 +193,4 @@ QuanTAlib validates SGMA against mathematical properties rather than external li 4. **Cold Start**: SGMA requires a full window ($L$) to produce mathematically valid output. The first $L-1$ bars are warmup noise. Check `IsHot` before trading on the signal. -5. **High Degree Instability**: Degrees 3-4 concentrate weight heavily in the center. While this preserves shape, it also means a small number of bars dominate the output—approaching the behavior of a very short moving average with extra smoothing on the tails. +5. **High Degree Instability**: Degrees 3-4 concentrate weight heavily in the center. While this preserves shape, it also means a small number of bars dominate the output—approaching the behavior of a very short moving average with extra smoothing on the tails. \ No newline at end of file diff --git a/lib/trends_FIR/sinema/Sinema.md b/lib/trends_FIR/sinema/Sinema.md index 023eb89e..83e5204a 100644 --- a/lib/trends_FIR/sinema/Sinema.md +++ b/lib/trends_FIR/sinema/Sinema.md @@ -14,9 +14,7 @@ | **Signature** | [sinema_signature](sinema_signature.md) | - The Sine-Weighted Moving Average (SINEMA) applies sine-wave weighting to data points within the lookback window. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ALMA](../alma/alma.md), [BLMA](../blma/blma.md) | **Complementary:** Cycle indicators | **Trading note:** Sine-weighted MA; half-sine kernel for naturally smooth bell-shaped weights. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Sine-Weighted Moving Average (SINEMA) applies sine-wave weighting to data points within the lookback window. Weights follow the formula $w_i = \sin(\pi \cdot (i+1) / N)$, creating a smooth bell-shaped distribution that emphasizes middle values while gracefully tapering at the edges. Unlike SMA's uniform weighting or WMA's linear ramp, sine weighting provides a natural transition that reduces high-frequency noise while preserving mid-frequency trends. @@ -128,4 +126,4 @@ Validation tests verify: ## References - Harris, F. J. (1978). "On the use of windows for harmonic analysis with the discrete Fourier transform." *Proceedings of the IEEE*, 66(1), 51-83. -- Oppenheim, A. V., & Schafer, R. W. (2010). *Discrete-Time Signal Processing* (3rd ed.). Pearson. +- Oppenheim, A. V., & Schafer, R. W. (2010). *Discrete-Time Signal Processing* (3rd ed.). Pearson. \ No newline at end of file diff --git a/lib/trends_FIR/sma/Sma.md b/lib/trends_FIR/sma/Sma.md index 5f0dc6b4..2c9b9281 100644 --- a/lib/trends_FIR/sma/Sma.md +++ b/lib/trends_FIR/sma/Sma.md @@ -14,9 +14,7 @@ | **Signature** | [sma_signature](sma_signature.md) | - The Simple Moving Average (SMA) is the unweighted arithmetic mean of the last $N$ data points. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [EMA](../../trends_IIR/ema/ema.md), [WMA](../wma/wma.md) | **Complementary:** ATR for Keltner-style bands | **Trading note:** Simple Moving Average; equal-weight FIR filter. Most basic and widely used MA. Foundation of many composite indicators. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Simple Moving Average (SMA) is the unweighted arithmetic mean of the last $N$ data points. It acts as a low-pass filter, smoothing out high-frequency noise to reveal the underlying trend. While conceptually simple, efficient implementation on modern hardware requires careful attention to memory access patterns and vectorization. @@ -115,4 +113,4 @@ For 512 bars: | **TA-Lib** | ✅ | Matches `TA_SMA` exactly. | | **Skender** | ✅ | Matches `GetSma` exactly. | | **Tulip** | ✅ | Matches `sma` exactly. | -| **Ooples** | ✅ | Matches `CalculateSimpleMovingAverage`. | +| **Ooples** | ✅ | Matches `CalculateSimpleMovingAverage`. | \ No newline at end of file diff --git a/lib/trends_FIR/sp15/Sp15.md b/lib/trends_FIR/sp15/Sp15.md index 1efc86e4..7a8ec705 100644 --- a/lib/trends_FIR/sp15/Sp15.md +++ b/lib/trends_FIR/sp15/Sp15.md @@ -15,8 +15,6 @@ - SP15 is a fixed-coefficient symmetric FIR filter with 15 weights: $[-3, -6, -5, 3, 21, 46, 67, 74, 67, 46, 21, 3, -5, -6, -3]$ divided by 320. - No configurable parameters; computation is stateless per bar. -- Output range: Tracks input. -- Requires `Period` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. SP15 is a fixed-coefficient symmetric FIR filter with 15 weights: $[-3, -6, -5, 3, 21, 46, 67, 74, 67, 46, 21, 3, -5, -6, -3]$ divided by 320. The weights were designed by John Spencer to have zero frequency response at periods 4 and 5 (frequencies $2\pi/4$ and $2\pi/5$), making the filter effective at removing quarterly and quintile seasonal components from economic time series. The negative edge weights provide bandpass-like characteristics, and the fixed design requires no parameters beyond the source series. @@ -128,4 +126,4 @@ O(1) per bar (N is fixed at 15). The dot product takes ~60 cycles on modern x86. | Negative edge weights | Yes | Signed FMA; no special masking | | Fixed-N: 15 taps | Yes | Compiler can fully unroll the 15-FMA loop at O3 | -With symmetric folding (8 unique weight pairs), the 15-tap dot product reduces to ~8 FMAs. AVX2 processes 4 output bars per outer iteration. Batch throughput: ~2 cycles per output bar at peak. Unrolled codegen fits entirely in instruction cache. +With symmetric folding (8 unique weight pairs), the 15-tap dot product reduces to ~8 FMAs. AVX2 processes 4 output bars per outer iteration. Batch throughput: ~2 cycles per output bar at peak. Unrolled codegen fits entirely in instruction cache. \ No newline at end of file diff --git a/lib/trends_FIR/swma/Swma.md b/lib/trends_FIR/swma/Swma.md index b8592238..1d93fe4e 100644 --- a/lib/trends_FIR/swma/Swma.md +++ b/lib/trends_FIR/swma/Swma.md @@ -14,9 +14,7 @@ | **Signature** | [swma_signature](swma_signature.md) | - SWMA applies triangular (symmetric) weights that peak at the center of the window and taper linearly to the edges. -- Parameterized by `period` (default 4). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [WMA](../wma/wma.md), [SMA](../sma/Sma.md) | **Trading note:** Symmetric-Weighted MA; bell-shaped weight profile centered on middle. Reduces end-point bias. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. SWMA applies triangular (symmetric) weights that peak at the center of the window and taper linearly to the edges. For period $N$, the weight at position $i$ is $w(i) = (N/2 + 1) - |i - N/2|$, producing a tent-shaped kernel. This is mathematically equivalent to convolving two rectangular windows (SMA of SMA), giving SWMA a frequency response that is the square of the SMA's sinc-like response. The result is smoother than SMA with better sidelobe suppression, at the cost of slightly more lag. @@ -126,4 +124,4 @@ O(N) per bar. For default N = 14: ~59 cycles. Triangular weights are strictly po | Symmetric triangular window | Yes | Fold: only ⌈N/2⌉ unique weights; halves FMA count | | Cross-bar independence | Yes | 4 output bars per AVX2 pass | -Symmetric folding reduces the effective FMA count to ⌈N/2⌉. For N = 14: 7 FMAs per bar. AVX2 batch throughput: ~N/8 cycles per bar. Among the windowed FIR filters, SWMA has the fewest effective operations due to its simple triangular shape. +Symmetric folding reduces the effective FMA count to ⌈N/2⌉. For N = 14: 7 FMAs per bar. AVX2 batch throughput: ~N/8 cycles per bar. Among the windowed FIR filters, SWMA has the fewest effective operations due to its simple triangular shape. \ No newline at end of file diff --git a/lib/trends_FIR/trima/Trima.md b/lib/trends_FIR/trima/Trima.md index 1cb87432..65db0876 100644 --- a/lib/trends_FIR/trima/Trima.md +++ b/lib/trends_FIR/trima/Trima.md @@ -14,9 +14,7 @@ | **Signature** | [trima_signature](trima_signature.md) | - The Triangular Moving Average (TRIMA) places the majority of its weight on the middle of the data window, tapering off linearly towards the ends. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `p1 + p2 - 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [WMA](../wma/wma.md), [SMA](../../trends_IIR/sma/sma.md) | **Complementary:** Volume analysis | **Trading note:** Triangular MA; double-smoothed SMA with triangle-shaped weights peaking at center. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Triangular Moving Average (TRIMA) places the majority of its weight on the middle of the data window, tapering off linearly towards the ends. This creates a triangular weight distribution (hence the name). It is mathematically equivalent to a double-smoothed SMA. @@ -90,4 +88,4 @@ Each SMA component benefits from SIMD prefix-sum optimization: | **TA-Lib** | ✅ | Matches `TA_TRIMA` exactly. | | **Skender** | ✅ | Matches composite `SMA(SMA)` logic. | | **Tulip** | ✅ | Matches `trima` exactly. | -| **Ooples** | N/A | Not implemented. | +| **Ooples** | N/A | Not implemented. | \ No newline at end of file diff --git a/lib/trends_FIR/tsf/Tsf.md b/lib/trends_FIR/tsf/Tsf.md index c9d32b31..9503a59b 100644 --- a/lib/trends_FIR/tsf/Tsf.md +++ b/lib/trends_FIR/tsf/Tsf.md @@ -14,9 +14,7 @@ | **Signature** | [tsf_signature](tsf_signature.md) | - TSF projects the least-squares regression line one bar forward, providing a statistically grounded forecast of the next bar's value. -- Parameterized by `period` (default 14). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [LSMA](../lsma/lsma.md), [LinReg](../../statistics/linreg/LinReg.md) | **Complementary:** R² for forecast reliability | **Trading note:** Time Series Forecast; linear regression extrapolated one bar ahead. Predictive MA. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. TSF projects the least-squares regression line one bar forward, providing a statistically grounded forecast of the next bar's value. Unlike simple moving averages that smooth past data, TSF answers the question: "If the current trend continues, where will price be next?" This makes it inherently leading rather than lagging, though the forecast degrades quickly beyond one step. @@ -144,4 +142,4 @@ The O(1) running-sum algorithm is inherently serial due to data dependencies. Ba - Tushar Chande, *The New Technical Trader*, 1994 - TA-Lib: `TA_TSF` function (www.ta-lib.org) -- PineScript: `ta.linreg(source, length, -1)` (offset=-1 = one step ahead) +- PineScript: `ta.linreg(source, length, -1)` (offset=-1 = one step ahead) \ No newline at end of file diff --git a/lib/trends_FIR/tukey_w/Tukey_w.md b/lib/trends_FIR/tukey_w/Tukey_w.md index 6e7e8a08..1f4b4807 100644 --- a/lib/trends_FIR/tukey_w/Tukey_w.md +++ b/lib/trends_FIR/tukey_w/Tukey_w.md @@ -14,9 +14,7 @@ | **Signature** | [tukey_w_signature](tukey_w_signature.md) | - TUKEY_W applies the Tukey (tapered cosine) window as FIR filter weights, offering a single parameter $\alpha$ that controls the fraction of the win... -- Parameterized by `period` (default 20), `alpha` (default 0.5). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HanMA](../hanma/hanma.md), [BWMA](../bwma/Bwma.md) | **Trading note:** Tukey-window MA; adjustable taper parameter between rectangular and Hann. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. TUKEY_W applies the Tukey (tapered cosine) window as FIR filter weights, offering a single parameter $\alpha$ that controls the fraction of the window that is cosine-tapered. At $\alpha = 0$, the window is rectangular (SMA). At $\alpha = 1$, it becomes the Hann window. The default $\alpha = 0.5$ tapers 25% at each edge while keeping the central 50% flat at unity, combining the passband efficiency of the rectangular window with the sidelobe suppression of cosine tapering. This makes Tukey the default "when in doubt" window in spectral analysis, and by extension, a sensible default for window-based moving averages. @@ -134,4 +132,4 @@ O(N) per bar. For default N = 14: ~59 cycles. Non-negative quartic weights; no s | Tukey symmetric window | Yes | Symmetric: fold to ⌈N/2⌉ unique weights | | Cross-bar independence | Yes | 4 output bars per AVX2 pass | -Tukey biweight shares the same symmetric FIR structure as Kaiser and Parzen. Symmetric folding halves FMA count to ⌈N/2⌉. AVX2 batch throughput: ~N/8 cycles per bar. +Tukey biweight shares the same symmetric FIR structure as Kaiser and Parzen. Symmetric folding halves FMA count to ⌈N/2⌉. AVX2 batch throughput: ~N/8 cycles per bar. \ No newline at end of file diff --git a/lib/trends_FIR/wma/Wma.md b/lib/trends_FIR/wma/Wma.md index fd31c5ce..6c307e7f 100644 --- a/lib/trends_FIR/wma/Wma.md +++ b/lib/trends_FIR/wma/Wma.md @@ -14,9 +14,7 @@ | **Signature** | [wma_signature](wma_signature.md) | - The Weighted Moving Average (WMA) assigns a linearly decreasing weight to data points. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [FWMA](../fwma/fwma.md), [TRIMA](../trima/trima.md) | **Complementary:** WMA crossover systems | **Trading note:** Linearly weighted MA; recent prices get higher weight, faster response than SMA. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Weighted Moving Average (WMA) assigns a linearly decreasing weight to data points. The most recent price gets weight $N$, the one before it $N-1$, down to 1. This makes it more responsive to recent price changes than an SMA, but without the infinite tail of an EMA. @@ -107,4 +105,4 @@ The batch path achieves near-linear scaling for large datasets. | **TA-Lib** | ✅ | Matches `TA_WMA` exactly. | | **Skender** | ✅ | Matches `GetWma` exactly. | | **Tulip** | ✅ | Matches `wma` exactly. | -| **Ooples** | ✅ | Matches `CalculateWeightedMovingAverage`. | +| **Ooples** | ✅ | Matches `CalculateWeightedMovingAverage`. | \ No newline at end of file diff --git a/lib/trends_IIR/adxvma/Adxvma.md b/lib/trends_IIR/adxvma/Adxvma.md index a899ac08..c54aea0d 100644 --- a/lib/trends_IIR/adxvma/Adxvma.md +++ b/lib/trends_IIR/adxvma/Adxvma.md @@ -13,9 +13,7 @@ | **PineScript** | [adxvma.pine](adxvma.pine) | - ADXVMA is an adaptive IIR filter that uses the Average Directional Index (ADX) as its smoothing constant. -- Parameterized by `period` (default 14). -- Output range: Tracks input. -- Requires `period * 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [KAMA](../kama/kama.md), [VIDYA](../vidya/vidya.md) | **Complementary:** ADX for trend strength | **Trading note:** ADX-based Variable MA; adapts smoothing using ADX measurement. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ADXVMA is an adaptive IIR filter that uses the Average Directional Index (ADX) as its smoothing constant. When ADX is high (strong trend), the smoothing factor approaches 1.0 and the filter tracks price aggressively. When ADX is low (range-bound), the smoothing factor approaches 0.0 and the filter barely moves. This creates a moving average that automatically switches between responsive trend-following and noise-immune range-holding without external regime detection. @@ -147,4 +145,4 @@ O(1) per bar. State is 4 RMA scalars + OHLC history + VMA output. WarmupPeriod = | ADX computation | Partial | Vectorizable ratio except for recursive RMA | | Adaptive VMA | No | Recursive IIR (alpha depends on computed ADX) | -All four RMA passes and the adaptive VMA are recursive IIR — inherently sequential. Batch mode can vectorize TR and DM computation (pure per-bar arithmetic) then run scalar RMA sweeps. Net batch speedup for large series: ~1.5× (TR/DM vectorization only). +All four RMA passes and the adaptive VMA are recursive IIR — inherently sequential. Batch mode can vectorize TR and DM computation (pure per-bar arithmetic) then run scalar RMA sweeps. Net batch speedup for large series: ~1.5× (TR/DM vectorization only). \ No newline at end of file diff --git a/lib/trends_IIR/ahrens/Ahrens.md b/lib/trends_IIR/ahrens/Ahrens.md index 85476201..606b969c 100644 --- a/lib/trends_IIR/ahrens/Ahrens.md +++ b/lib/trends_IIR/ahrens/Ahrens.md @@ -14,9 +14,7 @@ | **Signature** | [ahrens_signature](ahrens_signature.md) | - AHRENS is a recursive IIR filter that adjusts toward the source price minus the midpoint of its current and lagged (by one period) states. -- Parameterized by `period` (default 9). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [EMA](../ema/ema.md) | **Complementary:** Trend filters | **Trading note:** Ahrens MA; modified exponential averaging for reduced noise. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. AHRENS is a recursive IIR filter that adjusts toward the source price minus the midpoint of its current and lagged (by one period) states. The formula $\text{AHRENS}_t = \text{AHRENS}_{t-1} + (\text{source} - \frac{\text{AHRENS}_{t-1} + \text{AHRENS}_{t-N}}{2}) / N$ creates a self-dampening feedback loop: the correction term shrinks as the current and lagged states converge, producing a smoother approach to equilibrium than a standard EMA with less tendency to overshoot on reversals. @@ -122,4 +120,4 @@ O(1) per bar. The ring buffer stores past output values, not input values — a | Self-referential IIR update | No | AHRENS[t] depends on AHRENS[t-1] and AHRENS[t-N]; both are computed values | | Correction divide | No | Alpha depends on computed error; scalar only | -AHRENS is strictly sequential — the output at bar t depends on the output at bar t-1 (direct feedback) AND the output at bar t-N (delayed feedback). No vectorization is possible. Batch mode runs the same scalar kernel as streaming. +AHRENS is strictly sequential — the output at bar t depends on the output at bar t-1 (direct feedback) AND the output at bar t-N (delayed feedback). No vectorization is possible. Batch mode runs the same scalar kernel as streaming. \ No newline at end of file diff --git a/lib/trends_IIR/coral/Coral.md b/lib/trends_IIR/coral/Coral.md index 94e26b24..ce4ba092 100644 --- a/lib/trends_IIR/coral/Coral.md +++ b/lib/trends_IIR/coral/Coral.md @@ -14,9 +14,7 @@ | **Signature** | [coral_signature](coral_signature.md) | - The **Coral** filter is a smooth, low-lag trend indicator that chains six cascaded EMA passes and combines stages 3–6 using polynomial coefficients... -- Parameterized by `period`, `cd` (default 0.4). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DEMA](../dema/dema.md), [TEMA](../tema/tema.md) | **Complementary:** Trend direction filters | **Trading note:** Coral trend indicator; smooth, low-lag modified exponential filter. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Overview @@ -191,4 +189,4 @@ All 6 EMA stages are recursive IIR — inherently sequential. The polynomial com - LazyBear, "Coral Trend Indicator" — [TradingView](https://www.tradingview.com/u/LazyBear/) - Original MT4 implementation (author unknown) -- Related: Tillson, T. "Smoothing Techniques for More Accurate Signals" — TASC, 1998 (T3 cascade technique) +- Related: Tillson, T. "Smoothing Techniques for More Accurate Signals" — TASC, 1998 (T3 cascade technique) \ No newline at end of file diff --git a/lib/trends_IIR/decycler/Decycler.md b/lib/trends_IIR/decycler/Decycler.md index e8de3908..e8315100 100644 --- a/lib/trends_IIR/decycler/Decycler.md +++ b/lib/trends_IIR/decycler/Decycler.md @@ -14,9 +14,7 @@ | **Signature** | [decycler_signature](decycler_signature.md) | - The Ehlers Decycler extracts the trend component from a price series by subtracting a 2-pole Butterworth high-pass filter from the source signal. -- Parameterized by `period` (default 60). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [EMA](../ema/ema.md), [HTIT](../htit/htit.md) | **Complementary:** Cycle indicators | **Trading note:** Ehlers Decycler; high-pass complement removes cycle components to isolate trend. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Ehlers Decycler extracts the trend component from a price series by subtracting a 2-pole Butterworth high-pass filter from the source signal. Where most moving averages blur the boundary between trend and cycle, the Decycler defines it with a frequency-domain cutoff: cycles shorter than the specified period are removed, everything longer stays. The result is an overlay that hugs price with near-zero lag during trends and rejects short-term oscillations without the smoothing artifacts of convolution-based averages. @@ -244,4 +242,4 @@ var (results, indicator) = Decycler.Calculate(series, period: 60); - Ehlers, J. F. (2015). "Decyclers." *Technical Analysis of Stocks & Commodities*, September 2015. - Ehlers, J. F. (2013). *Cycle Analytics for Traders*. Wiley. Chapter 4. -- Ehlers, J. F. (2004). *Cybernetic Analysis for Stocks and Futures*. Wiley. +- Ehlers, J. F. (2004). *Cybernetic Analysis for Stocks and Futures*. Wiley. \ No newline at end of file diff --git a/lib/trends_IIR/dsma/Dsma.md b/lib/trends_IIR/dsma/Dsma.md index 93771e46..9162ebd6 100644 --- a/lib/trends_IIR/dsma/Dsma.md +++ b/lib/trends_IIR/dsma/Dsma.md @@ -14,9 +14,7 @@ | **Signature** | [dsma_signature](dsma_signature.md) | - DSMA (Deviation-Scaled Moving Average) is a volatility-adaptive trend filter that combines a Super Smoother (2-pole Butterworth IIR filter) with RM... -- Parameterized by `period`, `scalefactor` (default 0.5). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DEMA](../dema/dema.md), [KAMA](../kama/kama.md) | **Complementary:** ADX for trend confirmation | **Trading note:** Deviation-Scaled MA; adapts smoothing based on price deviation. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. DSMA (Deviation-Scaled Moving Average) is a volatility-adaptive trend filter that combines a Super Smoother (2-pole Butterworth IIR filter) with RMS-based deviation scaling. Unlike fixed-period moving averages that treat all market conditions identically, DSMA adjusts its responsiveness based on measured volatility—accelerating when trends are strong and decelerating when prices consolidate. @@ -172,4 +170,4 @@ DSMA is not implemented in mainstream libraries (TA-Lib, Skender, Tulip, Ooples) 6. **Bar Correction**: Like all QuanTAlib indicators, DSMA supports bar correction via the `isNew` parameter. When `isNew = false`, it rolls back to the previous state before recalculating. Ensure your data feed correctly signals bar updates versus corrections. -7. **SIMD Limitation**: The recursive nature of the Super Smoother filter and adaptive alpha calculation precludes efficient SIMD vectorization. The `Calculate(Span)` method uses a scalar loop. For bulk backtesting, consider parallelizing across multiple series rather than within a single series. +7. **SIMD Limitation**: The recursive nature of the Super Smoother filter and adaptive alpha calculation precludes efficient SIMD vectorization. The `Calculate(Span)` method uses a scalar loop. For bulk backtesting, consider parallelizing across multiple series rather than within a single series. \ No newline at end of file diff --git a/lib/trends_IIR/ema/ema.py b/lib/trends_IIR/ema/ema.py new file mode 100644 index 00000000..a7ff2203 --- /dev/null +++ b/lib/trends_IIR/ema/ema.py @@ -0,0 +1,52 @@ +import math +import numpy as np + +__all__ = ["ema"] + +EPSILON = 1e-10 # bias-compensator cutoff + +def ema(source, period: int = 10, *, alpha: float | None = None) -> np.ndarray: + """Bias-compensated EMA. + + Use *period* (default) or explicit *alpha* (keyword-only). + If *alpha* is given, *period* is ignored. + """ + if alpha is not None: + if not (0.0 < alpha <= 1.0): + raise ValueError(f"alpha must be in (0, 1], got {alpha}") + else: + if period <= 0: + raise ValueError(f"period must be > 0, got {period}") + alpha = 2.0 / (period + 1) + + src = np.asarray(source, dtype=np.float64) + if src.ndim == 0 or src.size == 0: + raise ValueError("source must not be empty") + src = src.ravel() + + out = np.empty(len(src), dtype=np.float64) + decay = 1.0 - alpha + ema_val = 0.0 + e = 1.0 + last_valid = 0.0 + has_valid = False + + for i, v in enumerate(src): + if math.isfinite(v): + last_valid = v + has_valid = True + elif has_valid: + v = last_valid + else: + out[i] = math.nan + continue + + ema_val = ema_val * decay + alpha * v + + if e > EPSILON: + e *= decay + out[i] = ema_val / (1.0 - e) + else: + out[i] = ema_val + + return out diff --git a/lib/trends_IIR/ema/ema_test.py b/lib/trends_IIR/ema/ema_test.py new file mode 100644 index 00000000..e0c28f0a --- /dev/null +++ b/lib/trends_IIR/ema/ema_test.py @@ -0,0 +1,143 @@ +"""Unit tests for pure-Python EMA implementation. + +Per PYTHON_FALLBACK_SPEC §5: co-located _test.py + +Run:: + + pytest lib/trends_IIR/ema/ema_test.py -v +""" + +import math +import sys +from pathlib import Path + +import numpy as np +import pytest + +# Import from co-located ema.py +sys.path.insert(0, str(Path(__file__).parent)) +from ema import ema # noqa: E402 + + +# ── basic correctness ── + +def test_known_values(): + """Hand-calculated EMA(3) with bias compensation. + + alpha=0.5, decay=0.5: + Bar 0: acc = 0.5*10 = 5, E = 0.5, result = 5/0.5 = 10.0 + Bar 1: acc = 5*0.5 + 0.5*20 = 12.5, E = 0.25, result = 12.5/0.75 ≈ 16.667 + Bar 2: acc = 12.5*0.5 + 0.5*30 = 21.25, E = 0.125, result = 21.25/0.875 ≈ 24.286 + """ + data = np.array([10.0, 20.0, 30.0, 40.0, 50.0]) + result = ema(data, period=3) + assert result[0] == pytest.approx(10.0, rel=1e-12) + assert result[1] == pytest.approx(16.666666666666668, rel=1e-10) + assert result[2] == pytest.approx(24.285714285714285, rel=1e-10) + + +def test_period_1(): + """Period=1 → alpha=1.0 → output equals input (no smoothing).""" + data = np.array([10.0, 20.0, 30.0, 40.0, 50.0]) + result = ema(data, period=1) + np.testing.assert_array_equal(result, data) + + +def test_constant_input(): + """Constant 100.0 through any EMA → always 100.0.""" + data = np.full(100, 100.0) + result = ema(data, period=20) + np.testing.assert_allclose(result, 100.0, rtol=1e-12) + + +# ── edge cases ── + +def test_empty_array(): + """Empty input → raises ValueError.""" + with pytest.raises(ValueError, match="must not be empty"): + ema(np.array([]), period=5) + + +def test_invalid_period(): + """Period ≤ 0 → raises ValueError.""" + with pytest.raises(ValueError, match="period must be > 0"): + ema(np.array([1.0, 2.0, 3.0]), period=0) + with pytest.raises(ValueError, match="period must be > 0"): + ema(np.array([1.0, 2.0, 3.0]), period=-1) + + +def test_single_element(): + """Single-element input returns that element.""" + result = ema([42.0], period=10) + assert len(result) == 1 + assert result[0] == pytest.approx(42.0, rel=1e-12) + + +# ── NaN handling ── + +def test_nan_in_input(): + """NaN replaced with last valid value → output stays finite.""" + data = np.array([10.0, 20.0, np.nan, 40.0, 50.0]) + result = ema(data, period=3) + assert all(math.isfinite(v) for v in result) + + +def test_all_nan_returns_nan(): + """All-NaN input → all-NaN output.""" + data = np.full(5, np.nan) + result = ema(data, period=3) + assert all(math.isnan(v) for v in result) + + +def test_inf_handled(): + """Inf replaced with last valid value.""" + data = np.array([10.0, 20.0, np.inf, 40.0, 50.0]) + result = ema(data, period=3) + assert all(math.isfinite(v) for v in result) + + +# ── output shape & warmup ── + +def test_output_length_matches_input(): + """len(output) == len(input).""" + data = np.random.default_rng(42).normal(100, 5, size=200) + result = ema(data, period=14) + assert len(result) == 200 + + +def test_first_bar_always_valid(): + """Bias compensation means EMA produces valid output from bar 0.""" + data = np.random.default_rng(42).normal(100, 5, size=50) + result = ema(data, period=50) + assert math.isfinite(result[0]) + + +# ── numerical precision ── + +def test_large_values(): + """No overflow with 1e300 values.""" + data = np.full(100, 1e300) + result = ema(data, period=10) + np.testing.assert_allclose(result, 1e300, rtol=1e-10) + + +def test_tiny_values(): + """No underflow with 1e-300 values.""" + data = np.full(100, 1e-300) + result = ema(data, period=10) + np.testing.assert_allclose(result, 1e-300, rtol=1e-10) + + +def test_10k_series_all_finite(): + """Long series stays finite (no drift).""" + data = np.random.default_rng(42).normal(100, 10, size=10_000) + result = ema(data, period=20) + assert np.all(np.isfinite(result)) + + +def test_alpha_from_period_equivalence(): + """ema(period=N) == ema(alpha=2/(N+1)).""" + data = np.random.default_rng(42).normal(100, 5, size=200) + r1 = ema(data, period=14) + r2 = ema(data, alpha=2.0 / 15.0) + np.testing.assert_allclose(r1, r2, rtol=1e-14) diff --git a/lib/trends_IIR/ema/tests/test_ema.py b/lib/trends_IIR/ema/tests/test_ema.py new file mode 100644 index 00000000..30a2d753 --- /dev/null +++ b/lib/trends_IIR/ema/tests/test_ema.py @@ -0,0 +1,337 @@ +"""Tests for the pure-Python EMA implementation. + +Validates that ``ema.py`` produces results matching the C# ``Ema.Batch`` +algorithm, including bias compensation, NaN handling, and edge cases. + +Run with:: + + python -m pytest lib/trends_IIR/ema/tests/test_ema.py -v +""" + +import math +import sys +from pathlib import Path + +import numpy as np +import pytest + +# ── ensure the ema module is importable ────────────────────────────────── +# The ema.py lives one directory up from tests/ +_EMA_DIR = Path(__file__).resolve().parent.parent +if str(_EMA_DIR) not in sys.path: + sys.path.insert(0, str(_EMA_DIR)) + +from ema import ema # noqa: E402 + + +# ═════════════════════════════════════════════════════════════════════════ +# Fixtures +# ═════════════════════════════════════════════════════════════════════════ + +@pytest.fixture +def constant_series() -> np.ndarray: + """100 bars of constant value 50.0.""" + return np.full(100, 50.0) + + +@pytest.fixture +def ramp_series() -> np.ndarray: + """50 bars ramping 1..50.""" + return np.arange(1.0, 51.0) + + +@pytest.fixture +def short_series() -> np.ndarray: + """10 bars: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100].""" + return np.arange(10.0, 110.0, 10.0) + + +# ═════════════════════════════════════════════════════════════════════════ +# Input validation +# ═════════════════════════════════════════════════════════════════════════ + +class TestInputValidation: + """Guard clauses match C# ArgumentOutOfRangeException behavior.""" + + def test_period_zero_raises(self) -> None: + with pytest.raises(ValueError, match="period must be > 0"): + ema([1.0, 2.0], period=0) + + def test_period_negative_raises(self) -> None: + with pytest.raises(ValueError, match="period must be > 0"): + ema([1.0, 2.0], period=-5) + + def test_alpha_zero_raises(self) -> None: + with pytest.raises(ValueError, match="alpha must be in"): + ema([1.0, 2.0], alpha=0.0) + + def test_alpha_negative_raises(self) -> None: + with pytest.raises(ValueError, match="alpha must be in"): + ema([1.0, 2.0], alpha=-0.1) + + def test_alpha_above_one_raises(self) -> None: + with pytest.raises(ValueError, match="alpha must be in"): + ema([1.0, 2.0], alpha=1.01) + + def test_alpha_exactly_one_ok(self) -> None: + result = ema([5.0, 10.0, 15.0], alpha=1.0) + # alpha=1 means output == input (no smoothing) + np.testing.assert_array_equal(result, [5.0, 10.0, 15.0]) + + def test_empty_source_raises(self) -> None: + with pytest.raises(ValueError, match="must not be empty"): + ema([], period=10) + + def test_scalar_source_raises(self) -> None: + with pytest.raises(ValueError, match="must not be empty"): + ema(np.float64(5.0), period=10) + + +# ═════════════════════════════════════════════════════════════════════════ +# Output shape +# ═════════════════════════════════════════════════════════════════════════ + +class TestOutputShape: + """Output array must match input length exactly.""" + + def test_length_equals_input(self, ramp_series: np.ndarray) -> None: + result = ema(ramp_series, period=10) + assert len(result) == len(ramp_series) + + def test_single_element(self) -> None: + result = ema([42.0], period=5) + assert len(result) == 1 + + def test_dtype_float64(self, ramp_series: np.ndarray) -> None: + result = ema(ramp_series, period=10) + assert result.dtype == np.float64 + + def test_accepts_list_input(self) -> None: + result = ema([1.0, 2.0, 3.0], period=2) + assert len(result) == 3 + + def test_accepts_tuple_input(self) -> None: + result = ema((1.0, 2.0, 3.0), period=2) + assert len(result) == 3 + + +# ═════════════════════════════════════════════════════════════════════════ +# Bias compensation correctness +# ═════════════════════════════════════════════════════════════════════════ + +class TestBiasCompensation: + """Verify the warmup compensator E = (1-α)^t produces valid early values.""" + + def test_first_bar_equals_input(self) -> None: + """EMA(bar_0) must equal the input itself (compensated to 1×input).""" + result = ema([100.0, 200.0, 300.0], period=10) + # After compensation: ema_acc = alpha * 100, E = decay + # result[0] = (alpha * 100) / (1 - decay) = (alpha * 100) / alpha = 100 + assert result[0] == pytest.approx(100.0, rel=1e-12) + + def test_constant_series_converges_to_constant( + self, constant_series: np.ndarray + ) -> None: + """On constant input, every bar should equal the constant.""" + result = ema(constant_series, period=10) + np.testing.assert_allclose(result, 50.0, rtol=1e-12) + + def test_compensator_eliminates_zero_bias(self) -> None: + """Without compensation, starting from ema=0 would bias downward. + With compensation, bar 1 on a constant 100 series must be 100.""" + result = ema(np.full(5, 100.0), period=20) + # Every value should be exactly 100.0 (constant input) + np.testing.assert_allclose(result, 100.0, rtol=1e-12) + + def test_period_1_passthrough(self) -> None: + """Period=1 → alpha=1.0 → output equals input.""" + data = np.array([10.0, 20.0, 30.0, 40.0, 50.0]) + result = ema(data, period=1) + np.testing.assert_array_equal(result, data) + + +# ═════════════════════════════════════════════════════════════════════════ +# EMA mathematical properties +# ═════════════════════════════════════════════════════════════════════════ + +class TestMathProperties: + """Verify EMA satisfies known mathematical properties.""" + + def test_monotone_input_monotone_output(self, ramp_series: np.ndarray) -> None: + """Strictly increasing input → strictly increasing EMA.""" + result = ema(ramp_series, period=10) + diffs = np.diff(result) + assert np.all(diffs > 0), "EMA of monotone-increasing input must increase" + + def test_ema_lags_behind_ramp(self, ramp_series: np.ndarray) -> None: + """EMA of increasing ramp must be ≤ the source (lag property).""" + result = ema(ramp_series, period=10) + # After first bar, EMA should lag behind + assert np.all(result[1:] <= ramp_series[1:] + 1e-10) + + def test_ema_between_min_and_max(self, ramp_series: np.ndarray) -> None: + """EMA output must lie within [min(source), max(source)].""" + result = ema(ramp_series, period=10) + assert np.all(result >= ramp_series.min() - 1e-10) + assert np.all(result <= ramp_series.max() + 1e-10) + + def test_alpha_from_period(self) -> None: + """ema(period=N) must equal ema(alpha=2/(N+1)).""" + data = np.random.default_rng(42).normal(100, 5, size=200) + r1 = ema(data, period=14) + r2 = ema(data, alpha=2.0 / 15.0) + np.testing.assert_allclose(r1, r2, rtol=1e-14) + + def test_larger_period_smoother(self) -> None: + """Larger period → less variance in the output.""" + data = np.random.default_rng(99).normal(100, 10, size=500) + r5 = ema(data, period=5) + r50 = ema(data, period=50) + # Skip warmup region; use last 300 bars + assert np.std(r50[-300:]) < np.std(r5[-300:]) + + +# ═════════════════════════════════════════════════════════════════════════ +# NaN / Inf handling +# ═════════════════════════════════════════════════════════════════════════ + +class TestNanHandling: + """NaN/Inf inputs are replaced with last valid value (C# GetValidValue).""" + + def test_nan_in_middle(self) -> None: + data = np.array([10.0, 20.0, np.nan, 40.0, 50.0]) + result = ema(data, period=3) + assert all(math.isfinite(v) for v in result) + + def test_inf_in_middle(self) -> None: + data = np.array([10.0, 20.0, np.inf, 40.0, 50.0]) + result = ema(data, period=3) + assert all(math.isfinite(v) for v in result) + + def test_neg_inf_in_middle(self) -> None: + data = np.array([10.0, 20.0, -np.inf, 40.0, 50.0]) + result = ema(data, period=3) + assert all(math.isfinite(v) for v in result) + + def test_nan_at_start_skipped(self) -> None: + """Leading NaNs use last_valid = 0 until a finite value arrives.""" + data = np.array([np.nan, np.nan, 100.0, 200.0, 300.0]) + result = ema(data, period=3) + # First two bars use last_valid=0 initially, then seed + # After 100.0 arrives, behavior normalizes + assert math.isfinite(result[2]) + assert math.isfinite(result[4]) + + def test_all_nan_returns_nan(self) -> None: + """If every value is NaN, output must be all NaN.""" + data = np.full(5, np.nan) + result = ema(data, period=3) + assert all(math.isnan(v) for v in result) + + def test_all_inf_returns_nan(self) -> None: + """If every value is Inf, no valid seed → all NaN.""" + data = np.full(5, np.inf) + result = ema(data, period=3) + assert all(math.isnan(v) for v in result) + + +# ═════════════════════════════════════════════════════════════════════════ +# Golden values (hand-calculated reference) +# ═════════════════════════════════════════════════════════════════════════ + +class TestGoldenValues: + """Verify against hand-calculated EMA with bias compensation. + + For period=3, alpha=0.5, decay=0.5: + Bar 0: ema_acc = 0.5*10 = 5, E = 0.5, result = 5/(1-0.5) = 10.0 + Bar 1: ema_acc = 5*0.5 + 0.5*20 = 12.5, E = 0.25, result = 12.5/0.75 ≈ 16.6667 + Bar 2: ema_acc = 12.5*0.5 + 0.5*30 = 21.25, E = 0.125, result = 21.25/0.875 ≈ 24.2857 + """ + + def test_period_3_first_three_bars(self) -> None: + data = np.array([10.0, 20.0, 30.0, 40.0, 50.0]) + result = ema(data, period=3) + + assert result[0] == pytest.approx(10.0, rel=1e-12) + assert result[1] == pytest.approx(16.666666666666668, rel=1e-10) + assert result[2] == pytest.approx(24.285714285714285, rel=1e-10) + + def test_period_5_constant_100(self) -> None: + """Constant 100 through EMA(5) → all 100.0.""" + data = np.full(20, 100.0) + result = ema(data, period=5) + np.testing.assert_allclose(result, 100.0, rtol=1e-12) + + def test_ema_alpha_direct(self) -> None: + """ema(alpha=0.5) on [10,20,30] → same as period=3.""" + data = np.array([10.0, 20.0, 30.0]) + r1 = ema(data, period=3) + r2 = ema(data, alpha=0.5) + np.testing.assert_allclose(r1, r2, rtol=1e-14) + + +# ═════════════════════════════════════════════════════════════════════════ +# Stability and performance +# ═════════════════════════════════════════════════════════════════════════ + +class TestStability: + """Long series shouldn't drift or produce non-finite values.""" + + def test_10k_bars_all_finite(self) -> None: + rng = np.random.default_rng(42) + data = rng.normal(100, 10, size=10_000) + result = ema(data, period=20) + assert np.all(np.isfinite(result)) + + def test_large_values_no_overflow(self) -> None: + data = np.full(100, 1e300) + result = ema(data, period=10) + np.testing.assert_allclose(result, 1e300, rtol=1e-10) + + def test_tiny_values_no_underflow(self) -> None: + data = np.full(100, 1e-300) + result = ema(data, period=10) + np.testing.assert_allclose(result, 1e-300, rtol=1e-10) + + def test_alternating_sign(self) -> None: + """Alternating +100 / -100 should converge toward 0 for large period.""" + data = np.array([100.0, -100.0] * 500) + result = ema(data, period=100) + # Last few values should be near zero + assert abs(result[-1]) < 20.0 + + +# ═════════════════════════════════════════════════════════════════════════ +# Cross-validation with C# native (when available) +# ═════════════════════════════════════════════════════════════════════════ + +class TestCrossValidation: + """Compare pure Python EMA against NativeAOT EMA (skipped if unavailable).""" + + @pytest.fixture + def native_ema(self): + """Try to import the native EMA wrapper.""" + try: + from quantalib.trends_iir import ema as native_ema_fn + return native_ema_fn + except (ImportError, OSError): + pytest.skip("quantalib native lib not available") + + def test_matches_native_random_data(self, native_ema) -> None: + rng = np.random.default_rng(12345) + data = rng.normal(100, 10, size=500) + py_result = ema(data, period=14) + native_result = native_ema(data, period=14) + + # Convert native result to numpy if needed + native_arr = np.asarray(native_result, dtype=np.float64) + np.testing.assert_allclose(py_result, native_arr, rtol=1e-10, + err_msg="Python EMA diverges from native") + + def test_matches_native_with_nans(self, native_ema) -> None: + data = np.array([10.0, np.nan, 30.0, 40.0, np.nan, 60.0, 70.0]) + py_result = ema(data, period=3) + native_result = native_ema(data, period=3) + native_arr = np.asarray(native_result, dtype=np.float64) + np.testing.assert_allclose(py_result, native_arr, rtol=1e-10, + err_msg="NaN handling diverges from native") diff --git a/lib/trends_IIR/frama/Frama.md b/lib/trends_IIR/frama/Frama.md index 518bb194..56e66ae1 100644 --- a/lib/trends_IIR/frama/Frama.md +++ b/lib/trends_IIR/frama/Frama.md @@ -14,9 +14,7 @@ | **Signature** | [frama_signature](frama_signature.md) | - FRAMA is John Ehlers' fractal adaptive moving average. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `pe` bars of warmup before first valid output (IsHot = true). +- **Similar:** [KAMA](../kama/kama.md), [VIDYA](../vidya/vidya.md) | **Complementary:** ADX for trend context | **Trading note:** Fractal Adaptive MA; uses fractal dimension to adjust smoothing. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. FRAMA is John Ehlers' fractal adaptive moving average. It estimates a fractal dimension from high and low ranges, then converts that dimension into a dynamic EMA alpha. The result is a moving average that tightens in trends and relaxes in noise. @@ -127,4 +125,4 @@ FRAMA is not implemented in the common TA libraries used by QuanTAlib. Validatio 1. **Period parity**: The algorithm requires even `N`. Odd values are rounded up. 2. **Warmup**: Outputs are `NaN` until `N` bars are available. 3. **Range source**: FRAMA uses High and Low ranges. Feeding Close-only data collapses the ranges. -4. **Bar correction**: Use `isNew=false` for corrections so the last bar is recomputed safely. +4. **Bar correction**: Use `isNew=false` for corrections so the last bar is recomputed safely. \ No newline at end of file diff --git a/lib/trends_IIR/gdema/Gdema.md b/lib/trends_IIR/gdema/Gdema.md index 21c6b68e..e42318c1 100644 --- a/lib/trends_IIR/gdema/Gdema.md +++ b/lib/trends_IIR/gdema/Gdema.md @@ -14,9 +14,7 @@ | **Signature** | [gdema_signature](gdema_signature.md) | - GDEMA extends the standard DEMA (Double Exponential Moving Average) with a tunable gain factor $v$ that controls the aggressiveness of lag compensa... -- Parameterized by `period` (default 10), `vfactor` (default 1.0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DEMA](../dema/dema.md), [T3](../t3/t3.md) | **Complementary:** Signal crossovers | **Trading note:** Generalized DEMA; tunable volume factor between EMA and DEMA behavior. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. GDEMA extends the standard DEMA (Double Exponential Moving Average) with a tunable gain factor $v$ that controls the aggressiveness of lag compensation. The formula $\text{GDEMA} = (1+v) \cdot \text{EMA}_1 - v \cdot \text{EMA}_2$ reduces to plain EMA when $v=0$, standard DEMA when $v=1$, and progressively more aggressive lag removal for $v>1$. This parametric flexibility allows traders to dial in the exact smoothness-responsiveness trade-off for their application, rather than being locked into DEMA's fixed 2:1 ratio. @@ -131,4 +129,4 @@ O(1) per bar. Two FMAs for EMA stages, one FMA for the combination. Fastest of t | EMA₂ pass (depends on EMA₁ output) | No | Sequential dependency on EMA₁ series | | Output combination (1+v)×E1 − v×E2 | Yes | `VFNMADD231PD` across bar series once EMA passes complete | -Both EMA passes are recursive IIR. The final linear combination is vectorizable after the two EMA sweeps. Net batch speedup: minimal (~1.1×) since combination is only 3 of 18 cycles. +Both EMA passes are recursive IIR. The final linear combination is vectorizable after the two EMA sweeps. Net batch speedup: minimal (~1.1×) since combination is only 3 of 18 cycles. \ No newline at end of file diff --git a/lib/trends_IIR/hema/Hema.md b/lib/trends_IIR/hema/Hema.md index 64a4ac05..64523ec7 100644 --- a/lib/trends_IIR/hema/Hema.md +++ b/lib/trends_IIR/hema/Hema.md @@ -14,9 +14,7 @@ | **Signature** | [hema_signature](hema_signature.md) | - HEMA is a Hull-style moving average built entirely from **exponential smoothers**. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `EstimateWarmupPeriod()` bars of warmup before first valid output (IsHot = true). +- **Similar:** [EMA](../ema/ema.md), [DEMA](../dema/dema.md) | **Complementary:** Trend following | **Trading note:** Hull-style EMA; applies Hulls lag-reduction technique to EMA. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## An EMA-domain analog of HMA with WMA-lag-matched alphas @@ -246,4 +244,4 @@ HEMA is not commonly available in mainstream TA libraries. Validation uses a **r ## References - Hull, A. "Hull Moving Average." Technical analysis methodology using WMA lag cancellation. -- Wolfram Alpha verification: EMA lag with alpha=3/(N+2) equals (N-1)/3, matching WMA(N) lag exactly. +- Wolfram Alpha verification: EMA lag with alpha=3/(N+2) equals (N-1)/3, matching WMA(N) lag exactly. \ No newline at end of file diff --git a/lib/trends_IIR/holt/Holt.md b/lib/trends_IIR/holt/Holt.md index cfde0fbb..d98ab763 100644 --- a/lib/trends_IIR/holt/Holt.md +++ b/lib/trends_IIR/holt/Holt.md @@ -14,9 +14,7 @@ | **Signature** | [holt_signature](holt_signature.md) | - Holt's exponential smoothing extends simple exponential smoothing (EMA) by adding a second equation that explicitly tracks the local trend. -- Parameterized by `period`, `gamma` (default 0). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DEMA](../dema/dema.md), [KAMA](../kama/kama.md) | **Complementary:** Forecast accuracy metrics | **Trading note:** Holt exponential smoothing; level + trend components for forecasting. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Overview @@ -131,4 +129,4 @@ Both state variables are recursive. Batch mode provides no SIMD opportunity beyo - [EMA](../ema/Ema.md) — Single exponential smoothing (level only) - [DEMA](../dema/Dema.md) — Double EMA with algebraic lag correction (different approach) -- [TEMA](../tema/Tema.md) — Triple EMA cascade +- [TEMA](../tema/Tema.md) — Triple EMA cascade \ No newline at end of file diff --git a/lib/trends_IIR/htit/Htit.md b/lib/trends_IIR/htit/Htit.md index 68cd511f..c04b3cbb 100644 --- a/lib/trends_IIR/htit/Htit.md +++ b/lib/trends_IIR/htit/Htit.md @@ -14,9 +14,7 @@ | **Signature** | [htit_signature](htit_signature.md) | - HTIT (Hilbert Transform Instantaneous Trend) is a trend-following indicator that doesn't rely on simple averaging. -- No configurable parameters; computation is stateless per bar. -- Output range: Tracks input. -- Requires `12` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MAMA](../mama/mama.md), [DEMA](../dema/dema.md) | **Complementary:** HT_DCPeriod | **Trading note:** Hilbert Transform trendline; cycle-adaptive smoothing. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HTIT (Hilbert Transform Instantaneous Trend) is a trend-following indicator that doesn't rely on simple averaging. Instead, it uses the Hilbert Transform to measure the dominant cycle period of the market and then computes a trendline that filters out that specific cycle. It adapts to the market's rhythm rather than imposing a fixed period. @@ -177,4 +175,4 @@ The differences with Skender and Ooples arise from: 1. **Initialization**: How the first few bars are handled. 2. **Precision**: Hardcoded decimals vs exact fractions. -3. **Period Constraints**: How strictly the [6, 50] bounds are enforced during intermediate steps. +3. **Period Constraints**: How strictly the [6, 50] bounds are enforced during intermediate steps. \ No newline at end of file diff --git a/lib/trends_IIR/hwma/Hwma.md b/lib/trends_IIR/hwma/Hwma.md index e20dadf2..3c6d2796 100644 --- a/lib/trends_IIR/hwma/Hwma.md +++ b/lib/trends_IIR/hwma/Hwma.md @@ -14,9 +14,7 @@ | **Signature** | [hwma_signature](hwma_signature.md) | - HWMA is an Infinite Impulse Response (IIR) filter that applies triple exponential smoothing with level (F), velocity (V), and acceleration (A) comp... -- Parameterized by `period` (default 10). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HOLT](../holt/holt.md) | **Complementary:** Seasonal analysis | **Trading note:** Holt-Winters MA; triple exponential smoothing with seasonal component. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. HWMA is an Infinite Impulse Response (IIR) filter that applies triple exponential smoothing with level (F), velocity (V), and acceleration (A) components. Unlike simple exponential smoothing which only tracks the current level, HWMA anticipates future values by extrapolating trend and trend changes. @@ -189,4 +187,4 @@ QuanTAlib validates HWMA against its PineScript reference implementation. 5. **Seasonal Confusion**: "Holt-Winters" often implies seasonal decomposition. This implementation is the non-seasonal variant focusing on level-trend-acceleration only. -6. **Parameter Sensitivity**: Small changes in β and γ significantly affect behavior. Start with the default period-based derivation before experimenting with custom values. +6. **Parameter Sensitivity**: Small changes in β and γ significantly affect behavior. Start with the default period-based derivation before experimenting with custom values. \ No newline at end of file diff --git a/lib/trends_IIR/jma/Jma.md b/lib/trends_IIR/jma/Jma.md index 24e670f3..a43352dc 100644 --- a/lib/trends_IIR/jma/Jma.md +++ b/lib/trends_IIR/jma/Jma.md @@ -14,9 +14,7 @@ | **Signature** | [jma_signature](jma_signature.md) | - JMA (Jurik Moving Average) is Mark Jurik's flagship adaptive smoother, recovered through decompilation of his proprietary AmiBroker/MetaTrader bina... -- Parameterized by `period`, `phase` (default 0), `power` (default 0.45). -- Output range: $-100$ to $+100$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [KAMA](../kama/kama.md), [FRAMA](../frama/frama.md) | **Complementary:** JMA-based bands | **Trading note:** Jurik MA; gold standard for smoothness with minimal lag. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. JMA (Jurik Moving Average) is Mark Jurik's flagship adaptive smoother, recovered through decompilation of his proprietary AmiBroker/MetaTrader binaries. Unlike forum-sourced approximations that use exponential volatility smoothing, this implementation maintains a 128-bar volatility distribution and applies percentile trimming to derive a robust reference. The result: identical behavior to Jurik's commercial software within floating-point tolerance, including spike rejection during 3-sigma events where approximations diverge by 3-4%. @@ -270,4 +268,4 @@ JMA is proprietary. No open-source library implements it. Validation is performe ## References - Jurik Research. (1998-2005). "JMA White Papers." *jurikres.com* (archived). -- Kositsin, Nikolay. (2007). "Digital Indicators for MetaTrader 4." *Alpari Forum Archives*. +- Kositsin, Nikolay. (2007). "Digital Indicators for MetaTrader 4." *Alpari Forum Archives*. \ No newline at end of file diff --git a/lib/trends_IIR/kama/Kama.md b/lib/trends_IIR/kama/Kama.md index 2a9dd019..3f9afd7d 100644 --- a/lib/trends_IIR/kama/Kama.md +++ b/lib/trends_IIR/kama/Kama.md @@ -14,9 +14,7 @@ | **Signature** | [kama_signature](kama_signature.md) | - KAMA (Kaufman's Adaptive Moving Average) is an intelligent moving average that adjusts its smoothing speed based on market noise. -- Parameterized by `period` (default 10), `fastperiod` (default 2), `slowperiod` (default 30). -- Output range: Tracks input. -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [FRAMA](../frama/frama.md), [VIDYA](../vidya/vidya.md) | **Complementary:** ADX to confirm trend | **Trading note:** Kaufmans Adaptive MA; efficiency ratio adjusts speed. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. KAMA (Kaufman's Adaptive Moving Average) is an intelligent moving average that adjusts its smoothing speed based on market noise. When the price is moving steadily (high signal-to-noise ratio), KAMA speeds up to capture the trend. When the price is chopping sideways (low signal-to-noise ratio), KAMA slows down to filter out the noise. @@ -110,4 +108,4 @@ Validated against TA-Lib, Skender, Tulip, and Ooples. | **TA-Lib** | ✅ | Matches `Kama` | | **Skender** | ✅ | Matches `GetKama` | | **Tulip** | ✅ | Matches `kama` | -| **Ooples** | ✅ | Matches `CalculateKaufmanAdaptiveMovingAverage` | +| **Ooples** | ✅ | Matches `CalculateKaufmanAdaptiveMovingAverage` | \ No newline at end of file diff --git a/lib/trends_IIR/lema/Lema.md b/lib/trends_IIR/lema/Lema.md index 9b076bc9..de9e3b25 100644 --- a/lib/trends_IIR/lema/Lema.md +++ b/lib/trends_IIR/lema/Lema.md @@ -14,9 +14,7 @@ | **Signature** | [lema_signature](lema_signature.md) | - LEMA (Leader EMA) adds a smoothed error correction to the standard EMA, creating a moving average that anticipates price movement. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [EMA](../ema/ema.md) | **Complementary:** Trend following | **Trading note:** Leading EMA; forward-shifted to reduce lag. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. LEMA (Leader EMA) adds a smoothed error correction to the standard EMA, creating a moving average that anticipates price movement. The formula $\text{LEMA} = \text{EMA}(x, N) + \text{EMA}(x - \text{EMA}(x, N), N)$ decomposes price into a smooth component (EMA) and an error component (residual), then re-smooths the error and adds it back. The re-smoothed error represents the systematic part of the EMA's tracking deficit, and adding it back shifts the output toward where the next price is likely to be. @@ -146,4 +144,4 @@ O(1) per bar. The error-tracking EMA (stage 2) reacts faster than it would as a | EMA₂ pass (on error series) | No | Recursive IIR on error series | | Final addition | Yes | `VADDPD` once both EMA series computed | -EMA₁ must complete before the error series can be computed, and EMA₂ must complete before the final addition. Single-pass vectorization is impossible. Batch speedup: error subtraction and final addition are vectorizable but represent <10% of total cost. +EMA₁ must complete before the error series can be computed, and EMA₂ must complete before the final addition. Single-pass vectorization is impossible. Batch speedup: error subtraction and final addition are vectorizable but represent <10% of total cost. \ No newline at end of file diff --git a/lib/trends_IIR/mama/Mama.md b/lib/trends_IIR/mama/Mama.md index 34b19410..a07f9fb0 100644 --- a/lib/trends_IIR/mama/Mama.md +++ b/lib/trends_IIR/mama/Mama.md @@ -15,9 +15,7 @@ - MAMA (MESA Adaptive Moving Average) is a unique adaptive moving average that uses the Hilbert Transform to determine the phase rate of change of th... -- Parameterized by `fastlimit` (default 0.5), `slowlimit` (default 0.05). -- Output range: Tracks input. -- Requires `50` bars of warmup before first valid output (IsHot = true). +- **Similar:** [FRAMA](../frama/frama.md), [KAMA](../kama/kama.md) | **Complementary:** FAMA crossover | **Trading note:** MESA Adaptive MA by Ehlers; Hilbert Transform cycle-adaptive smoothing. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. MAMA (MESA Adaptive Moving Average) is a unique adaptive moving average that uses the Hilbert Transform to determine the phase rate of change of the market cycle. It produces two outputs: MAMA (the adaptive average) and FAMA (Following Adaptive Moving Average), which acts as a slower, confirming signal. @@ -359,4 +357,4 @@ MAMA works best when combined with indicators that cover its blind spots: 5. **Precision Expectations**: Don't expect your MAMA to match TradingView or TA-Lib to the sixth decimal. It won't. Those implementations have accumulated rounding errors from 20 years of cargo-cult porting. Your values will be more accurate but numerically different. If this breaks your backtests, the backtests were fragile. -6. **Ignoring the Alpha Output**: Many traders only look at MAMA and FAMA values. The adaptive alpha itself is valuable information—it tells you how confident MAMA is in its cycle estimate. High alpha (near FastLimit) means rapid phase change and uncertainty. Low alpha (near SlowLimit) means stable, established trend. +6. **Ignoring the Alpha Output**: Many traders only look at MAMA and FAMA values. The adaptive alpha itself is valuable information—it tells you how confident MAMA is in its cycle estimate. High alpha (near FastLimit) means rapid phase change and uncertainty. Low alpha (near SlowLimit) means stable, established trend. \ No newline at end of file diff --git a/lib/trends_IIR/mavp/Mavp.md b/lib/trends_IIR/mavp/Mavp.md index 56552f85..92c27698 100644 --- a/lib/trends_IIR/mavp/Mavp.md +++ b/lib/trends_IIR/mavp/Mavp.md @@ -13,9 +13,7 @@ | **PineScript** | [mavp.pine](mavp.pine) | - MAVP applies an EMA-style exponential smoothing where the period -- and therefore the smoothing constant alpha -- changes on every bar. -- Parameterized by `minperiod` (default 2), `maxperiod` (default 30). -- Output range: Tracks input. -- Requires `maxPeriod` bars of warmup before first valid output (IsHot = true). +- **Similar:** [KAMA](../kama/kama.md), [VIDYA](../vidya/vidya.md) | **Complementary:** Adaptive period selection | **Trading note:** MA with Variable Period; dynamically adjusts lookback period. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -170,4 +168,4 @@ TA-Lib's native `MAVP` function uses SMA by default (MAType=0), not EMA. Direct - Kaufman, P. J. (2013). *Trading Systems and Methods*, 5th Ed. Wiley. Discusses adaptive moving averages. - TA-Lib documentation: [MAVP - Moving Average with Variable Period](https://ta-lib.org/function.html) -- Ehlers, J. F. (2001). *Rocket Science for Traders*. Wiley. Adaptive smoothing with variable alpha. +- Ehlers, J. F. (2001). *Rocket Science for Traders*. Wiley. Adaptive smoothing with variable alpha. \ No newline at end of file diff --git a/lib/trends_IIR/mcnma/Mcnma.md b/lib/trends_IIR/mcnma/Mcnma.md index 200557ed..e8affa0b 100644 --- a/lib/trends_IIR/mcnma/Mcnma.md +++ b/lib/trends_IIR/mcnma/Mcnma.md @@ -14,9 +14,7 @@ | **Signature** | [mcnma_signature](mcnma_signature.md) | - MCNMA computes $2 \times \text{TEMA}(x, N) - \text{TEMA}(\text{TEMA}(x, N), N)$, applying the DEMA lag-cancellation technique to TEMA itself. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SMA](../sma/sma.md) | **Complementary:** Trend detection | **Trading note:** McNicholl MA; modified SMA calculation for improved response. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. MCNMA computes $2 \times \text{TEMA}(x, N) - \text{TEMA}(\text{TEMA}(x, N), N)$, applying the DEMA lag-cancellation technique to TEMA itself. This requires six cascaded EMA stages: three for the inner TEMA and three for the outer TEMA of the inner TEMA's output. The result is an extremely responsive moving average that tracks fast trends with minimal lag, at the cost of significant overshoot on reversals. Published by Dennis McNicholl in "Better Bollinger Bands" (*Futures Magazine*, October 1998) as a component for improved volatility band construction. @@ -150,4 +148,4 @@ O(1) per bar. Six EMA stages plus two TEMA constructions and the final differenc | TEMA combinations (×2) | Yes | `VFNMADD` after EMA stages; constant coefficients | | Final 2×TEMA₁ − TEMA₂ | Yes | `VFNMADD231PD` across bar series | -All EMA stages must complete sequentially. TEMA combinations and the final subtraction are vectorizable but represent ~28 of 52 cycles — approximately 54% of compute. Batch speedup: ~1.3× (vectorizing only the combination phases). +All EMA stages must complete sequentially. TEMA combinations and the final subtraction are vectorizable but represent ~28 of 52 cycles — approximately 54% of compute. Batch speedup: ~1.3× (vectorizing only the combination phases). \ No newline at end of file diff --git a/lib/trends_IIR/mgdi/Mgdi.md b/lib/trends_IIR/mgdi/Mgdi.md index a29d30f9..6c2d8db6 100644 --- a/lib/trends_IIR/mgdi/Mgdi.md +++ b/lib/trends_IIR/mgdi/Mgdi.md @@ -14,9 +14,7 @@ | **Signature** | [mgdi_signature](mgdi_signature.md) | - MGDI (McGinley Dynamic Indicator) looks like a moving average but operates on a fundamentally different principle. -- Parameterized by `period` (default 14), `k` (default 0.6). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [JMA](../jma/jma.md), [KAMA](../kama/kama.md) | **Complementary:** Momentum oscillators | **Trading note:** McGinley Dynamic; self-adjusts to market speed. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. MGDI (McGinley Dynamic Indicator) looks like a moving average but operates on a fundamentally different principle. Rather than using a fixed smoothing factor, it dynamically adjusts based on the ratio between price and the indicator's current value. The result is a filter that accelerates to catch breakouts while decelerating to avoid overshooting reversals—a behavior that fixed-alpha filters cannot achieve. @@ -165,4 +163,4 @@ MGDI is inherently recursive (each value depends on the previous), limiting SIMD ## References -- McGinley, J.R. (1991). "The McGinley Dynamic." *Market Technicians Association Journal*, Fall 1991. +- McGinley, J.R. (1991). "The McGinley Dynamic." *Market Technicians Association Journal*, Fall 1991. \ No newline at end of file diff --git a/lib/trends_IIR/mma/Mma.md b/lib/trends_IIR/mma/Mma.md index eb932b0b..8ebabf7b 100644 --- a/lib/trends_IIR/mma/Mma.md +++ b/lib/trends_IIR/mma/Mma.md @@ -14,9 +14,7 @@ | **Signature** | [mma_signature](mma_signature.md) | - MMA (Modified Moving Average) uses a **simple mean** as a baseline, then adds a **weighted correction** based on the position of values within the ... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SMMA](../smma/smma.md), [EMA](../ema/ema.md) | **Complementary:** RSI/ATR (use MMA internally) | **Trading note:** Modified MA (identical to SMMA/RMA); Wilders smoothing. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. MMA (Modified Moving Average) uses a **simple mean** as a baseline, then adds a **weighted correction** based on the position of values within the buffer. The weighting tilts toward newer bars without fully discarding older ones, creating a filter that sits between SMA (equal weights) and WMA (linear weights) in both lag and smoothness characteristics. @@ -175,4 +173,4 @@ The weighted sum computation is vectorizable: ## References -- PineScript reference implementation: `lib/trends_IIR/mma/mma.pine` +- PineScript reference implementation: `lib/trends_IIR/mma/mma.pine` \ No newline at end of file diff --git a/lib/trends_IIR/nma/Nma.md b/lib/trends_IIR/nma/Nma.md index 190d1691..6eea3540 100644 --- a/lib/trends_IIR/nma/Nma.md +++ b/lib/trends_IIR/nma/Nma.md @@ -14,9 +14,7 @@ | **Signature** | [nma_signature](nma_signature.md) | - NMA is an adaptive IIR filter whose smoothing ratio is derived from a volatility-weighted square-root kernel analysis of log-price movements over a... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [KAMA](../kama/kama.md), [VIDYA](../vidya/vidya.md) | **Complementary:** Noise filters | **Trading note:** Noise-elimination MA; adapts to signal-to-noise ratio. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. NMA is an adaptive IIR filter whose smoothing ratio is derived from a volatility-weighted square-root kernel analysis of log-price movements over a lookback window. When volatility concentrates in recent bars, the ratio approaches 1.0 (fast tracking). When volatility is spread uniformly, the ratio approaches $1/\sqrt{N}$ (heavy smoothing). The square-root kernel $(\sqrt{i+1} - \sqrt{i})$ gives a concave-down weighting that gently emphasizes recency, while the log-price transformation normalizes for price level, making the adaptation scale-invariant. @@ -206,4 +204,4 @@ NMA is a proprietary indicator from Sloman's *Ocean Theory*. No reference implem - Sloman, J. *Ocean Theory*. Pages 63-70. (Original NMA description.) - Kaufman, P.J. (2013). *Trading Systems and Methods*, 5th ed. Wiley. Chapter 7: Adaptive Moving Averages. -- Chande, T.S. & Kroll, S. (1994). *The New Technical Trader*. Wiley. (Adaptive filter framework.) +- Chande, T.S. & Kroll, S. (1994). *The New Technical Trader*. Wiley. (Adaptive filter framework.) \ No newline at end of file diff --git a/lib/trends_IIR/qema/Qema.md b/lib/trends_IIR/qema/Qema.md index 12f96d74..5fb37e7a 100644 --- a/lib/trends_IIR/qema/Qema.md +++ b/lib/trends_IIR/qema/Qema.md @@ -14,9 +14,7 @@ | **Signature** | [qema_signature](qema_signature.md) | - QEMA (Quad Exponential Moving Average) is a zero-lag smoothing filter that cascades four EMAs with geometrically ramped alphas and combines them us... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DEMA](../dema/dema.md), [TEMA](../tema/tema.md) | **Complementary:** Signal line crossovers | **Trading note:** Quadruple EMA; 4th-order lag reduction with overshoot risk. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. QEMA (Quad Exponential Moving Average) is a zero-lag smoothing filter that cascades four EMAs with geometrically ramped alphas and combines them using minimum-energy weights. Unlike traditional multi-stage EMAs (DEMA, TEMA) that use fixed coefficients, QEMA solves for weights that explicitly eliminate DC lag while minimizing output variance. The result is a filter that tracks linear trends with zero group delay while suppressing high-frequency noise more effectively than standard EMA cascades. @@ -358,4 +356,4 @@ Run validation: `dotnet test --filter "FullyQualifiedName~QemaValidation"` 6. **Using `isNew` Incorrectly**: For live tick updates within the same bar, use `Update(value, isNew: false)`. Use `isNew: true` (default) only when a new bar opens. Getting this wrong causes the filter to run 4× faster than intended. -7. **Overshoot on Step Changes**: Despite being "zero-lag," QEMA can overshoot on sudden step changes because the weighted sum can extrapolate beyond the input. This is the price of reduced lag. If overshoot is unacceptable, use a filter with monotonic step response (like EMA). +7. **Overshoot on Step Changes**: Despite being "zero-lag," QEMA can overshoot on sudden step changes because the weighted sum can extrapolate beyond the input. This is the price of reduced lag. If overshoot is unacceptable, use a filter with monotonic step response (like EMA). \ No newline at end of file diff --git a/lib/trends_IIR/rema/Rema.md b/lib/trends_IIR/rema/Rema.md index e38bcbf1..418cd0e0 100644 --- a/lib/trends_IIR/rema/Rema.md +++ b/lib/trends_IIR/rema/Rema.md @@ -14,9 +14,7 @@ | **Signature** | [rema_signature](rema_signature.md) | - REMA (Regularized Exponential Moving Average) combines exponential smoothing with a regularization term that penalizes deviations from the previous... -- Parameterized by `period`, `lambda` (default 0.5). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [EMA](../ema/ema.md), [DEMA](../dema/dema.md) | **Complementary:** Volatility filters | **Trading note:** Regularized EMA; lambda term reduces whipsaws. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. REMA (Regularized Exponential Moving Average) combines exponential smoothing with a regularization term that penalizes deviations from the previous trend direction. The result is a filter that responds to genuine price movements while suppressing noise-induced oscillations. Think of it as an EMA with momentum awareness: it knows where it was heading and applies a penalty for sudden course corrections. @@ -211,4 +209,4 @@ REMA is ideal when: REMA is less suitable when: - You need maximum responsiveness (use EMA instead) - You're comparing against external libraries that don't implement REMA -- You need predictable, standardized behavior across platforms +- You need predictable, standardized behavior across platforms \ No newline at end of file diff --git a/lib/trends_IIR/rgma/Rgma.md b/lib/trends_IIR/rgma/Rgma.md index 3befbf53..4a2dfe66 100644 --- a/lib/trends_IIR/rgma/Rgma.md +++ b/lib/trends_IIR/rgma/Rgma.md @@ -14,9 +14,7 @@ | **Signature** | [rgma_signature](rgma_signature.md) | - RGMA (Recursive Gaussian Moving Average) approximates Gaussian smoothing by cascading multiple identical exponential moving averages. -- Parameterized by `period`, `passes` (default 3). -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DEMA](../dema/dema.md), [TEMA](../tema/tema.md) | **Complementary:** Trend confirmation | **Trading note:** Recursive Gaussian MA; Gaussian IIR approximation for smooth trend. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. RGMA (Recursive Gaussian Moving Average) approximates Gaussian smoothing by cascading multiple identical exponential moving averages. Each pass through an EMA filter smooths the signal further, and the mathematical magic is that cascaded low-pass filters push the impulse response toward a Gaussian-like shape. You get the desirable properties of Gaussian smoothing—smooth frequency roll-off, minimal ringing, symmetric lag—without the computational cost of a true FIR convolution. @@ -231,4 +229,4 @@ RGMA is less suitable when: ## References - TradingView reference implementation: `lib/trends_IIR/rgma/rgma.pine` -- Central Limit Theorem and cascaded filter theory: Smith, S.W. *The Scientist and Engineer's Guide to Digital Signal Processing*, Chapter 15 +- Central Limit Theorem and cascaded filter theory: Smith, S.W. *The Scientist and Engineer's Guide to Digital Signal Processing*, Chapter 15 \ No newline at end of file diff --git a/lib/trends_IIR/rma/Rma.md b/lib/trends_IIR/rma/Rma.md index 80feef73..0670eb21 100644 --- a/lib/trends_IIR/rma/Rma.md +++ b/lib/trends_IIR/rma/Rma.md @@ -14,9 +14,7 @@ | **Signature** | [rma_signature](rma_signature.md) | - The Running Moving Average (RMA), also known as the Smoothed Moving Average (SMMA) or Wilder's Moving Average, is the backbone of J. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `ema.WarmupPeriod` bars of warmup before first valid output (IsHot = true). +- **Similar:** [SMMA](../smma/smma.md), [MMA](../mma/mma.md) | **Complementary:** RSI/ATR | **Trading note:** Running MA (identical to SMMA); Wilders original smoothing method. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Running Moving Average (RMA), also known as the Smoothed Moving Average (SMMA) or Wilder's Moving Average, is the backbone of J. Welles Wilder's most famous indicators: RSI, ATR, and ADX. It is functionally identical to an Exponential Moving Average (EMA), but with a smoothing factor ($\alpha$) of $1/N$ instead of $2/(N+1)$. This results in a longer "memory" and slower decay than a standard EMA of the same period. @@ -111,4 +109,4 @@ Validated against Skender and Ooples. 1. **Initialization**: Like EMA, RMA requires a "warmup" period to converge. Wilder often initialized with a Simple Moving Average (SMA) of the first $N$ bars. QuanTAlib follows this convention. 2. **Naming**: Often called SMMA (Smoothed Moving Average) in other libraries. -3. **Period Mismatch**: Using an EMA(14) where an RMA(14) is expected will result in a much faster-moving line (equivalent to RMA(7.5)). +3. **Period Mismatch**: Using an EMA(14) where an RMA(14) is expected will result in a much faster-moving line (equivalent to RMA(7.5)). \ No newline at end of file diff --git a/lib/trends_IIR/t3/T3.md b/lib/trends_IIR/t3/T3.md index 5d2e0a9c..ada036f1 100644 --- a/lib/trends_IIR/t3/T3.md +++ b/lib/trends_IIR/t3/T3.md @@ -14,9 +14,7 @@ | **Signature** | [t3_signature](t3_signature.md) | - The T3 Moving Average is a hyper-smooth, low-lag filter that cascades six Exponential Moving Averages (EMAs). -- Parameterized by `period`, `vfactor` (default 0.7). -- Output range: Tracks input. -- Requires `period * 6` bars of warmup before first valid output (IsHot = true). +- **Similar:** [TEMA](../tema/tema.md), [DEMA](../dema/dema.md) | **Complementary:** Signal line crossover | **Trading note:** Tillsons T3; generalized DEMA with volume factor. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The T3 Moving Average is a hyper-smooth, low-lag filter that cascades six Exponential Moving Averages (EMAs). Unlike standard cascading (which increases lag), T3 uses a "Volume Factor" ($v$) to weight the EMAs in a way that partially cancels out the lag, resulting in a curve that is smoother than an EMA but more responsive than an SMA. @@ -116,4 +114,4 @@ T3 is inherently recursive due to 6 cascaded EMAs. SIMD parallelization across b 1. **Warmup**: Because it cascades 6 EMAs, T3 takes significantly longer to stabilize than a standard EMA. A T3(10) might need 60+ bars to converge. 2. **Overshoot**: With high $v$ values ($>1$), T3 can overshoot price turns, creating false breakout signals. -3. **Complexity**: It is computationally heavier than SMA or EMA (approx 6x ops), though still negligible on modern CPUs. +3. **Complexity**: It is computationally heavier than SMA or EMA (approx 6x ops), though still negligible on modern CPUs. \ No newline at end of file diff --git a/lib/trends_IIR/trama/Trama.md b/lib/trends_IIR/trama/Trama.md index 0fd2bc36..e00cad65 100644 --- a/lib/trends_IIR/trama/Trama.md +++ b/lib/trends_IIR/trama/Trama.md @@ -14,9 +14,7 @@ | **Signature** | [trama_signature](trama_signature.md) | - TRAMA is an adaptive EMA where the smoothing factor derives from the "trend regularity" of the lookback window, measured as the fraction of bars th... -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [KAMA](../kama/kama.md), [VIDYA](../vidya/vidya.md) | **Complementary:** Volatility filters | **Trading note:** Triangular Adaptive MA; uses triangular window in adaptive mode. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. TRAMA is an adaptive EMA where the smoothing factor derives from the "trend regularity" of the lookback window, measured as the fraction of bars that produce either a new highest-high (HH) or a new lowest-low (LL). This fraction is squared to create a convex penalty: low regularity (ranging) produces near-zero smoothing (filter barely moves), while high regularity (trending) produces aggressive smoothing (filter tracks closely). Developed by LuxAlgo (TradingView, December 2020). @@ -155,4 +153,4 @@ Batch implementation uses ArrayPool-rented circular buffers for prices and event - LuxAlgo (2020). "TRAMA - Trend Regularity Adaptive Moving Average." TradingView. Published December 2020. - Kaufman, P.J. (1995). *Smarter Trading*. McGraw-Hill. Chapter 7: Adaptive Techniques. (KAMA framework, precursor to adaptive MA design.) -- Chande, T.S. (1997). *Beyond Technical Analysis*, 2nd ed. Wiley. (VIDYA and adaptive smoothing theory.) +- Chande, T.S. (1997). *Beyond Technical Analysis*, 2nd ed. Wiley. (VIDYA and adaptive smoothing theory.) \ No newline at end of file diff --git a/lib/trends_IIR/vama/Vama.md b/lib/trends_IIR/vama/Vama.md index 7755f3a4..e5e7d212 100644 --- a/lib/trends_IIR/vama/Vama.md +++ b/lib/trends_IIR/vama/Vama.md @@ -13,9 +13,7 @@ | **PineScript** | [vama.pine](vama.pine) | - Most moving averages use a fixed lookback period. -- Parameterized by `baselength` (default 20), `shortatrperiod` (default 10), `longatrperiod` (default 50), `minlength` (default 5), `maxlength` (default 100). -- Output range: Tracks input. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [VIDYA](../vidya/vidya.md), [KAMA](../kama/kama.md) | **Complementary:** Volatility analysis | **Trading note:** Volatility-Adjusted MA; scales smoothing by relative volatility. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## The Core Insight @@ -287,4 +285,4 @@ VAMA's ATR-based approach specifically responds to range expansion/contraction, ## References - Wilder, J.W. (1978). "New Concepts in Technical Trading Systems" - ATR and RMA foundations -- PineScript reference implementation: `vama.pine` +- PineScript reference implementation: `vama.pine` \ No newline at end of file diff --git a/lib/trends_IIR/vidya/Vidya.md b/lib/trends_IIR/vidya/Vidya.md index f19f4ba5..b2aa94a6 100644 --- a/lib/trends_IIR/vidya/Vidya.md +++ b/lib/trends_IIR/vidya/Vidya.md @@ -14,9 +14,7 @@ | **Signature** | [vidya_signature](vidya_signature.md) | - The Variable Index Dynamic Average (VIDYA) is an adaptive moving average that automatically adjusts its smoothing speed based on market volatility. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [KAMA](../kama/kama.md), [FRAMA](../frama/frama.md) | **Complementary:** CMO (used internally) | **Trading note:** Chandes Variable Index Dynamic Average; adapts via CMO ratio. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Variable Index Dynamic Average (VIDYA) is an adaptive moving average that automatically adjusts its smoothing speed based on market volatility. When the market is trending (high volatility), VIDYA speeds up to capture the move. When the market is ranging (low volatility), it slows down to filter out the noise. @@ -117,4 +115,4 @@ VIDYA is an IIR filter with CMO-driven adaptive alpha — not vectorizable acros 1. **Flatlining**: In extremely choppy, sideways markets, CMO can approach 0, causing VIDYA to flatline completely. This is a feature, not a bug. 2. **Sensitivity**: VIDYA is highly sensitive to the period chosen for the CMO. A short period makes it jittery; a long period makes it sluggish. -3. **Comparison**: Often compared to KAMA (Kaufman). KAMA uses Efficiency Ratio (ER); VIDYA uses CMO. They are conceptually similar but mathematically distinct. +3. **Comparison**: Often compared to KAMA (Kaufman). KAMA uses Efficiency Ratio (ER); VIDYA uses CMO. They are conceptually similar but mathematically distinct. \ No newline at end of file diff --git a/lib/trends_IIR/yzvama/Yzvama.md b/lib/trends_IIR/yzvama/Yzvama.md index 547a89b9..c190616d 100644 --- a/lib/trends_IIR/yzvama/Yzvama.md +++ b/lib/trends_IIR/yzvama/Yzvama.md @@ -13,9 +13,7 @@ | **PineScript** | [yzvama.pine](yzvama.pine) | - Most adaptive moving averages measure volatility using close-to-close changes (standard deviation) or high-low ranges (ATR). -- Parameterized by `yzvshortperiod` (default 3), `yzvlongperiod` (default 50), `percentilelookback` (default 100), `minlength` (default 5), `maxlength` (default 100). -- Output range: Tracks input. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [VAMA](../vama/vama.md), [VIDYA](../vidya/vidya.md) | **Complementary:** Yang-Zhang volatility | **Trading note:** Yang-Zhang Volatility-Adjusted MA; adapts using YZ volatility estimator. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## The Core Insight @@ -427,4 +425,4 @@ Percentile ranking solves both: - Yang, D., & Zhang, Q. (2000). "Drift-Independent Volatility Estimation Based on High, Low, Open, and Close Prices." *Journal of Business*, 73(3), 477-491. - Rogers, L.C.G., & Satchell, S.E. (1991). "Estimating Variance from High, Low and Closing Prices." *Annals of Applied Probability*, 1(4), 504-512. -- PineScript reference implementation: `yzvama.pine` +- PineScript reference implementation: `yzvama.pine` \ No newline at end of file diff --git a/lib/trends_IIR/zldema/Zldema.md b/lib/trends_IIR/zldema/Zldema.md index 9e5994b3..a8926561 100644 --- a/lib/trends_IIR/zldema/Zldema.md +++ b/lib/trends_IIR/zldema/Zldema.md @@ -14,9 +14,7 @@ | **Signature** | [zldema_signature](zldema_signature.md) | - ZLDEMA takes a standard DEMA and feeds it a **zero-lag signal**: current price minus a lagged price. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `Math.Max(lag + 1, EstimateWarmupPeriod(beta))` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ZLEMA](../zlema/zlema.md), [DEMA](../dema/dema.md) | **Complementary:** Signal line crossovers | **Trading note:** Zero-Lag DEMA; combines zero-lag with double-exponential. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## DEMA with lag compensation via a zero-lag signal @@ -164,4 +162,4 @@ ZLDEMA is validated against a PineScript reference implementation. 5. **DEMA vs ZLDEMA** - ZLDEMA is not simply DEMA with a different alpha. The zero-lag preprocessing fundamentally changes the input signal, making ZLDEMA more responsive but also more prone to overshoot than standard DEMA. + ZLDEMA is not simply DEMA with a different alpha. The zero-lag preprocessing fundamentally changes the input signal, making ZLDEMA more responsive but also more prone to overshoot than standard DEMA. \ No newline at end of file diff --git a/lib/trends_IIR/zlema/Zlema.md b/lib/trends_IIR/zlema/Zlema.md index 83c60a29..46ff3ec2 100644 --- a/lib/trends_IIR/zlema/Zlema.md +++ b/lib/trends_IIR/zlema/Zlema.md @@ -14,9 +14,7 @@ | **Signature** | [zlema_signature](zlema_signature.md) | - ZLEMA takes a standard EMA and feeds it a **zero-lag signal**: current price minus a lagged price. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `Math.Max(lag + 1, EstimateWarmupPeriod(beta))` bars of warmup before first valid output (IsHot = true). +- **Similar:** [DEMA](../dema/dema.md), [HMA](../../trends_FIR/hma/hma.md) | **Complementary:** Momentum confirmation | **Trading note:** Zero-Lag EMA; pre-adjusts input to remove delay. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## EMA with lag compensation via a zero-lag signal @@ -143,4 +141,4 @@ ZLEMA is validated against a PineScript reference implementation. 4. **Non-finite data** - NaN or Infinity is replaced with the last valid value. Before the first valid sample, output is `NaN`. + NaN or Infinity is replaced with the last valid value. Before the first valid sample, output is `NaN`. \ No newline at end of file diff --git a/lib/trends_IIR/zltema/Zltema.md b/lib/trends_IIR/zltema/Zltema.md index 109e7a5c..ba18195a 100644 --- a/lib/trends_IIR/zltema/Zltema.md +++ b/lib/trends_IIR/zltema/Zltema.md @@ -14,9 +14,7 @@ | **Signature** | [zltema_signature](zltema_signature.md) | - ZLTEMA takes a standard TEMA and feeds it a **zero-lag signal**: current price minus a lagged price. -- Parameterized by `period`. -- Output range: Tracks input. -- Requires `Math.Max(lag + 1, EstimateWarmupPeriod(beta))` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ZLEMA](../zlema/zlema.md), [TEMA](../tema/tema.md) | **Complementary:** Signal line crossovers | **Trading note:** Zero-Lag TEMA; combines zero-lag with triple-exponential. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## TEMA with lag compensation via a zero-lag signal @@ -173,4 +171,4 @@ ZLTEMA is validated against a PineScript reference implementation. 6. **ZLDEMA vs ZLTEMA** - ZLTEMA adds a third EMA stage over ZLDEMA. This provides additional smoothing at the cost of more overshoot during reversals. Use ZLDEMA when overshoot is more concerning than noise; use ZLTEMA when maximum smoothness is required. + ZLTEMA adds a third EMA stage over ZLDEMA. This provides additional smoothing at the cost of more overshoot during reversals. Use ZLDEMA when overshoot is more concerning than noise; use ZLTEMA when maximum smoothness is required. \ No newline at end of file diff --git a/lib/volatility/adr/Adr.md b/lib/volatility/adr/Adr.md index 9f444211..a150b78d 100644 --- a/lib/volatility/adr/Adr.md +++ b/lib/volatility/adr/Adr.md @@ -13,9 +13,7 @@ | **PineScript** | [adr.pine](adr.pine) | - The Average Daily Range (ADR) measures the average distance between High and Low prices over a specified period. -- Parameterized by `period`, `method` (default adrmethod.sma). -- Output range: $\geq 0$. -- Requires `ma.WarmupPeriod` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ATR](../atr/atr.md) | **Complementary:** Session range targets | **Trading note:** Average Daily Range; intraday range expectation. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Average Daily Range (ADR) measures the average distance between High and Low prices over a specified period. Unlike its cousin ATR, ADR ignores gaps entirely. It answers a straightforward question: "How much does this asset typically move within a single bar?" @@ -148,4 +146,4 @@ O(1) sliding mean of daily ranges. Same running-sum pattern as SMA but applied t - **Confusing ADR with ATR**: They measure different things. ADR ignores gaps; ATR accounts for them. Know which you need. - **Wrong smoothing method**: SMA is stable but can jump when old values exit the window. EMA is smoother for trending volatility. Match the method to your use case. - **Scale dependence**: Like ATR, ADR is absolute. An ADR of 5 on a \$100 stock is 5% volatility; on a \$10 stock, it's 50% volatility. Normalize if comparing across assets. -- **Assuming direction**: High ADR means wide bars, not up or down. Crashes and rallies both produce high ADR. +- **Assuming direction**: High ADR means wide bars, not up or down. Crashes and rallies both produce high ADR. \ No newline at end of file diff --git a/lib/volatility/atr/Atr.md b/lib/volatility/atr/Atr.md index 0836c4fd..6625032b 100644 --- a/lib/volatility/atr/Atr.md +++ b/lib/volatility/atr/Atr.md @@ -13,9 +13,7 @@ | **PineScript** | [atr.pine](atr.pine) | - The Average True Range measures market "heat" with complete disregard for direction. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires `rma.WarmupPeriod` bars of warmup before first valid output (IsHot = true). +- **Similar:** [NATR](../natr/natr.md), [TR](../tr/tr.md) | **Complementary:** SuperTrend, Keltner Channel | **Trading note:** Wilder's ATR; most popular volatility measure. 14-period standard. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Average True Range measures market "heat" with complete disregard for direction. It ignores whether the market is screaming upward or crashing downward. ATR cares only about magnitude. When ATR is high, expect wide swings. When ATR is low, expect narrow consolidation. Most traders mistakenly use ATR to find entries. Its true power lies in exits and position sizing. ATR answers the critical question: "How far can this asset move against me in a single day?" @@ -219,4 +217,4 @@ var atr14 = new Atr(source, 14); - Wilder, J. W. (1978). *New Concepts in Technical Trading Systems*. Trend Research. Chapter: Average True Range. - Kaufman, P. (2013). *Trading Systems and Methods*. Wiley. (ATR-based position sizing) -- Kase, C. (1996). "Trading with the True Range." *Technical Analysis of Stocks & Commodities*. (TR variations) +- Kase, C. (1996). "Trading with the True Range." *Technical Analysis of Stocks & Commodities*. (TR variations) \ No newline at end of file diff --git a/lib/volatility/atrn/Atrn.md b/lib/volatility/atrn/Atrn.md index fff17d57..ef37ccd4 100644 --- a/lib/volatility/atrn/Atrn.md +++ b/lib/volatility/atrn/Atrn.md @@ -13,9 +13,7 @@ | **PineScript** | [atrn.pine](atrn.pine) | - ATRN transforms the absolute ATR into a relative measure by normalizing it to a [0,1] scale using min-max scaling over a lookback window. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [ATR](../atr/atr.md), [NATR](../natr/natr.md) | **Complementary:** Position sizing | **Trading note:** Normalized ATR; percentage-based for cross-asset comparison. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ATRN transforms the absolute ATR into a relative measure by normalizing it to a [0,1] scale using min-max scaling over a lookback window. This answers the question: "Is current volatility high or low *compared to recent history*?" @@ -151,4 +149,4 @@ ATRN is a QuanTAlib-specific indicator. Validation confirms: 3. **Regime Detection**: Use ATRN thresholds to switch between mean-reversion (low ATRN) and trend-following (high ATRN) strategies. -4. **Volatility Breakout**: Look for moves from ATRN < 0.2 to ATRN > 0.5 as potential breakout confirmation. +4. **Volatility Breakout**: Look for moves from ATRN < 0.2 to ATRN > 0.5 as potential breakout confirmation. \ No newline at end of file diff --git a/lib/volatility/bbw/Bbw.md b/lib/volatility/bbw/Bbw.md index 073b9e3b..8841600a 100644 --- a/lib/volatility/bbw/Bbw.md +++ b/lib/volatility/bbw/Bbw.md @@ -13,9 +13,7 @@ | **PineScript** | [bbw.pine](bbw.pine) | - Bollinger Band Width measures the distance between upper and lower Bollinger Bands, normalized by the middle band. -- Parameterized by `period`, `multiplier` (default 2.0). -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BBands](../../channels/bbands/bbands.md) | **Complementary:** Squeeze detection | **Trading note:** Bollinger BandWidth; quantifies band expansion/contraction. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Bollinger Band Width measures the distance between upper and lower Bollinger Bands, normalized by the middle band. When BBW is low, the bands are squeezing together, signaling compressed volatility and impending breakout. When BBW is high, the market is in an expanded volatility state. BBW transforms Bollinger Bands from a visual channel indicator into a quantifiable volatility oscillator, enabling algorithmic detection of "squeeze" conditions that often precede significant price moves. @@ -223,4 +221,4 @@ var bbw = new Bbw(source, period: 20, multiplier: 2.0); - Bollinger, J. (2001). *Bollinger on Bollinger Bands*. McGraw-Hill. (Original Bollinger Band methodology) - Bollinger, J. "Bollinger Band Width." BollingerBands.com. (BBW definition and squeeze strategy) -- Connors, L., & Raschke, L. (1995). *Street Smarts*. M. Gordon Publishing. (Squeeze trading strategies) +- Connors, L., & Raschke, L. (1995). *Street Smarts*. M. Gordon Publishing. (Squeeze trading strategies) \ No newline at end of file diff --git a/lib/volatility/bbwn/Bbwn.md b/lib/volatility/bbwn/Bbwn.md index 74fc91df..a729cfbd 100644 --- a/lib/volatility/bbwn/Bbwn.md +++ b/lib/volatility/bbwn/Bbwn.md @@ -13,9 +13,7 @@ | **PineScript** | [bbwn.pine](bbwn.pine) | - Bollinger Band Width Normalized (BBWN) extends the standard BBW by normalizing it to a [0,1] range based on historical minimum and maximum values o... -- Parameterized by `period`, `multiplier` (default 2.0), `lookback` (default 252). -- Output range: $\geq 0$. -- Requires `period + lookback` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BBW](../bbw/bbw.md) | **Complementary:** Cross-asset comparison | **Trading note:** Normalized BandWidth for cross-asset comparison. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Bollinger Band Width Normalized (BBWN) extends the standard BBW by normalizing it to a [0,1] range based on historical minimum and maximum values over a lookback period. This normalization enables better comparison across different timeframes, instruments, and market conditions, making it easier to identify relative volatility levels consistently. @@ -285,4 +283,4 @@ $$ - **CPU Complexity**: O(1) per update, O(lookback) for min/max search - **Batch Processing**: Optimized vectorized calculations available -BBWN transforms absolute volatility measurements into relative, comparable signals that work consistently across different market conditions and instruments. The normalization provides context that pure BBW cannot offer, making it particularly valuable for systematic trading strategies that need consistent volatility thresholds. +BBWN transforms absolute volatility measurements into relative, comparable signals that work consistently across different market conditions and instruments. The normalization provides context that pure BBW cannot offer, making it particularly valuable for systematic trading strategies that need consistent volatility thresholds. \ No newline at end of file diff --git a/lib/volatility/bbwp/Bbwp.md b/lib/volatility/bbwp/Bbwp.md index 94615e56..29b6dd08 100644 --- a/lib/volatility/bbwp/Bbwp.md +++ b/lib/volatility/bbwp/Bbwp.md @@ -13,9 +13,7 @@ | **PineScript** | [bbwp.pine](bbwp.pine) | - BBWP (Bollinger Band Width Percentile) measures where the current Bollinger Band Width falls within its historical distribution, expressing the res... -- Parameterized by `period`, `multiplier` (default 2.0), `lookback` (default 252). -- Output range: $\geq 0$. -- Requires `period + lookback` bars of warmup before first valid output (IsHot = true). +- **Similar:** [BBW](../bbw/bbw.md) | **Complementary:** Percentile rank | **Trading note:** BandWidth Percentile; ranks current width in historical context. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. BBWP (Bollinger Band Width Percentile) measures where the current Bollinger Band Width falls within its historical distribution, expressing the result as a percentile rank between 0 and 1. Unlike BBWN which normalizes using min/max values, BBWP uses percentile ranking which is more robust to outliers. @@ -129,4 +127,4 @@ where L = lookback period (default 252) ## References - Bollinger, J. (2001). "Bollinger on Bollinger Bands." McGraw-Hill. -- QuanTAlib PineScript reference implementation (bbwp.pine) +- QuanTAlib PineScript reference implementation (bbwp.pine) \ No newline at end of file diff --git a/lib/volatility/ccv/Ccv.md b/lib/volatility/ccv/Ccv.md index 0d619da5..d3fa43ff 100644 --- a/lib/volatility/ccv/Ccv.md +++ b/lib/volatility/ccv/Ccv.md @@ -13,9 +13,7 @@ | **PineScript** | [ccv.pine](ccv.pine) | - Close-to-Close Volatility (CCV) calculates the annualized standard deviation of logarithmic returns using only closing prices. -- Parameterized by `period`, `method` (default 1). -- Output range: $\geq 0$. -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HV](../hv/hv.md) | **Complementary:** Close-to-close analysis | **Trading note:** Close-to-Close volatility; simplest vol estimator. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Close-to-Close Volatility (CCV) calculates the annualized standard deviation of logarithmic returns using only closing prices. This is the foundational volatility measure in quantitative finance, serving as a benchmark against which more sophisticated estimators are compared. The implementation supports three smoothing methods (SMA, EMA, WMA) and annualizes using the standard √252 factor for daily data. @@ -212,4 +210,4 @@ CCV is a standard volatility measure implemented consistently across platforms: - Black, F., & Scholes, M. (1973). "The Pricing of Options and Corporate Liabilities." *Journal of Political Economy*. - Parkinson, M. (1980). "The Extreme Value Method for Estimating the Variance of the Rate of Return." *Journal of Business*. - Garman, M., & Klass, M. (1980). "On the Estimation of Security Price Volatilities from Historical Data." *Journal of Business*. -- Yang, D., & Zhang, Q. (2000). "Drift-Independent Volatility Estimation Based on High, Low, Open, and Close Prices." *Journal of Business*. +- Yang, D., & Zhang, Q. (2000). "Drift-Independent Volatility Estimation Based on High, Low, Open, and Close Prices." *Journal of Business*. \ No newline at end of file diff --git a/lib/volatility/cv/Cv.md b/lib/volatility/cv/Cv.md index e950cce4..cb6fc796 100644 --- a/lib/volatility/cv/Cv.md +++ b/lib/volatility/cv/Cv.md @@ -13,9 +13,7 @@ | **PineScript** | [cv.pine](cv.pine) | - Conditional Volatility (CV) implements the GARCH(1,1) model for volatility forecasting, the most widely used time-varying volatility model in finan... -- Parameterized by `period` (default 20), `alpha` (default 0.2), `beta` (default 0.7). -- Output range: $\geq 0$. -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HV](../hv/hv.md) | **Complementary:** Volatility analysis | **Trading note:** Coefficient of Variation; ratio of std dev to mean. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Conditional Volatility (CV) implements the GARCH(1,1) model for volatility forecasting, the most widely used time-varying volatility model in financial econometrics. Unlike simple historical volatility measures, GARCH captures two key empirical features of financial returns: volatility clustering (large moves tend to follow large moves) and mean reversion (volatility eventually returns to a long-run average). The output is annualized volatility expressed as a percentage. @@ -213,4 +211,4 @@ CV/GARCH is proprietary with no direct open-source equivalents using the same ap - Engle, R. F. (1982). "Autoregressive Conditional Heteroscedasticity with Estimates of the Variance of United Kingdom Inflation." *Econometrica*, 50(4), 987-1007. - Bollerslev, T. (1986). "Generalized Autoregressive Conditional Heteroskedasticity." *Journal of Econometrics*, 31(3), 307-327. - Engle, R. F. (2001). "GARCH 101: The Use of ARCH/GARCH Models in Applied Econometrics." *Journal of Economic Perspectives*, 15(4), 157-168. -- Hansen, P. R., & Lunde, A. (2005). "A Forecast Comparison of Volatility Models: Does Anything Beat a GARCH(1,1)?" *Journal of Applied Econometrics*, 20(7), 873-889. +- Hansen, P. R., & Lunde, A. (2005). "A Forecast Comparison of Volatility Models: Does Anything Beat a GARCH(1,1)?" *Journal of Applied Econometrics*, 20(7), 873-889. \ No newline at end of file diff --git a/lib/volatility/cvi/Cvi.md b/lib/volatility/cvi/Cvi.md index 61560417..08c20e44 100644 --- a/lib/volatility/cvi/Cvi.md +++ b/lib/volatility/cvi/Cvi.md @@ -13,9 +13,7 @@ | **PineScript** | [cvi.pine](cvi.pine) | - Chaikin's Volatility (CVI) measures the rate of change of the EMA-smoothed high-low trading range. -- Parameterized by `roclength` (default 10), `smoothlength` (default 10). -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [ATR](../atr/atr.md) | **Complementary:** BandWidth | **Trading note:** Chaikin Volatility; ROC of high-low EMA range. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Chaikin's Volatility (CVI) measures the rate of change of the EMA-smoothed high-low trading range. Unlike traditional volatility measures that focus on returns, CVI directly tracks the expansion and contraction of price ranges over time. A positive CVI indicates expanding volatility (wider trading ranges), while a negative CVI signals contracting volatility (narrower ranges). This makes CVI particularly useful for identifying breakout conditions and market transitions. @@ -244,4 +242,4 @@ Avoid range trades when: CVI rising sharply - Chaikin, M. (1966). "Stock Market Trading Systems." Various publications and interviews. - Achelis, S. B. (2000). "Technical Analysis from A to Z." McGraw-Hill. Chapter on Chaikin Volatility. -- Murphy, J. J. (1999). "Technical Analysis of the Financial Markets." New York Institute of Finance. +- Murphy, J. J. (1999). "Technical Analysis of the Financial Markets." New York Institute of Finance. \ No newline at end of file diff --git a/lib/volatility/etherm/Etherm.md b/lib/volatility/etherm/Etherm.md index 6425f1e6..f5c59850 100644 --- a/lib/volatility/etherm/Etherm.md +++ b/lib/volatility/etherm/Etherm.md @@ -13,9 +13,7 @@ | **PineScript** | [etherm.pine](etherm.pine) | - Elder's Thermometer (ETHERM) measures how far today's price bar protrudes beyond yesterday's range, capturing the maximum outward extension in either direction. -- Parameterized by `period` (default 22) for the EMA signal line. -- Output range: $\geq 0$ (same units as price). -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [ATR](../atr/atr.md) | **Complementary:** Trend detection | **Trading note:** Elder Thermometer; measures current bar's range vs previous. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Elder's Thermometer (ETHERM) measures bar-to-bar range extension — the maximum outward protrusion of the current bar beyond the previous bar's high or low. Developed by Dr. Alexander Elder, it captures only outward expansions; inward contractions clamp to zero. An EMA signal line with bias compensation provides a smoothed reference for detecting explosive moves (temperature significantly exceeding the signal). @@ -122,4 +120,4 @@ Not beneficial — the recursive EMA dependency prevents vectorization. Each bar ## References - **Elder, Alexander** (2002). *Come Into My Trading Room: A Complete Guide to Trading*, Wiley. p. 162. -- **Elder, Alexander** (1993). *Trading for a Living*, Wiley. (Earlier discussion of volatility-based stops.) +- **Elder, Alexander** (1993). *Trading for a Living*, Wiley. (Earlier discussion of volatility-based stops.) \ No newline at end of file diff --git a/lib/volatility/ewma/Ewma.md b/lib/volatility/ewma/Ewma.md index 9dfc0e1f..4cc88b51 100644 --- a/lib/volatility/ewma/Ewma.md +++ b/lib/volatility/ewma/Ewma.md @@ -13,9 +13,7 @@ | **PineScript** | [ewma.pine](ewma.pine) | - EWMA Volatility calculates market volatility using an exponentially weighted moving average of squared log returns with bias correction. -- Parameterized by `period` (default 20), `annualize` (default true), `annualperiods` (default 252). -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HV](../hv/hv.md), [ATR](../atr/atr.md) | **Complementary:** Risk management | **Trading note:** Exponentially-Weighted Moving Average volatility; RiskMetrics standard. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. EWMA Volatility calculates market volatility using an exponentially weighted moving average of squared log returns with bias correction. Unlike simple historical volatility that weights all observations equally, EWMA gives more weight to recent observations while still considering historical data, making it more responsive to current market conditions. @@ -181,4 +179,4 @@ Note: This implementation is based on the PineScript reference at `ewma.pine`. T - J.P. Morgan/Reuters. (1996). "RiskMetrics Technical Document." Fourth Edition. - Bollerslev, T. (1986). "Generalized Autoregressive Conditional Heteroskedasticity." Journal of Econometrics. -- Hull, J. (2018). "Options, Futures, and Other Derivatives." Chapter on Volatility Estimation. +- Hull, J. (2018). "Options, Futures, and Other Derivatives." Chapter on Volatility Estimation. \ No newline at end of file diff --git a/lib/volatility/gkv/Gkv.md b/lib/volatility/gkv/Gkv.md index 6f85d96c..b762c95f 100644 --- a/lib/volatility/gkv/Gkv.md +++ b/lib/volatility/gkv/Gkv.md @@ -13,9 +13,7 @@ | **PineScript** | [gkv.pine](gkv.pine) | - Garman-Klass Volatility (GKV) is a range-based volatility estimator that uses all four OHLC prices to provide more efficient volatility estimates t... -- Parameterized by `period` (default 20), `annualize` (default true), `annualperiods` (default 252). -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [YZV](../yzv/yzv.md), [HV](../hv/hv.md) | **Complementary:** Options pricing | **Trading note:** Garman-Klass; full OHLC, more efficient than close-to-close. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Garman-Klass Volatility (GKV) is a range-based volatility estimator that uses all four OHLC prices to provide more efficient volatility estimates than traditional close-to-close methods. Developed by Mark Garman and Michael Klass in 1980, this estimator achieves theoretical efficiency gains of 7-8x over simple close-to-close variance by incorporating intraday price information. The implementation includes RMA (Wilder's) smoothing with bias correction and optional annualization. @@ -292,4 +290,4 @@ Confirmation: Wait for directional move - Garman, M. B., & Klass, M. J. (1980). "On the Estimation of Security Price Volatilities from Historical Data." *Journal of Business*, 53(1), 67-78. - Parkinson, M. (1980). "The Extreme Value Method for Estimating the Variance of the Rate of Return." *Journal of Business*, 53(1), 61-65. - Rogers, L. C. G., & Satchell, S. E. (1991). "Estimating Variance from High, Low and Closing Prices." *Annals of Applied Probability*, 1(4), 504-512. -- Yang, D., & Zhang, Q. (2000). "Drift-Independent Volatility Estimation Based on High, Low, Open, and Close Prices." *Journal of Business*, 73(3), 477-491. +- Yang, D., & Zhang, Q. (2000). "Drift-Independent Volatility Estimation Based on High, Low, Open, and Close Prices." *Journal of Business*, 73(3), 477-491. \ No newline at end of file diff --git a/lib/volatility/hlv/Hlv.md b/lib/volatility/hlv/Hlv.md index 723d8ec1..19dbe0ae 100644 --- a/lib/volatility/hlv/Hlv.md +++ b/lib/volatility/hlv/Hlv.md @@ -13,9 +13,7 @@ | **PineScript** | [hlv.pine](hlv.pine) | - *Also known as: PV (Parkinson Volatility)* -- Parameterized by `period` (default 20), `annualize` (default true), `annualperiods` (default 252). -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [GKV](../gkv/gkv.md), [ATR](../atr/atr.md) | **Complementary:** ATR comparison | **Trading note:** Parkinson high-low volatility; ~5x more efficient than close-to-close. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. *Also known as: PV (Parkinson Volatility)* @@ -308,4 +306,4 @@ Note: HLV may underestimate true volatility due to drift bias - Parkinson, M. (1980). "The Extreme Value Method for Estimating the Variance of the Rate of Return." *Journal of Business*, 53(1), 61-65. - Garman, M. B., & Klass, M. J. (1980). "On the Estimation of Security Price Volatilities from Historical Data." *Journal of Business*, 53(1), 67-78. - Rogers, L. C. G., & Satchell, S. E. (1991). "Estimating Variance from High, Low and Closing Prices." *Annals of Applied Probability*, 1(4), 504-512. -- Alizadeh, S., Brandt, M. W., & Diebold, F. X. (2002). "Range-Based Estimation of Stochastic Volatility Models." *Journal of Finance*, 57(3), 1047-1091. +- Alizadeh, S., Brandt, M. W., & Diebold, F. X. (2002). "Range-Based Estimation of Stochastic Volatility Models." *Journal of Finance*, 57(3), 1047-1091. \ No newline at end of file diff --git a/lib/volatility/hv/Hv.md b/lib/volatility/hv/Hv.md index ccf6cbc6..db921b64 100644 --- a/lib/volatility/hv/Hv.md +++ b/lib/volatility/hv/Hv.md @@ -13,9 +13,7 @@ | **PineScript** | [hv.pine](hv.pine) | - Historical Volatility (HV), also known as close-to-close volatility or realized volatility, is the classical measure of price volatility using the ... -- Parameterized by `period` (default 20), `annualize` (default true), `annualperiods` (default 252). -- Output range: $\geq 0$. -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [RVI](../rvi/rvi.md), [ATR](../atr/atr.md) | **Complementary:** Implied volatility for HV/IV ratio | **Trading note:** Historical Volatility; annualized std dev of log returns. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Historical Volatility (HV), also known as close-to-close volatility or realized volatility, is the classical measure of price volatility using the standard deviation of logarithmic returns. First formalized in the early 20th century and central to the Black-Scholes option pricing model, HV remains the benchmark against which all other volatility estimators are compared. This implementation uses population standard deviation with a rolling window and optional annualization. @@ -306,4 +304,4 @@ HV is the standard for regulatory risk calculations (VaR, ES) because: - Black, F., & Scholes, M. (1973). "The Pricing of Options and Corporate Liabilities." *Journal of Political Economy*, 81(3), 637-654. - Parkinson, M. (1980). "The Extreme Value Method for Estimating the Variance of the Rate of Return." *Journal of Business*, 53(1), 61-65. - Garman, M. B., & Klass, M. J. (1980). "On the Estimation of Security Price Volatilities from Historical Data." *Journal of Business*, 53(1), 67-78. -- Merton, R. C. (1980). "On Estimating the Expected Return on the Market: An Exploratory Investigation." *Journal of Financial Economics*, 8(4), 323-361. +- Merton, R. C. (1980). "On Estimating the Expected Return on the Market: An Exploratory Investigation." *Journal of Financial Economics*, 8(4), 323-361. \ No newline at end of file diff --git a/lib/volatility/jvolty/Jvolty.md b/lib/volatility/jvolty/Jvolty.md index 4b52a56d..999e4dd1 100644 --- a/lib/volatility/jvolty/Jvolty.md +++ b/lib/volatility/jvolty/Jvolty.md @@ -13,9 +13,7 @@ | **PineScript** | [jvolty.pine](jvolty.pine) | - Jurik Volatility (JVOLTY) is the adaptive volatility component extracted from Mark Jurik's JMA algorithm. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [ATR](../atr/atr.md) | **Complementary:** JMA bands | **Trading note:** Jurik Volatility; adaptive volatility from JMA internals. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Jurik Volatility (JVOLTY) is the adaptive volatility component extracted from Mark Jurik's JMA algorithm. Unlike traditional volatility measures that treat all price movements equally, JVOLTY uses a 128-bar trimmed mean distribution to compute a robust volatility reference that rejects outliers by design. The result: a volatility measure that remains stable during flash crashes, earnings surprises, and 5-sigma events while still tracking genuine regime changes. @@ -255,4 +253,4 @@ JVOLTY is proprietary. No open-source library implements it. Validation is perfo - Jurik Research. (1998-2005). "JMA White Papers." *jurikres.com* (archived). - Kositsin, Nikolay. (2007). "Digital Indicators for MetaTrader 4." *Alpari Forum Archives*. -- Wilcox, R. R. (2012). "Introduction to Robust Estimation and Hypothesis Testing." *Academic Press*. (Trimmed mean statistics) +- Wilcox, R. R. (2012). "Introduction to Robust Estimation and Hypothesis Testing." *Academic Press*. (Trimmed mean statistics) \ No newline at end of file diff --git a/lib/volatility/jvoltyn/Jvoltyn.md b/lib/volatility/jvoltyn/Jvoltyn.md index 54a6e188..05a10af6 100644 --- a/lib/volatility/jvoltyn/Jvoltyn.md +++ b/lib/volatility/jvoltyn/Jvoltyn.md @@ -13,9 +13,7 @@ | **PineScript** | [jvoltyn.pine](jvoltyn.pine) | - Normalized Jurik Volatility (JVOLTYN) maps the raw JVOLTY dynamic exponent to a 0-100 scale. -- Parameterized by `period`. -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [JVolty](../jvolty/jvolty.md) | **Complementary:** Normalized comparison | **Trading note:** Normalized Jurik Volatility; percentage-based. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Normalized Jurik Volatility (JVOLTYN) maps the raw JVOLTY dynamic exponent to a 0-100 scale. While JVOLTY outputs values in the range [1, logParam] (where logParam is period-dependent), JVOLTYN transforms this to a universal scale where 0 represents minimum volatility and 100 represents maximum volatility. This normalization enables direct comparison across different periods and instruments. @@ -228,4 +226,4 @@ public Jvoltyn(int period = 14) ## References - Jurik Research. (1998-2005). "JMA White Papers." *jurikres.com* (archived). -- QuanTAlib. "JVOLTY: Jurik Volatility." [Documentation](../jvolty/Jvolty.md). +- QuanTAlib. "JVOLTY: Jurik Volatility." [Documentation](../jvolty/Jvolty.md). \ No newline at end of file diff --git a/lib/volatility/massi/Massi.md b/lib/volatility/massi/Massi.md index 19ac6a61..8b597e06 100644 --- a/lib/volatility/massi/Massi.md +++ b/lib/volatility/massi/Massi.md @@ -13,9 +13,7 @@ | **PineScript** | [massi.pine](massi.pine) | - The Mass Index, developed by Donald Dorsey and introduced in the June 1992 issue of *Technical Analysis of Stocks & Commodities*, identifies potent... -- Parameterized by `emalength` (default 9), `sumlength` (default 25). -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [BBW](../bbw/bbw.md) | **Complementary:** Reversal signals | **Trading note:** Mass Index; detects range bulges signaling reversals (>27 = reversal setup). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Mass Index, developed by Donald Dorsey and introduced in the June 1992 issue of *Technical Analysis of Stocks & Commodities*, identifies potential trend reversals by measuring the narrowing and widening of the range between high and low prices. Unlike directional indicators, MASSI focuses on the *pattern* of range expansion and contraction, particularly the characteristic "reversal bulge" that often precedes significant market turns. @@ -221,4 +219,4 @@ Massi.Calculate(ranges, output, emaLength: 9, sumLength: 25); - Dorsey, Donald. (1992). "The Mass Index." *Technical Analysis of Stocks & Commodities*, June 1992. - Achelis, Steven B. (2000). *Technical Analysis from A to Z*. McGraw-Hill. -- Pring, Martin J. (2002). *Technical Analysis Explained*. McGraw-Hill. +- Pring, Martin J. (2002). *Technical Analysis Explained*. McGraw-Hill. \ No newline at end of file diff --git a/lib/volatility/natr/Natr.md b/lib/volatility/natr/Natr.md index 05f2c9a1..db19ba2c 100644 --- a/lib/volatility/natr/Natr.md +++ b/lib/volatility/natr/Natr.md @@ -13,9 +13,7 @@ | **PineScript** | [natr.pine](natr.pine) | - NATR normalizes the Average True Range (ATR) as a percentage of the closing price. -- Parameterized by `period` (default 14). -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [ATR](../atr/atr.md), [ATRN](../atrn/atrn.md) | **Complementary:** Cross-asset comparison | **Trading note:** Normalized ATR as percentage of close. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. NATR normalizes the Average True Range (ATR) as a percentage of the closing price. This is mathematically identical to ATRP (Average True Range Percent)—both compute `(ATR / Close) × 100`. The difference is purely nomenclature: NATR is the term used in TA-Lib and many charting platforms. @@ -210,4 +208,4 @@ Ensures equal percentage risk per position regardless of asset price. - Wilder, J.W. (1978). *New Concepts in Technical Trading Systems*. Trend Research. - TA-Lib documentation: NATR function specification -- TradingView PineScript: `ta.natr()` implementation +- TradingView PineScript: `ta.natr()` implementation \ No newline at end of file diff --git a/lib/volatility/rsv/Rsv.md b/lib/volatility/rsv/Rsv.md index ae01a4c7..1326f0ce 100644 --- a/lib/volatility/rsv/Rsv.md +++ b/lib/volatility/rsv/Rsv.md @@ -13,9 +13,7 @@ | **PineScript** | [rsv.pine](rsv.pine) | - Rogers-Satchell Volatility (RSV) is a drift-adjusted OHLC-based volatility estimator that uses all four price points (Open, High, Low, Close) to pr... -- Parameterized by `period` (default 20), `annualize` (default true), `annualperiods` (default 252). -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HV](../hv/hv.md) | **Complementary:** Options pricing | **Trading note:** Rogers-Satchell volatility; handles drift without bias. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Rogers-Satchell Volatility (RSV) is a drift-adjusted OHLC-based volatility estimator that uses all four price points (Open, High, Low, Close) to provide more accurate volatility estimates than simpler range-based methods. Developed by L.C.G. Rogers and S.E. Satchell in 1991, this estimator is unique in its ability to account for price drift, making it particularly suitable for trending markets. The implementation uses SMA smoothing and optional annualization. @@ -352,4 +350,4 @@ rsVariance = Math.FusedMultiplyAdd(lnHO, lnHC, lnLO * lnLC); - Parkinson, M. (1980). "The Extreme Value Method for Estimating the Variance of the Rate of Return." *Journal of Business*, 53(1), 61-65. - Garman, M. B., & Klass, M. J. (1980). "On the Estimation of Security Price Volatilities from Historical Data." *Journal of Business*, 53(1), 67-78. - Yang, D., & Zhang, Q. (2000). "Drift-Independent Volatility Estimation Based on High, Low, Open, and Close Prices." *Journal of Business*, 73(3), 477-492. -- Alizadeh, S., Brandt, M. W., & Diebold, F. X. (2002). "Range-Based Estimation of Stochastic Volatility Models." *Journal of Finance*, 57(3), 1047-1091. +- Alizadeh, S., Brandt, M. W., & Diebold, F. X. (2002). "Range-Based Estimation of Stochastic Volatility Models." *Journal of Finance*, 57(3), 1047-1091. \ No newline at end of file diff --git a/lib/volatility/rv/Rv.md b/lib/volatility/rv/Rv.md index b0cbf69f..c753d3fe 100644 --- a/lib/volatility/rv/Rv.md +++ b/lib/volatility/rv/Rv.md @@ -13,9 +13,7 @@ | **PineScript** | [rv.pine](rv.pine) | - Realized Volatility (RV) measures price volatility using the sum of squared logarithmic returns over a rolling window, then applying SMA smoothing ... -- Parameterized by `period` (default 5), `smoothingperiod` (default 20), `annualize` (default true), `annualperiods` (default 252). -- Output range: $\geq 0$. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [HV](../hv/hv.md), [EWMA](../ewma/ewma.md) | **Complementary:** High-frequency analysis | **Trading note:** Realized Volatility; sum of squared returns. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Realized Volatility (RV) measures price volatility using the sum of squared logarithmic returns over a rolling window, then applying SMA smoothing for stability. Unlike traditional Historical Volatility (HV) which calculates standard deviation of returns, RV directly accumulates squared returns—the raw building blocks of variance—providing a more direct measure of realized price variation. @@ -276,4 +274,4 @@ Diverging (short < long): Volatility compression - Andersen, T. G., Bollerslev, T., Diebold, F. X., & Labys, P. (2001). "The Distribution of Realized Exchange Rate Volatility." *Journal of the American Statistical Association*, 96(453), 42-55. - Andersen, T. G., Bollerslev, T., Diebold, F. X., & Ebens, H. (2001). "The Distribution of Realized Stock Return Volatility." *Journal of Financial Economics*, 61(1), 43-76. - Barndorff-Nielsen, O. E., & Shephard, N. (2002). "Econometric Analysis of Realized Volatility and Its Use in Estimating Stochastic Volatility Models." *Journal of the Royal Statistical Society: Series B*, 64(2), 253-280. -- McAleer, M., & Medeiros, M. C. (2008). "Realized Volatility: A Review." *Econometric Reviews*, 27(1-3), 10-45. +- McAleer, M., & Medeiros, M. C. (2008). "Realized Volatility: A Review." *Econometric Reviews*, 27(1-3), 10-45. \ No newline at end of file diff --git a/lib/volatility/rvi/Rvi.md b/lib/volatility/rvi/Rvi.md index 8b529ea4..021256dd 100644 --- a/lib/volatility/rvi/Rvi.md +++ b/lib/volatility/rvi/Rvi.md @@ -14,9 +14,7 @@ - The Relative Volatility Index (RVI) implements Dorsey's **revised (1995)** version: computes original RVI separately on High and Low series, then averages. - When fed single-price data (TValue), both channels receive the same value, reducing to the original (1993) formula. -- Parameterized by `stdevLength` (default 10), `rmaLength` (default 14). -- Output range: $0$ to $100$. -- Requires `stdevLength` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HV](../hv/hv.md), [ATR](../atr/atr.md) | **Complementary:** Bollinger Bands | **Trading note:** Relative Volatility Index; direction of volatility. - Validated against FM Labs revised RVI specification. The Relative Volatility Index (RVI) is a directional volatility oscillator that distinguishes between upward and downward price volatility. Originally developed by Donald Dorsey in 1993 using close prices only, RVI was **revised in 1995** to compute separate RVI values on the High and Low price series and average them. This implementation follows the revised version: when fed OHLCV bars (TBar), it runs independent RVI channels on High and Low; when fed single prices (TValue), both channels receive the same value, reducing to the original formula. @@ -285,4 +283,4 @@ Price making lower lows + RVI making higher lows: Bullish divergence - Dorsey, D. (1993). "The Relative Volatility Index." *Technical Analysis of Stocks & Commodities*, 11(6), 253-256. - Dorsey, D. (1995). "Refining the Relative Volatility Index." *Technical Analysis of Stocks & Commodities*, 13(9). - FM Labs. "Relative Volatility Index." https://www.fmlabs.com/reference/RVI.htm (Original vs Revised versions). -- TradingView. (2024). "PineScript Reference Implementation." rvi.pine source file. +- TradingView. (2024). "PineScript Reference Implementation." rvi.pine source file. \ No newline at end of file diff --git a/lib/volatility/tr/Tr.md b/lib/volatility/tr/Tr.md index 0bbe5a15..c2c0e891 100644 --- a/lib/volatility/tr/Tr.md +++ b/lib/volatility/tr/Tr.md @@ -13,9 +13,8 @@ | **PineScript** | [tr.pine](tr.pine) | - True Range (TR) is a volatility measure that captures the maximum price movement for each bar, including any gap from the previous close. +- **Similar:** [ATR](../atr/atr.md) | **Complementary:** ATR for smoothed version | **Trading note:** True Range; single-bar volatility including gaps. - No configurable parameters; computation is stateless per bar. -- Output range: $\geq 0$. -- Requires `1` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. True Range (TR) is a volatility measure that captures the maximum price movement for each bar, including any gap from the previous close. Developed by J. Welles Wilder Jr. in 1978, TR forms the foundation for Average True Range (ATR) and numerous other volatility-based indicators. Unlike simple High-Low range, TR accounts for overnight gaps and opening jumps, providing a complete picture of price movement. @@ -289,4 +288,4 @@ If gap contribution > 50% of TR: Significant gap move - Wilder, J. W. (1978). *New Concepts in Technical Trading Systems*. Trend Research. - Kaufman, P. J. (2013). *Trading Systems and Methods* (5th ed.). Wiley. -- Murphy, J. J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. +- Murphy, J. J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. \ No newline at end of file diff --git a/lib/volatility/ui/Ui.md b/lib/volatility/ui/Ui.md index d735c502..7f41e268 100644 --- a/lib/volatility/ui/Ui.md +++ b/lib/volatility/ui/Ui.md @@ -13,9 +13,7 @@ | **PineScript** | [ui.pine](ui.pine) | - Ulcer Index (UI) is a downside volatility measure that quantifies the depth and duration of drawdowns from recent highs. -- Parameterized by `period` (default 14). -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HV](../hv/hv.md) | **Complementary:** Martin ratio | **Trading note:** Ulcer Index; measures drawdown depth and duration. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Ulcer Index (UI) is a downside volatility measure that quantifies the depth and duration of drawdowns from recent highs. Developed by Peter G. Martin in 1987, UI captures what most volatility measures miss: the pain of being underwater. Unlike standard deviation or ATR that treat upside and downside moves equally, UI measures only the decline from peaks—the psychological stress that keeps investors awake at night. @@ -263,4 +261,4 @@ Strategy B is better risk-adjusted despite lower returns - Martin, P. G., & McCann, B. B. (1989). *The Investor's Guide to Fidelity Funds*. John Wiley & Sons. - Martin, P. G. (1987). "Ulcer Index, An Alternative Approach to the Measurement of Investment Risk & Risk-Adjusted Performance." -- Kaufman, P. J. (2013). *Trading Systems and Methods* (5th ed.). Wiley. +- Kaufman, P. J. (2013). *Trading Systems and Methods* (5th ed.). Wiley. \ No newline at end of file diff --git a/lib/volatility/vov/Vov.md b/lib/volatility/vov/Vov.md index df0ea9c8..df666ea2 100644 --- a/lib/volatility/vov/Vov.md +++ b/lib/volatility/vov/Vov.md @@ -13,9 +13,7 @@ | **PineScript** | [vov.pine](vov.pine) | - Volatility of Volatility (VOV) measures the standard deviation of volatility itself, quantifying how much volatility fluctuates over time. -- Parameterized by `volatilityperiod` (default 20), `vovperiod` (default 10). -- Output range: $\geq 0$. -- Requires `volatilityPeriod + vovPeriod - 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HV](../hv/hv.md) | **Complementary:** Regime detection | **Trading note:** Volatility of Volatility; GARCH-style clustering indicator. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Volatility of Volatility (VOV) measures the standard deviation of volatility itself, quantifying how much volatility fluctuates over time. While standard volatility tells you how much prices move, VOV tells you how stable or unstable that movement pattern is. High VOV indicates volatility is erratic and unpredictable; low VOV suggests volatility is relatively stable and consistent. @@ -270,4 +268,4 @@ The formula $\sqrt{E[X^2] - E[X]^2}$ can produce small negative values due to fl - Heston, S. L. (1993). "A Closed-Form Solution for Options with Stochastic Volatility with Applications to Bond and Currency Options." *Review of Financial Studies*, 6(2), 327-343. - Gatheral, J. (2006). *The Volatility Surface: A Practitioner's Guide*. Wiley Finance. -- CBOE. "VVIX Index." Chicago Board Options Exchange white paper on volatility-of-volatility indices. +- CBOE. "VVIX Index." Chicago Board Options Exchange white paper on volatility-of-volatility indices. \ No newline at end of file diff --git a/lib/volatility/vr/Vr.md b/lib/volatility/vr/Vr.md index c36c231c..51e46a74 100644 --- a/lib/volatility/vr/Vr.md +++ b/lib/volatility/vr/Vr.md @@ -13,9 +13,7 @@ | **PineScript** | [vr.pine](vr.pine) | - Volatility Ratio (VR) measures the current bar's True Range relative to its Average True Range (ATR), providing a normalized indicator of short-ter... -- Parameterized by `period` (default 14). -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [HV](../hv/hv.md), [ATR](../atr/atr.md) | **Complementary:** Volatility regimes | **Trading note:** Volatility Ratio; current vs historical for regime detection. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Volatility Ratio (VR) measures the current bar's True Range relative to its Average True Range (ATR), providing a normalized indicator of short-term volatility expansion or contraction. Values above 1.0 indicate above-average volatility (potential breakouts), while values below 1.0 suggest below-average volatility (consolidation). This simple yet powerful ratio helps traders identify when markets are moving unusually, often preceding significant price moves. @@ -285,4 +283,4 @@ The implementation uses: - Wilder, J. W. (1978). *New Concepts in Technical Trading Systems*. Trend Research. - Kaufman, P. J. (2013). *Trading Systems and Methods* (5th ed.). John Wiley & Sons. -- Kirkpatrick, C. D., & Dahlquist, J. R. (2010). *Technical Analysis: The Complete Resource for Financial Market Technicians* (2nd ed.). FT Press. +- Kirkpatrick, C. D., & Dahlquist, J. R. (2010). *Technical Analysis: The Complete Resource for Financial Market Technicians* (2nd ed.). FT Press. \ No newline at end of file diff --git a/lib/volatility/yzv/Yzv.md b/lib/volatility/yzv/Yzv.md index ae2034b1..04a997bd 100644 --- a/lib/volatility/yzv/Yzv.md +++ b/lib/volatility/yzv/Yzv.md @@ -13,9 +13,7 @@ | **PineScript** | [yzv.pine](yzv.pine) | - Yang-Zhang Volatility is a sophisticated volatility estimator that combines overnight (close-to-open) returns with Rogers-Satchell intraday volatil... -- Parameterized by `period` (default 20). -- Output range: $\geq 0$. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [GKV](../gkv/gkv.md), [HV](../hv/hv.md) | **Complementary:** HV/IV comparison | **Trading note:** Yang-Zhang; most efficient OHLC estimator, handles gaps and drift. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Yang-Zhang Volatility is a sophisticated volatility estimator that combines overnight (close-to-open) returns with Rogers-Satchell intraday volatility to capture the full spectrum of price dynamics. Unlike simple close-to-close volatility that misses overnight gaps, or purely intraday measures that ignore opening moves, Yang-Zhang provides a theoretically unbiased estimate that remains consistent whether markets gap or drift. @@ -314,4 +312,4 @@ The implementation uses: - Yang, D., & Zhang, Q. (2000). "Drift-Independent Volatility Estimation Based on High, Low, Open, and Close Prices." *Journal of Business*, 73(3), 477-491. - Rogers, L. C. G., & Satchell, S. E. (1991). "Estimating Variance from High, Low and Closing Prices." *Annals of Applied Probability*, 1(4), 504-512. - Parkinson, M. (1980). "The Extreme Value Method for Estimating the Variance of the Rate of Return." *Journal of Business*, 53(1), 61-65. -- Garman, M. B., & Klass, M. J. (1980). "On the Estimation of Security Price Volatilities from Historical Data." *Journal of Business*, 53(1), 67-78. +- Garman, M. B., & Klass, M. J. (1980). "On the Estimation of Security Price Volatilities from Historical Data." *Journal of Business*, 53(1), 67-78. \ No newline at end of file diff --git a/lib/volume/adl/Adl.md b/lib/volume/adl/Adl.md index 15747318..b3707f1e 100644 --- a/lib/volume/adl/Adl.md +++ b/lib/volume/adl/Adl.md @@ -14,8 +14,6 @@ - The Accumulation/Distribution Line (ADL) is the bedrock of volume analysis. - No configurable parameters; computation is stateless per bar. -- Output range: Unbounded. -- Requires 1 bar of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Accumulation/Distribution Line (ADL) is the bedrock of volume analysis. It attempts to answer a single, vital question: "Are the big players buying or selling?" @@ -99,4 +97,4 @@ O(1) cumulative indicator — no window, no buffer. Throughput ~4 ns/bar. Divisi * **Gaps**: ADL ignores gaps. If a stock gaps up but closes near its low, ADL will register distribution, even if the price is higher than yesterday. * **Scale**: The absolute value of ADL is meaningless; it depends on the start date of the data. Only the *trend* and *divergence* matter. -* **Volume Spikes**: A single bad data point with erroneous volume can permanently skew the ADL. Sanitize your data. +* **Volume Spikes**: A single bad data point with erroneous volume can permanently skew the ADL. Sanitize your data. \ No newline at end of file diff --git a/lib/volume/adosc/Adosc.md b/lib/volume/adosc/Adosc.md index 13b7e4cc..587d3123 100644 --- a/lib/volume/adosc/Adosc.md +++ b/lib/volume/adosc/Adosc.md @@ -13,9 +13,7 @@ | **PineScript** | [adosc.pine](adosc.pine) | - The Chaikin Oscillator (ADOSC) is an indicator of an indicator. -- Parameterized by `fastperiod` (default 3), `slowperiod` (default 10). -- Output range: Unbounded. -- Requires `slowPeriod` bars of warmup before first valid output (IsHot = true). +- **Similar:** [CMF](../cmf/Cmf.md), [OBV](../vwad/Vwad.md) | **Complementary:** MACD for price confirmation | **Trading note:** Accumulation/Distribution Oscillator; MACD of A/D Line. Divergence with price = potential reversal. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Chaikin Oscillator (ADOSC) is an indicator of an indicator. It applies the MACD formula to the Accumulation/Distribution Line (ADL) instead of the price. @@ -95,4 +93,4 @@ Validation is performed against **TA-Lib**, **Skender**, **Tulip**, and **Ooples * **Volatility**: ADOSC is extremely volatile. It whipsaws frequently. It should never be used in isolation. * **Trend Confirmation**: Use it to confirm a trend, not to predict it. If price is rising but ADOSC is falling (divergence), the rally is running on fumes. -* **Zero Line**: Crosses above zero indicate that short-term accumulation is overpowering long-term accumulation (Bullish). Crosses below zero indicate the opposite (Bearish). +* **Zero Line**: Crosses above zero indicate that short-term accumulation is overpowering long-term accumulation (Bullish). Crosses below zero indicate the opposite (Bearish). \ No newline at end of file diff --git a/lib/volume/aobv/Aobv.md b/lib/volume/aobv/Aobv.md index 36e42193..b577116d 100644 --- a/lib/volume/aobv/Aobv.md +++ b/lib/volume/aobv/Aobv.md @@ -14,8 +14,6 @@ - Archer On-Balance Volume (AOBV) applies dual exponential smoothing to the classic On-Balance Volume indicator, creating a responsive yet noise-filt... - No configurable parameters; computation is stateless per bar. -- Output range: Unbounded. -- Requires `> SlowPeriod` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Archer On-Balance Volume (AOBV) applies dual exponential smoothing to the classic On-Balance Volume indicator, creating a responsive yet noise-filtered momentum signal. The intersection of fast and slow EMAs provides actionable crossover signals while preserving OBV's core insight: volume precedes price. @@ -187,4 +185,4 @@ AOBV is a proprietary indicator. Validation is performed against internal consis - Granville, J. (1963). *Granville's New Key to Stock Market Profits*. Prentice-Hall. - EverGet. "Archer On-Balance Volume (AOBV)." TradingView Script Library. -- StockCharts. "On Balance Volume (OBV)." [Technical Indicators](https://school.stockcharts.com/doku.php?id=technical_indicators:on_balance_volume_obv) +- StockCharts. "On Balance Volume (OBV)." [Technical Indicators](https://school.stockcharts.com/doku.php?id=technical_indicators:on_balance_volume_obv) \ No newline at end of file diff --git a/lib/volume/cmf/Cmf.md b/lib/volume/cmf/Cmf.md index e616a646..e756148c 100644 --- a/lib/volume/cmf/Cmf.md +++ b/lib/volume/cmf/Cmf.md @@ -13,9 +13,7 @@ | **PineScript** | [cmf.pine](cmf.pine) | - Chaikin Money Flow (CMF) is the normalized cousin of the Accumulation/Distribution Line. -- Parameterized by `period` (default 20). -- Output range: Unbounded. -- Requires `> period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [Adosc](../adosc/Adosc.md), [MFI](../mfi/Mfi.md) | **Complementary:** RSI | **Trading note:** Chaikin Money Flow; volume-weighted close location within H-L range. +/− indicates buying/selling pressure. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Chaikin Money Flow (CMF) is the normalized cousin of the Accumulation/Distribution Line. While ADL is cumulative and unbounded, CMF oscillates between -1 and +1, measuring the persistence of buying or selling pressure over a rolling window. @@ -122,4 +120,4 @@ The MFM/MFV calculation is fully vectorizable. The rolling sum phase is inherent ## References - Chaikin, M. (1996). "Chaikin Money Flow." *Technical Analysis of Stocks & Commodities*. -- StockCharts. "Chaikin Money Flow (CMF)." [Technical Indicators](https://school.stockcharts.com/doku.php?id=technical_indicators:chaikin_money_flow_cmf) +- StockCharts. "Chaikin Money Flow (CMF)." [Technical Indicators](https://school.stockcharts.com/doku.php?id=technical_indicators:chaikin_money_flow_cmf) \ No newline at end of file diff --git a/lib/volume/efi/Efi.md b/lib/volume/efi/Efi.md index 8270ff5e..67af3291 100644 --- a/lib/volume/efi/Efi.md +++ b/lib/volume/efi/Efi.md @@ -13,9 +13,7 @@ | **PineScript** | [efi.pine](efi.pine) | - Elder's Force Index (EFI) quantifies the buying and selling pressure behind price movements by multiplying price change by volume. -- Parameterized by `period` (default 13). -- Output range: Unbounded. -- Requires `> period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [FI](../../oscillators/fi/Fi.md), [MFI](../mfi/Mfi.md) | **Complementary:** EMA for smoothing | **Trading note:** Elder Force Index; price change × volume. Smoothed version identifies trend changes. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Elder's Force Index (EFI) quantifies the buying and selling pressure behind price movements by multiplying price change by volume. Large positive values indicate strong buying pressure (bulls in control), while large negative values reveal strong selling pressure (bears dominant). @@ -168,4 +166,4 @@ Note: Most libraries use standard EMA without bias correction, causing warmup di - Elder, A. (1993). "Trading for a Living." John Wiley & Sons. - Elder, A. (2002). "Come Into My Trading Room." John Wiley & Sons. - StockCharts. "Force Index." [Technical Indicators](https://school.stockcharts.com/doku.php?id=technical_indicators:force_index) -- Investopedia. "Force Index Definition." [Technical Analysis](https://www.investopedia.com/terms/f/force-index.asp) +- Investopedia. "Force Index Definition." [Technical Analysis](https://www.investopedia.com/terms/f/force-index.asp) \ No newline at end of file diff --git a/lib/volume/eom/Eom.md b/lib/volume/eom/Eom.md index eccf27fa..e1f1dcff 100644 --- a/lib/volume/eom/Eom.md +++ b/lib/volume/eom/Eom.md @@ -13,9 +13,7 @@ | **PineScript** | [eom.pine](eom.pine) | - Ease of Movement (EOM) quantifies how easily price moves relative to volume. -- Parameterized by `period` (default 14), `volumescale` (default 10000). -- Output range: Unbounded. -- Requires `period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [CMF](../cmf/Cmf.md), [EFI](../efi/Efi.md) | **Complementary:** ATR | **Trading note:** Ease of Movement; volume-normalized price displacement. High = price moves easily on low volume. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Ease of Movement (EOM) quantifies how easily price moves relative to volume. High positive values indicate price is advancing with little resistance (low volume relative to price range), while high negative values reveal price declining easily. Values near zero suggest price is meeting resistance, requiring substantial volume to produce movement. @@ -187,4 +185,4 @@ Note: External library implementations vary in their handling of volume scaling - Arms, R.W. Jr. (1994). "Trading Without Fear." John Wiley & Sons. - StockCharts. "Ease of Movement (EMV)." [Technical Indicators](https://school.stockcharts.com/doku.php?id=technical_indicators:ease_of_movement_emv) - Investopedia. "Ease of Movement Indicator." [Technical Analysis](https://www.investopedia.com/terms/e/easeofmovement.asp) -- TradingView Wiki. "Ease of Movement." [Pine Script Reference](https://www.tradingview.com/pine-script-reference/) +- TradingView Wiki. "Ease of Movement." [Pine Script Reference](https://www.tradingview.com/pine-script-reference/) \ No newline at end of file diff --git a/lib/volume/evwma/Evwma.md b/lib/volume/evwma/Evwma.md index 88ee2169..5e5204c9 100644 --- a/lib/volume/evwma/Evwma.md +++ b/lib/volume/evwma/Evwma.md @@ -13,9 +13,7 @@ | **PineScript** | [evwma.pine](evwma.pine) | - EVWMA (Elastic Volume Weighted Moving Average) is a volume-adaptive moving average that weights each bar's contribution to the average by its volum... -- Parameterized by `period` (default 20). -- Output range: Unbounded. -- Requires `> period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [VWMA](../vwma/Vwma.md), [VWAP](../vwap/Vwap.md) | **Complementary:** OBV | **Trading note:** Elastic Volume-Weighted MA; adapts weighting dynamically based on volume flow. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. ## Introduction @@ -169,4 +167,4 @@ Known-value tests verify manual calculations against the recursive formula. - Fries, C. P. "Elastic Volume Weighted Moving Average." Technical analysis research notes. - Granville, J. "New Key to Stock Market Profits." Prentice-Hall, 1963. (Volume analysis foundations) -- Ehlers, J. F. "Cybernetic Analysis for Stocks and Futures." Wiley, 2004. (Adaptive smoothing concepts) +- Ehlers, J. F. "Cybernetic Analysis for Stocks and Futures." Wiley, 2004. (Adaptive smoothing concepts) \ No newline at end of file diff --git a/lib/volume/iii/Iii.md b/lib/volume/iii/Iii.md index 2ecab182..e8745762 100644 --- a/lib/volume/iii/Iii.md +++ b/lib/volume/iii/Iii.md @@ -13,9 +13,7 @@ | **PineScript** | [iii.pine](iii.pine) | - The Intraday Intensity Index (III) measures buying and selling pressure by analyzing where the close price falls within the high-low range, weighte... -- Parameterized by `period` (default 14), `cumulative` (default false). -- Output range: Unbounded. -- Requires `period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [CMF](../cmf/Cmf.md), [MFI](../mfi/Mfi.md) | **Complementary:** Volume | **Trading note:** Intraday Intensity Index; measures close position within H-L range relative to volume. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Intraday Intensity Index (III) measures buying and selling pressure by analyzing where the close price falls within the high-low range, weighted by volume. Originally developed by David Bostian, this indicator quantifies whether money is flowing into or out of a security on an intraday basis. Values range from -1 (close at low, maximum selling pressure) to +1 (close at high, maximum buying pressure), multiplied by volume for magnitude. @@ -148,4 +146,4 @@ Validation focuses on internal consistency (streaming vs batch vs span modes). ## References - Bostian, D. "Intraday Intensity Index." *Technical Analysis of Stocks & Commodities*. -- Arms, R. W. (1989). "The Arms Index (TRIN)." *Dow Jones-Irwin*. +- Arms, R. W. (1989). "The Arms Index (TRIN)." *Dow Jones-Irwin*. \ No newline at end of file diff --git a/lib/volume/kvo/Kvo.md b/lib/volume/kvo/Kvo.md index 8a3405b8..f098af41 100644 --- a/lib/volume/kvo/Kvo.md +++ b/lib/volume/kvo/Kvo.md @@ -13,9 +13,7 @@ | **PineScript** | [kvo.pine](kvo.pine) | - The Klinger Volume Oscillator (KVO), developed by Stephen Klinger in the 1970s, measures the long-term trend of money flow while remaining sensitiv... -- Parameterized by `fastperiod` (default 34), `slowperiod` (default 55), `signalperiod` (default 13). -- Output range: Unbounded. -- Requires `slowPeriod` bars of warmup before first valid output (IsHot = true). +- **Similar:** [CMF](../cmf/Cmf.md), [Adosc](../adosc/Adosc.md) | **Complementary:** MACD | **Trading note:** Klinger Volume Oscillator; volume-based trend indicator. Signal line crossovers for entries. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Klinger Volume Oscillator (KVO), developed by Stephen Klinger in the 1970s, measures the long-term trend of money flow while remaining sensitive to short-term fluctuations. Unlike simple volume indicators, KVO incorporates price direction and range into its volume analysis, creating a comprehensive measure of buying and selling pressure that can identify divergences before they appear in price action. @@ -183,4 +181,4 @@ $$ - Klinger, S. (1977). "Summing Up Volume." *Stocks & Commodities Magazine*. - Murphy, J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. -- https://github.com/mihakralj/pinescript/blob/main/indicators/volume/kvo.md +- https://github.com/mihakralj/pinescript/blob/main/indicators/volume/kvo.md \ No newline at end of file diff --git a/lib/volume/mfi/Mfi.md b/lib/volume/mfi/Mfi.md index 1560564f..3eac0dec 100644 --- a/lib/volume/mfi/Mfi.md +++ b/lib/volume/mfi/Mfi.md @@ -13,9 +13,7 @@ | **PineScript** | [mfi.pine](mfi.pine) | - Money Flow Index is the volume-weighted cousin of RSI. -- Parameterized by `period` (default 14). -- Output range: Unbounded. -- Requires `> period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [RSI](../../momentum/rsi/Rsi.md), [CMF](../cmf/Cmf.md) | **Complementary:** Volume | **Trading note:** Money Flow Index; volume-weighted RSI. 80/20 overbought/oversold. Divergence signals are powerful. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Money Flow Index is the volume-weighted cousin of RSI. While RSI measures the momentum of price changes alone, MFI incorporates volume to determine whether the price movement has conviction behind it. The result is an oscillator that can identify when strong hands are accumulating or distributing. @@ -158,4 +156,4 @@ The TP and RMF calculations are fully vectorizable. The directional classificati - Quong, G. & Soudack, A. (1989). "Money Flow Index." *Technical Analysis of Stocks & Commodities*. - Investopedia. "Money Flow Index (MFI)." [Definition](https://www.investopedia.com/terms/m/mfi.asp) -- StockCharts. "Money Flow Index (MFI)." [Technical Indicators](https://school.stockcharts.com/doku.php?id=technical_indicators:money_flow_index_mfi) +- StockCharts. "Money Flow Index (MFI)." [Technical Indicators](https://school.stockcharts.com/doku.php?id=technical_indicators:money_flow_index_mfi) \ No newline at end of file diff --git a/lib/volume/nvi/Nvi.md b/lib/volume/nvi/Nvi.md index 1d6fcaf9..0b8bf076 100644 --- a/lib/volume/nvi/Nvi.md +++ b/lib/volume/nvi/Nvi.md @@ -13,9 +13,7 @@ | **PineScript** | [nvi.pine](nvi.pine) | - The Negative Volume Index tracks price changes exclusively on days when trading volume decreases compared to the previous day. -- Parameterized by `startvalue` (default 100.0). -- Output range: Unbounded. -- Requires `> 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [PVI](../pvi/Pvi.md), [OBV](../vwad/Vwad.md) | **Complementary:** 255-day MA of NVI | **Trading note:** Negative Volume Index; tracks price on low-volume days where smart money operates. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Negative Volume Index tracks price changes exclusively on days when trading volume decreases compared to the previous day. The underlying theory: institutional investors—the "smart money"—prefer to accumulate or distribute positions during quiet, low-volume periods, while retail traders drive high-volume days with more emotional, less informed decisions. @@ -195,4 +193,4 @@ NVI and PVI provide complementary signals: - Fosback, N. (1976). *Stock Market Logic*. Institute for Econometric Research. - Investopedia. "Negative Volume Index (NVI)." [Definition](https://www.investopedia.com/terms/n/nvi.asp) - StockCharts. "Negative Volume Index (NVI)." [Technical Indicators](https://school.stockcharts.com/doku.php?id=technical_indicators:negative_volume_index) -- TradingView. "PineScript ta.nvi()." [Reference](https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}nvi) +- TradingView. "PineScript ta.nvi()." [Reference](https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}nvi) \ No newline at end of file diff --git a/lib/volume/obv/Obv.md b/lib/volume/obv/Obv.md index 82765d6c..89a6352b 100644 --- a/lib/volume/obv/Obv.md +++ b/lib/volume/obv/Obv.md @@ -14,8 +14,6 @@ - On Balance Volume distills the relationship between price and volume into a single cumulative indicator. - No configurable parameters; computation is stateless per bar. -- Output range: Unbounded. -- Requires `> 2` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. On Balance Volume distills the relationship between price and volume into a single cumulative indicator. The premise is elegantly simple: volume flows into a security when it closes higher, and flows out when it closes lower. OBV tracks this flow as a running total, creating a momentum indicator that often leads price movements. @@ -196,4 +194,4 @@ The slope of OBV indicates buying/selling intensity: - Murphy, J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. - Investopedia. "On-Balance Volume (OBV)." [Definition](https://www.investopedia.com/terms/o/onbalancevolume.asp) - StockCharts. "On Balance Volume (OBV)." [Technical Indicators](https://school.stockcharts.com/doku.php?id=technical_indicators:on_balance_volume_obv) -- TradingView. "PineScript ta.obv()." [Reference](https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}obv) +- TradingView. "PineScript ta.obv()." [Reference](https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}obv) \ No newline at end of file diff --git a/lib/volume/pvd/Pvd.md b/lib/volume/pvd/Pvd.md index 600f5b7f..f2f90ba7 100644 --- a/lib/volume/pvd/Pvd.md +++ b/lib/volume/pvd/Pvd.md @@ -13,9 +13,7 @@ | **PineScript** | [pvd.pine](pvd.pine) | - Price Volume Divergence (PVD) quantifies the disagreement between price momentum and volume momentum. -- Parameterized by `priceperiod` (default 14), `volumeperiod` (default 14), `smoothingperiod` (default 3). -- Output range: Unbounded. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [PVI](../pvi/Pvi.md), [NVI](../nvi/Nvi.md) | **Complementary:** Volume | **Trading note:** Price-Volume Divergence; measures disagreement between price and volume trends. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Price Volume Divergence (PVD) quantifies the disagreement between price momentum and volume momentum. The indicator identifies situations where price movement lacks volume confirmation—a classic warning signal that the current trend may be weakening or about to reverse. @@ -200,4 +198,4 @@ PVD is a custom indicator not found in standard technical analysis libraries. Va - Dow, C. (1900-1902). *Wall Street Journal* editorials on price-volume relationships. - Murphy, J. J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. -- Achelis, S. B. (2001). *Technical Analysis from A to Z*. McGraw-Hill. +- Achelis, S. B. (2001). *Technical Analysis from A to Z*. McGraw-Hill. \ No newline at end of file diff --git a/lib/volume/pvi/Pvi.md b/lib/volume/pvi/Pvi.md index a2d33f64..1a14fe6d 100644 --- a/lib/volume/pvi/Pvi.md +++ b/lib/volume/pvi/Pvi.md @@ -13,9 +13,7 @@ | **PineScript** | [pvi.pine](pvi.pine) | - The Positive Volume Index tracks price changes exclusively on days when trading volume increases compared to the previous day. -- Parameterized by `startvalue` (default 100.0). -- Output range: Unbounded. -- Requires `> 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [NVI](../nvi/Nvi.md), [OBV](../vwad/Vwad.md) | **Complementary:** MA crossover | **Trading note:** Positive Volume Index; tracks price on high-volume days. Used with NVI for smart/uninformed money. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Positive Volume Index tracks price changes exclusively on days when trading volume increases compared to the previous day. The underlying theory: retail investors—the "uninformed crowd"—drive high-volume trading days, often reacting emotionally to news and price movements. Institutional investors prefer to operate during quieter periods to avoid moving markets. @@ -194,4 +192,4 @@ The danger signal: **PVI rising while NVI falling**. Retail enthusiasm without i - Fosback, N. (1976). *Stock Market Logic*. Institute for Econometric Research. - Investopedia. "Positive Volume Index (PVI)." [Definition](https://www.investopedia.com/terms/p/pvi.asp) - StockCharts. "Positive Volume Index (PVI)." [Technical Indicators](https://school.stockcharts.com/doku.php?id=technical_indicators:positive_volume_index) -- TradingView. "PineScript ta.pvi()." [Reference](https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}pvi) +- TradingView. "PineScript ta.pvi()." [Reference](https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}pvi) \ No newline at end of file diff --git a/lib/volume/pvo/Pvo.md b/lib/volume/pvo/Pvo.md index 0227f8dc..9e17bbe7 100644 --- a/lib/volume/pvo/Pvo.md +++ b/lib/volume/pvo/Pvo.md @@ -13,9 +13,7 @@ | **PineScript** | [pvo.pine](pvo.pine) | - The Percentage Volume Oscillator (PVO) measures the difference between two exponential moving averages of volume, expressed as a percentage of the ... -- Parameterized by `fastperiod` (default 12), `slowperiod` (default 26), `signalperiod` (default 9). -- Output range: Unbounded. -- Requires `slowPeriod` bars of warmup before first valid output (IsHot = true). +- **Similar:** [PPO](../../momentum/ppo/Ppo.md), [VO](../vo/Vo.md) | **Complementary:** Price oscillators | **Trading note:** Percentage Volume Oscillator; MACD concept applied to volume. Detects volume surges. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Percentage Volume Oscillator (PVO) measures the difference between two exponential moving averages of volume, expressed as a percentage of the slower EMA. Essentially the MACD of volume, PVO identifies whether volume is expanding (accumulation) or contracting (distribution) relative to its recent history. This percentage normalization makes it comparable across instruments with vastly different volume profiles. @@ -212,4 +210,4 @@ PVO's recursive EMA structure limits SIMD parallelization. The span-based `Calcu - Murphy, J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. - Achelis, S. (2001). *Technical Analysis from A to Z*. McGraw-Hill. - https://school.stockcharts.com/doku.php?id=technical_indicators:percentage_volume_oscillator_pvo -- https://github.com/mihakralj/pinescript/blob/main/indicators/volume/pvo.md +- https://github.com/mihakralj/pinescript/blob/main/indicators/volume/pvo.md \ No newline at end of file diff --git a/lib/volume/pvr/Pvr.md b/lib/volume/pvr/Pvr.md index 00091826..b67f9c41 100644 --- a/lib/volume/pvr/Pvr.md +++ b/lib/volume/pvr/Pvr.md @@ -14,8 +14,6 @@ - Price Volume Rank distills the price-volume relationship into a simple categorical indicator. - No configurable parameters; computation is stateless per bar. -- Output range: Unbounded. -- Requires 1 bar of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Price Volume Rank distills the price-volume relationship into a simple categorical indicator. Rather than producing a continuous value, PVR returns one of five discrete states (0-4) that classify the current bar's price and volume behavior relative to the previous bar. This creates an instant "market condition" snapshot. @@ -203,4 +201,4 @@ Track PVR distribution over rolling windows: - Arms, R. (1989). *Volume Cycles in the Stock Market*. Equis International. - Blau, W. (1995). *Momentum, Direction, and Divergence*. Wiley. - Elder, A. (1993). *Trading for a Living*. Wiley. -- Murphy, J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. +- Murphy, J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. \ No newline at end of file diff --git a/lib/volume/pvt/Pvt.md b/lib/volume/pvt/Pvt.md index 508d58d6..d0eb40df 100644 --- a/lib/volume/pvt/Pvt.md +++ b/lib/volume/pvt/Pvt.md @@ -14,8 +14,6 @@ - Price Volume Trend refines the OBV concept by weighting volume according to the percentage price change rather than using an all-or-nothing approach. - No configurable parameters; computation is stateless per bar. -- Output range: Unbounded. -- Requires `> 2` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Price Volume Trend refines the OBV concept by weighting volume according to the percentage price change rather than using an all-or-nothing approach. Where OBV assigns the entire bar's volume to either buyers or sellers, PVT scales the volume contribution by the relative price movement—a 1% move adds only 1% of volume to the running total. @@ -216,4 +214,4 @@ The default signal period is typically 14-21 bars. - Murphy, J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. - Investopedia. "Price Volume Trend (PVT)." [Definition](https://www.investopedia.com/terms/p/pricevolumetrend.asp) - StockCharts. "Price Volume Trend." [Technical Indicators](https://school.stockcharts.com/doku.php?id=technical_indicators:price_volume_trend_pvt) -- TradingView. "Volume Indicators." [Reference](https://www.tradingview.com/scripts/volume/) +- TradingView. "Volume Indicators." [Reference](https://www.tradingview.com/scripts/volume/) \ No newline at end of file diff --git a/lib/volume/tvi/Tvi.md b/lib/volume/tvi/Tvi.md index dfae95d4..c3883ff7 100644 --- a/lib/volume/tvi/Tvi.md +++ b/lib/volume/tvi/Tvi.md @@ -13,9 +13,7 @@ | **PineScript** | [tvi.pine](tvi.pine) | - Trade Volume Index refines the relationship between price and volume by introducing a threshold filter. -- Parameterized by `mintick` (default 0.125). -- Output range: Unbounded. -- Requires `> 2` bars of warmup before first valid output (IsHot = true). +- **Similar:** [OBV](../vwad/Vwad.md), [CMF](../cmf/Cmf.md) | **Complementary:** Price trend | **Trading note:** Trade Volume Index; tick-based volume accumulation. Directional volume flow. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Trade Volume Index refines the relationship between price and volume by introducing a threshold filter. Unlike OBV which responds to any price change, TVI only changes direction when price movement exceeds a minimum tick threshold. This "sticky direction" behavior filters out noise from insignificant price fluctuations, allowing the indicator to better capture genuine accumulation and distribution. @@ -231,4 +229,4 @@ The minTick should generally match or exceed the instrument's minimum price incr - Blau, W. (1995). *Momentum, Direction, and Divergence*. Wiley. - Blau, W. (1993). "The Trade Volume Index." *Technical Analysis of Stocks & Commodities*. - Achelis, S. (2001). *Technical Analysis from A to Z*. McGraw-Hill. -- TradingView. "PineScript TVI Implementation." Community Scripts. +- TradingView. "PineScript TVI Implementation." Community Scripts. \ No newline at end of file diff --git a/lib/volume/twap/Twap.md b/lib/volume/twap/Twap.md index cbf3386a..faa0c3c3 100644 --- a/lib/volume/twap/Twap.md +++ b/lib/volume/twap/Twap.md @@ -13,9 +13,7 @@ | **PineScript** | [twap.pine](twap.pine) | - Time Weighted Average Price (TWAP) calculates the average price over a period by giving equal weight to each price point, regardless of volume. -- Parameterized by `period` (default defaultperiod). -- Output range: Unbounded. -- Requires `> 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [VWAP](../vwap/Vwap.md) | **Complementary:** Volume | **Trading note:** Time-Weighted Average Price; equal time weighting vs volume weighting. Algorithmic execution benchmark. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Time Weighted Average Price (TWAP) calculates the average price over a period by giving equal weight to each price point, regardless of volume. Unlike VWAP which emphasizes high-volume periods, TWAP treats every moment as equally important. This makes it a pure temporal benchmark—ideal for evaluating execution quality when volume patterns could bias the analysis. @@ -271,4 +269,4 @@ Target: Minimize absolute slippage to achieve the unbiased average price. - Almgren, R., & Chriss, N. (2001). "Optimal Execution of Portfolio Transactions." *Journal of Risk*. - Berkowitz, S., Logue, D., & Noser, E. (1988). "The Total Cost of Transactions on the NYSE." *Journal of Finance*. - Kissell, R., & Glantz, M. (2003). *Optimal Trading Strategies*. AMACOM. -- TradingView. "PineScript TWAP Implementation." Community Scripts. +- TradingView. "PineScript TWAP Implementation." Community Scripts. \ No newline at end of file diff --git a/lib/volume/va/Va.md b/lib/volume/va/Va.md index 77b7ff75..7298b340 100644 --- a/lib/volume/va/Va.md +++ b/lib/volume/va/Va.md @@ -14,8 +14,6 @@ - Volume Accumulation (VA) measures the cumulative flow of volume weighted by where price closes relative to the bar's midpoint. - No configurable parameters; computation is stateless per bar. -- Output range: Unbounded. -- Requires `> 1` bars of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Volume Accumulation (VA) measures the cumulative flow of volume weighted by where price closes relative to the bar's midpoint. When price closes above the midpoint, volume is considered buying pressure; when below, selling pressure. The cumulative sum reveals the net directional conviction of market participants over time. @@ -246,4 +244,4 @@ var smoothedVa = new Ema(5); // 5-period smoothing - Williams, L. (1979). "How I Made One Million Dollars Last Year Trading Commodities." Windsor Books. - Granville, J. (1976). "Granville's New Strategy of Daily Stock Market Timing." Prentice-Hall. - Achelis, S. (2000). "Technical Analysis from A to Z." McGraw-Hill. -- TradingView. "PineScript Volume Accumulation." Community Reference. +- TradingView. "PineScript Volume Accumulation." Community Reference. \ No newline at end of file diff --git a/lib/volume/vf/Vf.md b/lib/volume/vf/Vf.md index 0b657e04..be2228a7 100644 --- a/lib/volume/vf/Vf.md +++ b/lib/volume/vf/Vf.md @@ -13,9 +13,7 @@ | **PineScript** | [vf.pine](vf.pine) | - Volume Force (VF) quantifies the strength of volume behind price movements by multiplying price change by volume and applying EMA smoothing with wa... -- Parameterized by `period` (default 14). -- Output range: Unbounded. -- Requires `> period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [MFI](../mfi/Mfi.md), [CMF](../cmf/Cmf.md) | **Complementary:** RSI | **Trading note:** Volume Force; measures directional volume pressure. Positive = buyers dominant. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Volume Force (VF) quantifies the strength of volume behind price movements by multiplying price change by volume and applying EMA smoothing with warmup compensation. The result is a momentum-style oscillator that distinguishes between genuine volume-backed moves and hollow price action. @@ -296,4 +294,4 @@ VF occupies a middle ground: more responsive than OBV/CMF (not cumulative), smoo - Elder, A. (1993). "Trading for a Living." John Wiley & Sons. - Ehlers, J. (2001). "Rocket Science for Traders." John Wiley & Sons. - Murphy, J. (1999). "Technical Analysis of the Financial Markets." New York Institute of Finance. -- TradingView. "PineScript Volume Force." Community Reference. +- TradingView. "PineScript Volume Force." Community Reference. \ No newline at end of file diff --git a/lib/volume/vo/Vo.md b/lib/volume/vo/Vo.md index 0d1b5c9f..549a3c69 100644 --- a/lib/volume/vo/Vo.md +++ b/lib/volume/vo/Vo.md @@ -13,9 +13,7 @@ | **PineScript** | [vo.pine](vo.pine) | - The Volume Oscillator (VO) measures the difference between two moving averages of volume, expressed as a percentage. -- Parameterized by `shortperiod` (default 5), `longperiod` (default 10), `signalperiod` (default 10). -- Output range: Unbounded. -- Requires 1 bar of warmup before first valid output (IsHot = true). +- **Similar:** [PVO](../pvo/Pvo.md), [VROC](../vroc/Vroc.md) | **Complementary:** Price confirmation | **Trading note:** Volume Oscillator; difference of two volume MAs. Confirms price moves with volume expansion. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. The Volume Oscillator (VO) measures the difference between two moving averages of volume, expressed as a percentage. It helps identify changes in volume trends and potential momentum shifts by comparing short-term volume activity against longer-term volume norms. @@ -183,4 +181,4 @@ With defaults (5, 10, 10): ~328 bytes per instance. - Murphy, J. J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. - Achelis, S. B. (2001). *Technical Analysis from A to Z*. McGraw-Hill. -- PineScript Reference: vo.pine +- PineScript Reference: vo.pine \ No newline at end of file diff --git a/lib/volume/vroc/Vroc.md b/lib/volume/vroc/Vroc.md index e25a7bcc..8475dfb9 100644 --- a/lib/volume/vroc/Vroc.md +++ b/lib/volume/vroc/Vroc.md @@ -13,9 +13,7 @@ | **PineScript** | [vroc.pine](vroc.pine) | - VROC (Volume Rate of Change) measures the percentage or absolute change in volume over a specified lookback period. -- Parameterized by `period` (default 12), `usepercent` (default true). -- Output range: Unbounded. -- Requires `> period + 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [VO](../vo/Vo.md), [PVO](../pvo/Pvo.md) | **Complementary:** Price ROC | **Trading note:** Volume Rate of Change; percentage change in volume. Spikes indicate potential breakouts. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. VROC (Volume Rate of Change) measures the percentage or absolute change in volume over a specified lookback period. Unlike moving average-based volume indicators that smooth data, VROC provides a direct comparison between current volume and historical volume, making it particularly useful for detecting sudden volume surges or contractions that may signal significant market events. @@ -145,4 +143,4 @@ Per instance: `8 bytes × (period + 1)` for the ring buffer plus ~32 bytes for s - Appel, G., & Hitschler, F. (1979). *Stock Market Trading Systems*. Dow Jones-Irwin. - Murphy, J. J. (1999). *Technical Analysis of the Financial Markets*. New York Institute of Finance. -- Achelis, S. B. (2001). *Technical Analysis from A to Z*. McGraw-Hill. +- Achelis, S. B. (2001). *Technical Analysis from A to Z*. McGraw-Hill. \ No newline at end of file diff --git a/lib/volume/vwad/Vwad.md b/lib/volume/vwad/Vwad.md index ecbb354a..afac1313 100644 --- a/lib/volume/vwad/Vwad.md +++ b/lib/volume/vwad/Vwad.md @@ -13,9 +13,7 @@ | **PineScript** | [vwad.pine](vwad.pine) | - Volume Weighted Accumulation/Distribution (VWAD) takes the classic ADL concept and asks a sharper question: not just "where did the close fall in t... -- Parameterized by `period` (default 20). -- Output range: Unbounded. -- Requires `> period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [CMF](../cmf/Cmf.md), [OBV](../vwad/Vwad.md) | **Complementary:** MACD | **Trading note:** Volume-Weighted A/D; running sum of volume-weighted price position. Classic accumulation/distribution. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Volume Weighted Accumulation/Distribution (VWAD) takes the classic ADL concept and asks a sharper question: not just "where did the close fall in the range?" but "how significant was this bar's volume compared to recent activity?" @@ -192,4 +190,4 @@ VWAD is a proprietary indicator. Validation is performed against the PineScript ## References - Chaikin, M. (1996). "Accumulation/Distribution Line." *Technical Analysis of Stocks & Commodities*. -- QuanTAlib. "Volume Weighted Accumulation/Distribution." [PineScript Reference](https://github.com/mihakralj/pinescript/blob/main/indicators/volume/vwad.md) +- QuanTAlib. "Volume Weighted Accumulation/Distribution." [PineScript Reference](https://github.com/mihakralj/pinescript/blob/main/indicators/volume/vwad.md) \ No newline at end of file diff --git a/lib/volume/vwap/Vwap.md b/lib/volume/vwap/Vwap.md index db60d55a..c52038ab 100644 --- a/lib/volume/vwap/Vwap.md +++ b/lib/volume/vwap/Vwap.md @@ -13,9 +13,7 @@ | **PineScript** | [vwap.pine](vwap.pine) | - VWAP (Volume Weighted Average Price) calculates the cumulative average price weighted by trading volume, typically reset at session boundaries. -- Parameterized by `period` (default 0). -- Output range: Unbounded. -- Requires `> 1` bars of warmup before first valid output (IsHot = true). +- **Similar:** [TWAP](../twap/Twap.md), [EVWMA](../evwma/Evwma.md) | **Complementary:** VWAP bands | **Trading note:** Volume-Weighted Average Price; institutional benchmark. Above VWAP = favorable fill for buyers. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. VWAP (Volume Weighted Average Price) calculates the cumulative average price weighted by trading volume, typically reset at session boundaries. It represents the true average price at which a security has traded throughout the period, giving more weight to prices where higher volume occurred. This implementation supports flexible period-based resets rather than traditional session-based anchoring. @@ -183,4 +181,4 @@ VWAP implementations vary primarily in reset behavior. This implementation uses - Berkowitz, S., Logue, D., & Noser, E. (1988). "The Total Cost of Transactions on the NYSE." *Journal of Finance*. - Madhavan, A. (2002). "VWAP Strategies." *Trading*, Spring 2002. -- Kissell, R. (2006). "The Science of Algorithmic Trading and Portfolio Management." *Academic Press*. +- Kissell, R. (2006). "The Science of Algorithmic Trading and Portfolio Management." *Academic Press*. \ No newline at end of file diff --git a/lib/volume/vwma/Vwma.md b/lib/volume/vwma/Vwma.md index 02cd1d67..47a66767 100644 --- a/lib/volume/vwma/Vwma.md +++ b/lib/volume/vwma/Vwma.md @@ -13,9 +13,7 @@ | **PineScript** | [vwma.pine](vwma.pine) | - VWMA (Volume Weighted Moving Average) calculates a moving average where each price is weighted by its corresponding volume over a specified lookbac... -- Parameterized by `period` (default 20). -- Output range: Unbounded. -- Requires `> period` bars of warmup before first valid output (IsHot = true). +- **Similar:** [EVWMA](../evwma/Evwma.md), [SMA](../../trends_FIR/sma/Sma.md) | **Complementary:** OBV | **Trading note:** Volume-Weighted MA; weights price by volume. More responsive during high-volume bars. - Validated against TA-Lib, Skender, and Tulip reference implementations where available. VWMA (Volume Weighted Moving Average) calculates a moving average where each price is weighted by its corresponding volume over a specified lookback period. Unlike VWAP which accumulates from a reset point, VWMA uses a sliding window that continuously drops old values, making it a true moving average. Bars with higher volume contribute more to the average, surfacing price levels where institutional activity concentrated. @@ -181,4 +179,4 @@ For batch calculation from scratch, SIMD can parallelize: - Arms, R. (1989). "Volume Cycles in the Stock Market." Equis International. - Achelis, S. (2000). "Technical Analysis from A to Z." McGraw-Hill. -- TradingView. "Pine Script VWMA Reference." [tradingview.com](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.vwma) +- TradingView. "Pine Script VWMA Reference." [tradingview.com](https://www.tradingview.com/pine-script-reference/v5/#fun_ta.vwma) \ No newline at end of file diff --git a/lib/volume/wad/Wad.md b/lib/volume/wad/Wad.md index 45944e7f..4d31c171 100644 --- a/lib/volume/wad/Wad.md +++ b/lib/volume/wad/Wad.md @@ -14,8 +14,6 @@ - Williams Accumulation/Distribution (WAD) is Larry Williams' contribution to the volume analysis toolkit. - No configurable parameters; computation is stateless per bar. -- Output range: Unbounded. -- Requires 1 bar of warmup before first valid output (IsHot = true). - Validated against TA-Lib, Skender, and Tulip reference implementations where available. Williams Accumulation/Distribution (WAD) is Larry Williams' contribution to the volume analysis toolkit. Unlike the standard Accumulation/Distribution Line that uses the close's position within the day's range, WAD incorporates **True Range** concepts. This gives it a different perspective on buying and selling pressure. @@ -140,4 +138,4 @@ O(1) cumulative. No window, no smoothing. The conditional branch (up day vs down ## References - Williams, L. (1979). "How I Made One Million Dollars... Last Year... Trading Commodities." Windsor Books. -- https://school.stockcharts.com/doku.php?id=technical_indicators:williams_ad +- https://school.stockcharts.com/doku.php?id=technical_indicators:williams_ad \ No newline at end of file diff --git a/ndepend/NDBadge.deps.json b/ndepend/NDBadge.deps.json new file mode 100644 index 00000000..e2c78f8c --- /dev/null +++ b/ndepend/NDBadge.deps.json @@ -0,0 +1,154 @@ +{ + "runtimeTarget": { + "name": ".NETCoreApp,Version=v10.0", + "signature": "" + }, + "compilationOptions": {}, + "targets": { + ".NETCoreApp,Version=v10.0": { + "NDBadge/1.0.0": { + "dependencies": { + "SkiaSharp": "3.119.1", + "SkiaSharp.NativeAssets.Linux": "3.119.1" + }, + "runtime": { + "NDBadge.dll": {} + } + }, + "SkiaSharp/3.119.1": { + "dependencies": { + "SkiaSharp.NativeAssets.Win32": "3.119.1", + "SkiaSharp.NativeAssets.macOS": "3.119.1" + }, + "runtime": { + "lib/net8.0/SkiaSharp.dll": { + "assemblyVersion": "3.119.0.0", + "fileVersion": "3.119.1.0" + } + } + }, + "SkiaSharp.NativeAssets.Linux/3.119.1": { + "runtimeTargets": { + "runtimes/linux-arm/native/libSkiaSharp.so": { + "rid": "linux-arm", + "assetType": "native", + "fileVersion": "0.0.0.0" + }, + "runtimes/linux-arm64/native/libSkiaSharp.so": { + "rid": "linux-arm64", + "assetType": "native", + "fileVersion": "0.0.0.0" + }, + "runtimes/linux-loongarch64/native/libSkiaSharp.so": { + "rid": "linux-loongarch64", + "assetType": "native", + "fileVersion": "0.0.0.0" + }, + "runtimes/linux-musl-arm/native/libSkiaSharp.so": { + "rid": "linux-musl-arm", + "assetType": "native", + "fileVersion": "0.0.0.0" + }, + "runtimes/linux-musl-arm64/native/libSkiaSharp.so": { + "rid": "linux-musl-arm64", + "assetType": "native", + "fileVersion": "0.0.0.0" + }, + "runtimes/linux-musl-loongarch64/native/libSkiaSharp.so": { + "rid": "linux-musl-loongarch64", + "assetType": "native", + "fileVersion": "0.0.0.0" + }, + "runtimes/linux-musl-riscv64/native/libSkiaSharp.so": { + "rid": "linux-musl-riscv64", + "assetType": "native", + "fileVersion": "0.0.0.0" + }, + "runtimes/linux-musl-x64/native/libSkiaSharp.so": { + "rid": "linux-musl-x64", + "assetType": "native", + "fileVersion": "0.0.0.0" + }, + "runtimes/linux-riscv64/native/libSkiaSharp.so": { + "rid": "linux-riscv64", + "assetType": "native", + "fileVersion": "0.0.0.0" + }, + "runtimes/linux-x64/native/libSkiaSharp.so": { + "rid": "linux-x64", + "assetType": "native", + "fileVersion": "0.0.0.0" + }, + "runtimes/linux-x86/native/libSkiaSharp.so": { + "rid": "linux-x86", + "assetType": "native", + "fileVersion": "0.0.0.0" + } + } + }, + "SkiaSharp.NativeAssets.macOS/3.119.1": { + "runtimeTargets": { + "runtimes/osx/native/libSkiaSharp.dylib": { + "rid": "osx", + "assetType": "native", + "fileVersion": "0.0.0.0" + } + } + }, + "SkiaSharp.NativeAssets.Win32/3.119.1": { + "runtimeTargets": { + "runtimes/win-arm64/native/libSkiaSharp.dll": { + "rid": "win-arm64", + "assetType": "native", + "fileVersion": "0.0.0.0" + }, + "runtimes/win-x64/native/libSkiaSharp.dll": { + "rid": "win-x64", + "assetType": "native", + "fileVersion": "0.0.0.0" + }, + "runtimes/win-x86/native/libSkiaSharp.dll": { + "rid": "win-x86", + "assetType": "native", + "fileVersion": "0.0.0.0" + } + } + } + } + }, + "libraries": { + "NDBadge/1.0.0": { + "type": "project", + "serviceable": false, + "sha512": "" + }, + "SkiaSharp/3.119.1": { + "type": "package", + "serviceable": true, + "sha512": "sha512-+Ru1BTSZQne3Vp+vbSb50Ke3Nlc3ZnItxx4+751J9WZ8YzLKAV/n+9DAo4zFTyeCI//ueT63c+VybmTTpYBEiw==", + "path": "skiasharp/3.119.1", + "hashPath": "skiasharp.3.119.1.nupkg.sha512" + }, + "SkiaSharp.NativeAssets.Linux/3.119.1": { + "type": "package", + "serviceable": true, + "sha512": "sha512-9YNoc4SeKvQhrwiqwT4ezkNfMywPdPSK+UFvo/CaoXqLixcnYOTsQKm5BF9mc4+q3vKgDtEgMt0d1ygZhJTEHg==", + "path": "skiasharp.nativeassets.linux/3.119.1", + "hashPath": "skiasharp.nativeassets.linux.3.119.1.nupkg.sha512" + }, + "SkiaSharp.NativeAssets.macOS/3.119.1": { + "type": "package", + "serviceable": true, + "sha512": "sha512-6hR3BdLhApjDxR1bFrJ7/lMydPfI01s3K+3WjIXFUlfC0MFCFCwRzv+JtzIkW9bDXs7XUVQS+6EVf0uzCasnGQ==", + "path": "skiasharp.nativeassets.macos/3.119.1", + "hashPath": "skiasharp.nativeassets.macos.3.119.1.nupkg.sha512" + }, + "SkiaSharp.NativeAssets.Win32/3.119.1": { + "type": "package", + "serviceable": true, + "sha512": "sha512-8C4GSXVJqSr0y3Tyyv5jz6MJSTVUyYkMjeKrzK+VyZPGLo89MNoUEclVuYahzOCDdtbfXrd2HtxXfDuvoSXrUw==", + "path": "skiasharp.nativeassets.win32/3.119.1", + "hashPath": "skiasharp.nativeassets.win32.3.119.1.nupkg.sha512" + } + } +} \ No newline at end of file diff --git a/ndepend/NDBadge.dll b/ndepend/NDBadge.dll new file mode 100644 index 00000000..785038f1 Binary files /dev/null and b/ndepend/NDBadge.dll differ diff --git a/ndepend/NDBadge.exe b/ndepend/NDBadge.exe new file mode 100644 index 00000000..6cffcad8 Binary files /dev/null and b/ndepend/NDBadge.exe differ diff --git a/ndepend/NDBadge.runtimeconfig.json b/ndepend/NDBadge.runtimeconfig.json new file mode 100644 index 00000000..f730443c --- /dev/null +++ b/ndepend/NDBadge.runtimeconfig.json @@ -0,0 +1,13 @@ +{ + "runtimeOptions": { + "tfm": "net10.0", + "framework": { + "name": "Microsoft.NETCore.App", + "version": "10.0.0" + }, + "configProperties": { + "System.Reflection.Metadata.MetadataUpdater.IsSupported": false, + "System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": false + } + } +} \ No newline at end of file diff --git a/ndepend/SkiaSharp.dll b/ndepend/SkiaSharp.dll new file mode 100644 index 00000000..40b5f963 Binary files /dev/null and b/ndepend/SkiaSharp.dll differ diff --git a/ndepend/badges/classes.svg b/ndepend/badges/classes.svg new file mode 100644 index 00000000..79191afa --- /dev/null +++ b/ndepend/badges/classes.svg @@ -0,0 +1,22 @@ + + # Classes: 1154 + + + + + + + + + + + + + + + # Classes + + 1154 + + \ No newline at end of file diff --git a/ndepend/badges/comments.svg b/ndepend/badges/comments.svg new file mode 100644 index 00000000..bd288144 --- /dev/null +++ b/ndepend/badges/comments.svg @@ -0,0 +1,22 @@ + + Percentage of Comments: 33.31 + + + + + + + + + + + + + + + Percentage of Comments + + 33.31 + + \ No newline at end of file diff --git a/ndepend/badges/complexity.svg b/ndepend/badges/complexity.svg new file mode 100644 index 00000000..a6ffaf1b --- /dev/null +++ b/ndepend/badges/complexity.svg @@ -0,0 +1,22 @@ + + Average Cyclomatic Complexity for Methods: 2.15 + + + + + + + + + + + + + + + Average Cyclomatic Complexity for Methods + + 2.15 + + \ No newline at end of file diff --git a/ndepend/badges/files.svg b/ndepend/badges/files.svg new file mode 100644 index 00000000..fc4099f6 --- /dev/null +++ b/ndepend/badges/files.svg @@ -0,0 +1,22 @@ + + # Source Files: 1851 + + + + + + + + + + + + + + + # Source Files + + 1851 + + \ No newline at end of file diff --git a/ndepend/badges/loc.svg b/ndepend/badges/loc.svg new file mode 100644 index 00000000..072962d9 --- /dev/null +++ b/ndepend/badges/loc.svg @@ -0,0 +1,22 @@ + + # Lines of Code: 147536 + + + + + + + + + + + + + + + # Lines of Code + + 147536 + + \ No newline at end of file diff --git a/ndepend/badges/methods.svg b/ndepend/badges/methods.svg new file mode 100644 index 00000000..9a4430ec --- /dev/null +++ b/ndepend/badges/methods.svg @@ -0,0 +1,22 @@ + + # Methods: 15079 + + + + + + + + + + + + + + + # Methods + + 15079 + + \ No newline at end of file diff --git a/ndepend/badges/public-api.svg b/ndepend/badges/public-api.svg new file mode 100644 index 00000000..fe996dae --- /dev/null +++ b/ndepend/badges/public-api.svg @@ -0,0 +1,22 @@ + + # Public Types: 1193 + + + + + + + + + + + + + + + # Public Types + + 1193 + + \ No newline at end of file diff --git a/ndepend/coverage-exclusions.runsettings b/ndepend/coverage-exclusions.runsettings new file mode 100644 index 00000000..0e67e8e5 --- /dev/null +++ b/ndepend/coverage-exclusions.runsettings @@ -0,0 +1,20 @@ + + + + + + + + + + + + .*::System\.Collections\..*\.GetEnumerator\(\).* + + + + + + + + diff --git a/ndepend/generate-badges.ps1 b/ndepend/generate-badges.ps1 new file mode 100644 index 00000000..f26db07a --- /dev/null +++ b/ndepend/generate-badges.ps1 @@ -0,0 +1,122 @@ +#!/usr/bin/env pwsh +#requires -Version 7.0 + +<# +.SYNOPSIS + Generates NDepend metric badges for QuanTAlib +.DESCRIPTION + Creates SVG badges for key quality metrics that reinforce QuanTAlib's + identity: scale, quality, low complexity, and comprehensive documentation. +#> + +[CmdletBinding()] +param( + [Parameter(Mandatory = $false)] + [string]$NDBadgePath = "$PSScriptRoot\NDBadge.exe", + + [Parameter(Mandatory = $false)] + [string]$XmlPath = ".\ndepend\NDependOut\TrendMetrics\NDependTrendData2026.xml" +) + +$ErrorActionPreference = 'Stop' + +# Validate prerequisites +if (-not (Test-Path $NDBadgePath)) { + Write-Error "NDBadge.exe not found at: $NDBadgePath" + exit 1 +} + +if (-not (Test-Path $XmlPath)) { + Write-Error "NDepend trend data XML not found at: $XmlPath" + Write-Information "Please run ndepend.ps1 first to generate analysis data" + exit 1 +} + +$ScriptDir = $PSScriptRoot +$OutputDir = Join-Path $ScriptDir "badges" + +# Create output directory +if (-not (Test-Path $OutputDir)) { + New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null +} + +Write-Information "=== Generating QuanTAlib Quality Badges ===" +Write-Information "Output directory: $OutputDir`n" + +# Selected badges for QuanTAlib README +Write-Information "Generating QuanTAlib badges..." + +$HighValueBadges = @( + @{ + Metric = "# Lines of Code" + Output = "loc.svg" + Description = "Total lines of code" + }, + @{ + Metric = "# Source Files" + Output = "files.svg" + Description = "Source files" + }, + @{ + Metric = "# Classes" + Output = "classes.svg" + Description = "Classes" + }, + @{ + Metric = "# Methods" + Output = "methods.svg" + Description = "Methods" + }, + @{ + Metric = "# Public Types" + Output = "public-api.svg" + Description = "Public API surface" + }, + @{ + Metric = "Percentage of Comments" + Output = "comments.svg" + Description = "Comment percentage" + }, + @{ + Metric = "Average Cyclomatic Complexity for Methods" + Output = "complexity.svg" + Description = "Average complexity" + } +) + +foreach ($badge in $HighValueBadges) { + $outputPath = Join-Path $OutputDir $badge.Output + Write-Information " [$($badge.Output)] $($badge.Description)" + + & $NDBadgePath --xml $XmlPath --metric $badge.Metric --output $outputPath + + if ($LASTEXITCODE -ne 0) { + Write-Warning "Failed to generate badge: $($badge.Output)" + } +} + + +# Generate summary +Write-Information "`n=== Badge Generation Complete ===" +$generatedBadges = Get-ChildItem -Path $OutputDir -Filter "*.svg" +Write-Information "Generated $($generatedBadges.Count) badges in: $OutputDir" + +Write-Information "`nGenerated badges:" +$HighValueBadges | ForEach-Object { + Write-Information " - $($_.Output.PadRight(20)) : $($_.Description)" +} + +Write-Information "`nMarkdown snippet for README.md:" +Write-Information @" + +## Quality Metrics + +[![LoC](ndepend/badges/loc.svg)]() +[![Files](ndepend/badges/files.svg)]() +[![Classes](ndepend/badges/classes.svg)]() +[![Methods](ndepend/badges/methods.svg)]() +[![Public API](ndepend/badges/public-api.svg)]() +[![Comments](ndepend/badges/comments.svg)]() +[![Complexity](ndepend/badges/complexity.svg)]() + +"@ diff --git a/ndepend/libSkiaSharp.dll b/ndepend/libSkiaSharp.dll new file mode 100644 index 00000000..036745b3 Binary files /dev/null and b/ndepend/libSkiaSharp.dll differ diff --git a/ndepend/ndepend.ps1 b/ndepend/ndepend.ps1 new file mode 100644 index 00000000..8760ecbb --- /dev/null +++ b/ndepend/ndepend.ps1 @@ -0,0 +1,239 @@ +#!/usr/bin/env pwsh +#requires -Version 7.0 + +[CmdletBinding()] +param( + [Parameter(Mandatory = $false)] + [string]$NdependLicense = $env:NDEPEND_LICENSE +) + +$ErrorActionPreference = 'Stop' +$ProgressPreference = 'SilentlyContinue' + +# Configuration +# Determine NDepend installation path based on OS +if ($IsWindows -or $env:OS -like "Windows*") { + $NdependDll = "C:\ndepend\net10.0\NDepend.Console.MultiOS.dll" +} else { + $NdependDll = Join-Path $HOME "NDepend/net10.0/NDepend.Console.MultiOS.dll" +} +# Ensure ScriptDir is set correctly even if $PSScriptRoot is empty (e.g., dot-sourced) +$ScriptDir = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Path } +$ProjectRoot = Split-Path -Parent $ScriptDir +$CoverageDir = Join-Path $ScriptDir "coverage" +$SarifDir = Join-Path $ProjectRoot ".sarif" +$SolutionFile = Join-Path $ProjectRoot "QuanTAlib.slnx" +$TestProject = Join-Path $ProjectRoot "lib/QuanTAlib.Tests.csproj" +$TestProject2 = Join-Path $ProjectRoot "quantower/Quantower.Tests.csproj" +$RunSettingsFile = Join-Path $ProjectRoot ".config/coverage.runsettings" +$NdependProject = Join-Path $ScriptDir "quantalib.ndproj" + +# Validate prerequisites +if (-not (Test-Path $NdependDll)) { + Write-Error "NDepend console not found at: $NdependDll" + exit 1 +} + +if ([string]::IsNullOrWhiteSpace($NdependLicense)) { + Write-Warning "NDEPEND_LICENSE environment variable not set. License activation may fail." +} + +if (-not (Test-Path $SolutionFile)) { + Write-Error "Solution file not found: $SolutionFile" + exit 1 +} + +# Helper function for section headers +function Write-Section { + param([string]$Message) + Write-Information "`n=== $Message ===" +} + +# Track analysis failure +$AnalysisFailed = $false + +try { + # Create .sarif directory + Write-Section "Creating .sarif directory for Roslyn analyzer output" + if (-not (Test-Path $SarifDir)) { + New-Item -ItemType Directory -Path $SarifDir -Force | Out-Null + } + Write-Information "SARIF directory: $SarifDir" + + # Restore, clean, and build + Write-Section "Cleaning and building solution (generates SARIF files)" + + Write-Information "Restoring packages..." + dotnet restore $SolutionFile -v q + if ($LASTEXITCODE -ne 0) { throw "Restore failed with exit code $LASTEXITCODE" } + + Write-Information "Cleaning solution..." + dotnet clean $SolutionFile -v q + if ($LASTEXITCODE -ne 0) { throw "Clean failed with exit code $LASTEXITCODE" } + + Write-Information "Removing old coverage data..." + if (Test-Path $CoverageDir) { + Remove-Item -Path $CoverageDir -Recurse -Force + } + + Write-Information "Building solution..." + dotnet build $SolutionFile -c Debug --no-incremental + if ($LASTEXITCODE -ne 0) { throw "Build failed with exit code $LASTEXITCODE" } + + # Run tests with coverage (QuanTAlib.Tests) + Write-Section "Running tests with coverage (QuanTAlib.Tests)" + dotnet test $TestProject ` + -c Debug ` + --no-build ` + --collect:"XPlat Code Coverage" ` + --settings $RunSettingsFile ` + --results-directory:$CoverageDir + + if ($LASTEXITCODE -ne 0) { throw "Tests failed for QuanTAlib.Tests with exit code $LASTEXITCODE" } + + # Run tests with coverage (Quantower.Tests) + Write-Section "Running tests with coverage (Quantower.Tests)" + dotnet test $TestProject2 ` + -c Debug ` + --no-build ` + --collect:"XPlat Code Coverage" ` + --settings $RunSettingsFile ` + --results-directory:$CoverageDir + + if ($LASTEXITCODE -ne 0) { throw "Tests failed for Quantower.Tests with exit code $LASTEXITCODE" } + + # Find coverage files + Write-Information "`nSearching for coverage files..." + $CoverageFiles = Get-ChildItem -Path $CoverageDir -Filter "coverage.opencover.xml" -Recurse -File | + Select-Object -ExpandProperty FullName + + if (-not $CoverageFiles) { + Write-Warning "No coverage files found in $CoverageDir" + } + else { + $CoverageFiles | ForEach-Object { + Write-Information "Coverage file: $_" + } + } + + # Run JetBrains InspectCode + Write-Section "Running JetBrains InspectCode" + $InspectCodeOutput = Join-Path $SarifDir "resharper.sarif.json" + $jbPath = Get-Command "jb" -ErrorAction SilentlyContinue + if ($jbPath) { + Write-Information "Running InspectCode analysis..." + jb inspectcode $SolutionFile --output=$InspectCodeOutput --format=Sarif --no-build + if ($LASTEXITCODE -ne 0) { + Write-Warning "InspectCode completed with exit code $LASTEXITCODE" + } + else { + Write-Information "InspectCode SARIF saved to: $InspectCodeOutput" + } + } + else { + Write-Warning "JetBrains CLI (jb) not found. Skipping InspectCode analysis." + Write-Information " Install with: dotnet tool install -g JetBrains.ReSharper.GlobalTools" + } + + # List SARIF files + Write-Section "SARIF files generated" + $SarifFiles = Get-ChildItem -Path $SarifDir -Filter "*.json" -ErrorAction SilentlyContinue + if ($SarifFiles) { + $SarifFiles | ForEach-Object { + Write-Information " $($_.Name) ($([math]::Round($_.Length / 1KB, 2)) KB)" + } + } + else { + Write-Information "No SARIF files found" + } + + # Activate NDepend license + Write-Section "Activating NDepend license" + if (-not [string]::IsNullOrWhiteSpace($NdependLicense)) { + dotnet $NdependDll --RegLic $NdependLicense + if ($LASTEXITCODE -ne 0) { Write-Warning "License activation returned exit code $LASTEXITCODE" } + } + else { + Write-Warning "Skipping license activation (no license provided)" + } + + # Run NDepend analysis + Write-Section "Running NDepend analysis" + $NdependArgs = @($NdependProject) + if ($CoverageFiles) { + $NdependArgs += "/CoverageFiles" + foreach ($file in $CoverageFiles) { + $NdependArgs += $file + } + } + + dotnet $NdependDll @NdependArgs + if ($LASTEXITCODE -ne 0) { + Write-Warning "NDepend analysis completed with exit code $LASTEXITCODE" + $AnalysisFailed = $true + } + +} +catch { + Write-Error "Script failed: $_" + $AnalysisFailed = $true +} +finally { + # Always deactivate license + Write-Section "Deactivating NDepend license" + if (-not [string]::IsNullOrWhiteSpace($NdependLicense)) { + dotnet $NdependDll --UnregLic + if ($LASTEXITCODE -ne 0) { Write-Warning "License deactivation returned exit code $LASTEXITCODE" } + } + else { + Write-Information "Skipping license deactivation (no license provided)" + } + + # Generate badges from NDepend trend data + Write-Section "Generating quality badges" + $NDBadgePath = Join-Path $ScriptDir "NDBadge.exe" + # Find the most recent trend data file + $TrendMetricsDir = Join-Path $ScriptDir "NDependOut\TrendMetrics" + $TrendXml = if (Test-Path $TrendMetricsDir) { + Get-ChildItem -Path $TrendMetricsDir -Filter "NDependTrendData*.xml" -File | + Sort-Object Name -Descending | + Select-Object -First 1 -ExpandProperty FullName + } + else { $null } + $BadgeDir = Join-Path $ScriptDir "badges" + + if ((Test-Path $NDBadgePath) -and $TrendXml -and (Test-Path $TrendXml)) { + if (-not (Test-Path $BadgeDir)) { + New-Item -ItemType Directory -Path $BadgeDir -Force | Out-Null + } + + $Badges = @( + @{ Metric = "# Lines of Code"; Output = "loc.svg" }, + @{ Metric = "# Source Files"; Output = "files.svg" }, + @{ Metric = "# Classes"; Output = "classes.svg" }, + @{ Metric = "# Methods"; Output = "methods.svg" }, + @{ Metric = "# Public Types"; Output = "public-api.svg" }, + @{ Metric = "Percentage of Comments"; Output = "comments.svg" }, + @{ Metric = "Average Cyclomatic Complexity for Methods"; Output = "complexity.svg" } + ) + + foreach ($badge in $Badges) { + $outputPath = Join-Path $BadgeDir $badge.Output + & $NDBadgePath --xml $TrendXml --metric $badge.Metric --output $outputPath 2>$null + if ($LASTEXITCODE -eq 0) { + Write-Information " Generated: $($badge.Output)" + } + } + Write-Information "Badges saved to: $BadgeDir" + } + else { + Write-Information "Skipping badge generation (NDBadge.exe or trend data not found)" + } + + Write-Section "Done" + + if ($AnalysisFailed) { + Write-Information "Note: Analysis completed with quality gate failures" + exit 1 + } +} \ No newline at end of file diff --git a/ndepend/quantalib.ndproj b/ndepend/quantalib.ndproj new file mode 100644 index 00000000..9488ae44 --- /dev/null +++ b/ndepend/quantalib.ndproj @@ -0,0 +1,565 @@ + + + .\NDependOut + + + + . + + + + .NET 10.0 + + + True + True + True + False + + + + + .\coverage\43fa2c87-f47e-4cfd-bc4d-2b640a2a37d6\coverage.opencover.xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 1 + 0 + 0 + $ManDay$ + 50 + USD + After + 18 + 240 + 8 + 5 + 10 + 20 + 50 + 1200000000 + 12000000000 + 72000000000 + 360000000000 + + + + + ND1000: Avoid types too big +warnif count > 0 +from t in JustMyCode.Types +where t.NbLinesOfCode > 500 && + !t.IsGeneratedByCompiler +let loc = t.NbLinesOfCode +orderby loc descending +select new { + t, + loc, + t.Methods, + t.Fields +} +// This rule identifies types that are too large and should be split into smaller, more focused types. +// Threshold increased from default 200 to 500 to accommodate complex financial algorithm classes. +// 10 min per issue +]]> + + ND1004: Avoid methods with too many parameters +warnif count > 0 +from m in JustMyCode.Methods +where m.NbParameters > 8 && + !m.IsGeneratedByCompiler +let np = m.NbParameters +orderby np descending +select new { + m, + np, + m.NbLinesOfCode +} +// This rule identifies methods with too many parameters. +// Threshold increased from default 5 to 8 to accommodate OHLCV bar data (6 values + time + flags). +// 5 min per issue +]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file