Trend and regime
All functions · nseries package
Sections: Directional Movement · Average Directional Index · Aroon · Vortex Indicator · Random Walk Index · Choppiness Index · Efficiency Ratio · Congestion Index · Follow-Through Index · Regime Detection · Markov Models · Hurst Exponent · Structural Breaks
Directional Movement
DMIMinus
func (s Series) DMIMinus(h, l, c Series, n int) Series
DMIMinus computes the negative Directional Movement Indicator over n bars. It measures the strength of downward price movement, consistent with the TradeStation DirMovement implementation.
If a high, low or close is NaN or infinite, the result is NaN from that bar onwards, except on the first bar, whose result is always 0; earlier bars are unaffected. A close counts on its own bar, although the calculation first reads it on the next one, and any later bad bars change nothing. This is the library’s policy for recursive methods: a non-finite value poisons the running averages permanently, so the result does not recover. It is NaN rather than 0 because 0 would read as “no downward movement” and pass for a real reading instead of showing up as missing data. Ordered comparisons such as > and < are false for NaN, and != is true, so test the result with math.IsNaN before comparing it with a threshold. The rule is keyed on the input values, not on the arithmetic: finite inputs whose arithmetic overflows, such as magnitudes near 1e308, are outside it and keep whatever result that arithmetic gives, which can include infinities or NaN.
The result is a new series of the same length as the inputs. If n is less than 1, or the series are empty or differ in length, it is an empty, non-nil series and the values are not inspected. Any n of 1 or more is accepted, even one longer than the series. The receiver is not used and may be nil.
The Wilder averages start from zero, so the first values after bar 0 are partial; the numerator and the denominator share the same weights, so the ratio is largely unaffected.
DMIPlus
func (s Series) DMIPlus(h, l, c Series, n int) Series
DMIPlus computes the positive Directional Movement Indicator over n bars. It measures the strength of upward price movement, consistent with the TradeStation DirMovement implementation.
If a high, low or close is NaN or infinite, the result is NaN from that bar onwards, except on the first bar, whose result is always 0; earlier bars are unaffected. A close counts on its own bar, although the calculation first reads it on the next one, and any later bad bars change nothing. This is the library’s policy for recursive methods: a non-finite value poisons the running averages permanently, so the result does not recover. It is NaN rather than 0 because 0 would read as “no upward movement” and pass for a real reading instead of showing up as missing data. Ordered comparisons such as > and < are false for NaN, and != is true, so test the result with math.IsNaN before comparing it with a threshold. The rule is keyed on the input values, not on the arithmetic: finite inputs whose arithmetic overflows, such as magnitudes near 1e308, are outside it and keep whatever result that arithmetic gives, which can include infinities or NaN.
The result is a new series of the same length as the inputs. If n is less than 1, or the series are empty or differ in length, it is an empty, non-nil series and the values are not inspected. Any n of 1 or more is accepted, even one longer than the series. The receiver is not used and may be nil.
The Wilder averages start from zero, so the first values after bar 0 are partial; the numerator and the denominator share the same weights, so the ratio is largely unaffected.
Average Directional Index
ADX
func (s Series) ADX(h, l, c Series, n int) Series
ADX calculates the Average Directional Index (ADX) based on the given high, low, and close price series and a period n. Returns a series representing the ADX values for the input data.
If a high, low or close is NaN or infinite, the result is NaN from that bar onwards, except on the first bar, whose result is always 0; earlier bars are unaffected. A close counts on its own bar, although the calculation first reads it on the next one, and any later bad bars change nothing. This is the library’s policy for recursive methods: ADX is built on DMIPlus and DMIMinus, and both its initial running sum over the first n bars and its later smoothing depend on every earlier bar, so the result does not recover. It is NaN rather than 0 because a near-zero ADX reads as “no trend” and, in a regime filter for example, would pass for a real reading instead of showing up as missing data. Ordered comparisons such as > and < are false for NaN, and != is true, so test the result with math.IsNaN before comparing it with a threshold. The rule is keyed on the input values, not on the arithmetic: finite inputs whose arithmetic overflows, such as magnitudes near 1e308, are outside it and keep whatever result that arithmetic gives, which can include infinities or NaN.
The result is a new series of the same length as the inputs. If n is less than 1, or the series are empty or differ in length, it is an empty, non-nil series and the values are not inspected. Any n of 1 or more is accepted, even one longer than the series. The receiver is not used and may be nil.
The warm-up reads 0, not NaN: bars 0 to n-1 are 0 and the first valid index is n, the mean of the directional index over bars 1 to n; Wilder’s smoothing follows. Releases before this change gave the running sum divided by n on bars 1 to n-1, so a directional index of 100 read 20, 40, 60 and 80 at n = 5, a rising ramp that an ADX-rising rule reads as a strengthening trend. A NaN or infinite input inside the warm-up still gives NaN from its own bar.
The directional index that ADX averages is pdi.Sub(mdi).Abs().Mul(100).Div(pdi.Add(mdi)) with pdi = c.DMIPlus(h, l, c, n) and mdi = c.DMIMinus(h, l, c, n), bit for bit, 0 on bar 0 and where the sum is 0. Wilder’s ADXR on this ADX is a.Add(a.Shift(n-1)).Div(2) with a = c.ADX(h, l, c, n), valid from bar 2n-1. Both, and Wilder’s own sum-seeded DX, ADX and ADXR, are among the compositions under “Average Directional Index” in the manual.
ADXTrendMode
func (s Series) ADXTrendMode(h, l, c Series, n int, on, off, exhaust, early float64) Series
ADXTrendMode is Ruggiero’s ADX trend mode: for each bar it returns +1 while the market is trending, -1 while it is consolidating and 0 while the mode is undetermined. The rules are those of Table 4.9, “Rules for trend mode”, in the “Market Modes” section of chapter 4, “Trading Using Technical Analysis”, of Murray A. Ruggiero Jr., Cybernetic Trading Strategies (Wiley, 1997). n is the ADX length (Ruggiero uses 14). The receiver is not used (as in ADX).
With a the ADX series of the package (a[t] is its value on bar t), the five rules are:
- If ADX crosses above on, the market is trending: a[t-1] <= on and a[t] > on.
- If ADX crosses below off, it is consolidating: a[t-1] >= off and a[t] < off.
- If ADX crosses below exhaust from above, it is consolidating: a[t-1] >= exhaust and a[t] < exhaust.
- If ADX rises from below early on 3 out of 4 days, the market will start to trend (an early trend): a[t-4] < early and at least 3 of the 4 steps a[t-k] > a[t-k-1], k = 0 to 3, hold (4 of 4 qualifies). Rises are strict: an equal step is not a rise, and a[t-4] equal to early is not below.
- If a trend is based on rule 4, it remains in effect until the 5-day difference in ADX is less than 0: a[t] < a[t-5], a comparison and not a subtraction. A trend confirmed by a rule-1 cross is read here as no longer based on rule 4, so only rules 2 and 3 end it; Table 4.9 does not settle this.
Ruggiero prints no code for rules 4 and 5, so the forms above, and the crosses’ ties (a prior bar equal to a level counts, where EasyLanguage’s “cross over” wording is strict), are this package’s reading.
Precedence: an exit wins on the same bar in every state (rules 2 and 3 beat rule 4, and rule 5 beats rule 4 on the entry bar), so an early trend starts only on a bar with a[t] >= a[t-5], or before bar n+5. Rules 2 and 3 end an early trend too. A rule-1 cross clears the early flag, so rule 5 cannot end that trend on a later bar; on the cross’s own bar an exit still wins, rule 5 included. A bar with both a rule-1 cross and rule 4 starts a trend that is not early. Rules 1 and 2 cannot fire on one bar when off <= on, and rules 1 and 3 cannot when on <= exhaust; rules 2 and 3 can, and both mean consolidation.
The levels are parameters: Table 4.9 gives Ruggiero’s four (on 25, off 20, exhaust 45, early 10) and its text his ADX length, for a run of his rules as printed (his platform’s ADX is another matter, see below). The levels on and off must be finite with off <= on, exhaust must be finite or +Inf with exhaust >= on, and early must be finite or -Inf with early <= on. Anything else (NaN included) returns len(h) zeros without inspecting the values. exhaust = +Inf disables rule 3 and early = -Inf disables rule 4. If n < 1, h is empty or h, l and c differ in length, the result is the empty Series{}.
ADX here is the package’s ADX: zero-seeded Wilder averages, the first ADX on bar n, no rounding. Wilder’s and TA-Lib’s sum seeds give their first ADX on bar 2n-1 instead, so over a short history a crossing can move by several bars or appear in one series and not the other; the two agree once the seeds have decayed. Wilder’s original rounds ADX to whole numbers, which moves crossings of the integer levels; what TradeStation 4.0, Ruggiero’s platform, did is not known.
The warm-up reads 0, not NaN: bars 0 to n are 0 and the first valid index is n+1. ADX’s own warm-up (bars 0 to n-1 are 0) would otherwise fake a rule-1 cross on bar n and a rule-4 rise. From bar n+1 the result stays 0, the undetermined state, until the first event. A bad input inside the warm-up still gives NaN from max(p, 1): NaN wins over the warm-up zeros.
With early = -Inf, before the first NaN, rules 1 to 3 alone give the same series as
up := a.CrossesAboveS(on).SetN(n+1, 0)
dn := a.CrossesBelowS(off).Add(a.CrossesBelowS(exhaust)).GT(0).SetN(n+1, 0)
up.Sub(dn).Hysteresis(0, 0)
(a.CrossesBelowS(+Inf) is all zeros for a finite a). Rule 4 then adds trend bars and, through rule 5, consolidation bars where rules 1 to 3 are undetermined, and keeps every trend bar of rules 1 to 3 up to the first bar where a rule-1 cross meets the rule-5 exit of an early trend: the exit wins there. That needs ADX to rise from below early to above on within three bars and then fall back to on or below before the cross, so only a small n reaches it.
The trade gate is the caller’s GT(0), which keeps the trending bars; LT(0) gives the consolidating bars, and 0 is neither. The companion filter is BreakoutModeIndex, whose gate is GTE(2).
NaN: if a has a NaN, the result is NaN from its first NaN bar to the end, and the bars before it are those of the finite prefix. ADX is NaN from max(p, 1) to the end, where p is the first bar with a NaN or infinite high, low or close, so the result is NaN exactly where ADX is, and bar 0 is 0 even when its input is bad (unlike BreakoutModeIndex, which is NaN from p).
The result is path-dependent and not start-invariant: ADX is recursive from bar 0 and the latch carries its state from bar n+1, so a different start can change the mode on a bar. It is prefix-invariant: the result on a prefix of the inputs is the prefix of the result. It takes O(len(h)) time for any n, math.MaxInt included.
Ruggiero’s levels were fitted on Treasury bond futures, in-sample, so they are a starting point and not evidence that they hold out of sample or on another market.
Compositions
The recipes below read the package’s DMIPlus, DMIMinus and ADX, which start Wilder’s averages from zero (TradeStation’s DirMovement) and give the first ADX on bar n, the mean of the directional index over bars 1 to n; Wilder’s worksheet and TA-Lib sum the first 13 bars and give theirs on bar 2n - 1. Over about the first 5n bars the package’s directional index differs from theirs by more than a point, and its ADX for about 6n (within 0.01 only after about 9n bars for the index and 10n to 11n for the ADX), so a level read in that burn-in compares seed transients; the last section gives Wilder’s own seed. Values are NaN before their first valid index and flags read 0 there; prices are positive and finite, lengths are in bars, and series are paired by position, so the caller aligns highs, lows and closes by timestamp first.
DX filter for breakouts (White)
Adam White (“Filtering Breakouts”, Stocks & Commodities V11:4, April 1993, pp. 149-155) enters long “when the market made an x-bar high and a y-bar ADX made a z-bar high”, repeats the test “using Dx in place of ADx”, exits when the trend “makes a seven-bar low” and settles on the universal DX setting “3,17,7”. The directional index is the one ADX averages, 100 times the absolute difference of the two directional indicators over their sum; t6DXFilter composes it from DMIPlus and DMIMinus in ADX’s order, reads each “x-bar high” and “low” as today included, and books White’s long-only trades with Position.
pdi := c.DMIPlus(h, l, c, n)
mdi := c.DMIMinus(h, l, c, n)
dx := pdi.Sub(mdi).Abs().Mul(100).Div(pdi.Add(mdi))
up := h.GTE(h.Highest(x)).SetN(x-1, 0)
dxUp := dx.GTE(dx.Highest(z)).SetN(z, 0)
entry := up.Mul(dxUp)
exit := l.LTE(l.Lowest(e)).SetN(e-1, 0)
pos := c.Position(entry, exit)
dxV := dx.SetN(1, math.NaN())- Inputs: highs, lows and closes; x, n, z and e (3, 17, 7 and 7; his ADX universal is 5, 17 and 6).
- First valid index: 1 for
dxV(bar 0 is NaN; 0 where the two indicators sum to 0, NaN from a missing bar on);entryreads 0 before max(x - 1, z) andexitbefore e - 1. The masks matter: on the first barsh.GTE(h.Highest(x))reads the expanding high, and the first directional movement makes a z-bar high of the index. - Anchors:
dxVequals a loop of ADX’s own index expression bit for bit, and a loop of ADX’s expressions over it rebuildsADXbit for bit (dxV.Window(-1).RMA(n)to about 1e-13);h.GTE(h.Highest(x))equalsh.GTE(h.Highest(x-1).Shift(1))from bar x - 1; on a bar where entry and exit both fire, an outside bar,Positionenters a flat book and exits a long one. - Traps: on a bar without directional movement (an inside bar, or equal up and down moves) the three averages decay alike, so the index is unchanged in exact arithmetic and its new value differs from the last by a few units of rounding; when the previous bar was the z-bar high the entry then rests on that rounding, which differs between arm64, where Go fuses the recursions of the DMIs, and amd64 (the index’s bits differ on most bars; whether an entry moves depends on the path). The same holds inside the burn-in while one indicator is exactly 0: the index sits at 100 to within a unit of rounding, so a z-bar high there is decided by rounding too. TA-Lib’s order,
Div(...).Mul(100), differs in the last bits. Over the burn-in the package’s index is not Wilder’s: on his own wheat it is 100 on the first eight bars, where only -DM had occurred. After a missing high, low or close the index is NaN for good, soentryreads 0 from that bar on and the book does not re-enter, and a missing low also silencesexitfor e bars. - Variant: the strict reading,
h.Breakout(x, 1).GT(0)andl.Breakout(e, 1).LT(0), a window one bar longer (different on 6% to 14% of random-walk bars), and his ADX form,a.GTE(a.Highest(z)).SetN(n+z-1, 0)witha := c.ADX(h, l, c, n). - Missing piece: a named
DX(TA-Lib’s TA_DX, Tulip’s dx); the four-call composition is bit for bit ADX’s internal index. - Evidence: his Figures 4 and 11 (six futures markets, 1,000 bars each from late 1987 to 1991, long only, no costs): the universal DX filter raised the share of dollars made by winning trades from 51.8% for the 3-bar breakout alone to 59.9%, with no trade counts printed; on a random walk the filter removes about two-thirds of the entries with little selectivity. Evidence, not a reference.
- Pinned by
TestRecipeT6DXFilter.
ADXR and Wilder’s 25/20 gate (Wilder; Drinka and Kille)
Thomas Drinka and Steven Kille (“A modification of Wilder’s directional movement system”, Stocks & Commodities V3:6, 1985, pp. 218-221) restate Wilder’s “ADXR = (ADXt +ADXt-13)/2” and his rule that the system “will be profitable on commodities that have an ADXR value above 25” and is not to be used “when ADXR drops below 20”. t6ADXR lags n - 1, as they, TA-Lib, Tulip and TradeStation’s DirMovement do, and reads the two levels as a latch on the package’s ADX. The signals such a gate admits, the DI crosses that Summers gates with the ADX itself at 20 rather than the ADXR, Wilder’s Extreme Point stop and reverse and Pruitt’s ADX-above-35 reading of the system, are on t6-dmi-systems.md in this category.
a := c.ADX(h, l, c, n)
adxr := a.Add(a.Shift(n-1)).Div(2).SetN(n+n-1, math.NaN())
state := adxr.Hysteresis(on, off)- Inputs: highs, lows and closes, n (14),
on>=off(25 and 20). - First valid index: 2n - 1 for
adxr(27 at n = 14), NaN before: unmasked, bars n to 2n - 2 read half the ADX (theShiftpad) and bars 0 to n - 1 read 0, which latches -1 from bar 0.stateis 1 (trade) or -1 (stand aside) from the first ADXR outside [off, on], and 0 before; the gatestate.GT(0)treats 0 and -1 alike. Wilder’s own seed gives his day 41, bar 3n - 2 (the last section). - Anchors:
Div(2)equalsMul(0.5)bit for bit;stateequals a loop of the rule, and an ADXR equal toonoroffholds the state;c.ADXTrendMode(h, l, c, n, 25, 20, math.Inf(1), math.Inf(-1))equalsa.SetN(n, math.NaN()).Hysteresis(25, 20)from the bar both have decided on (Ruggiero’s latch waits for a cross, this one decides on a level). - Traps: on Wilder’s own 42 bars the package’s ADXR is 51.16 on bar 27 and 33.89 and 34.26 on bars 40 and 41, and opens the gate from bar 27, where Wilder’s is 22 and 23, undetermined; Drinka and Kille’s printed formulas omit the absolute value, the factor 100 and Wilder’s smoothing; Balsara’s book lags n (“the ADX value 14 days ago”); Wilder’s two quoted sentences say nothing about the band between the levels, so the latch is a reading.
- Variant: the level alone,
adxr.GT(25.0), and Balsara’s lag,a.Add(a.Shift(n)).Div(2).SetN(n+n, math.NaN()). - Missing piece: a named
ADXR(TA-Lib’s TA_ADXR, Tulip’s adxr); the composition is two calls and a mask. - Evidence: Drinka and Kille’s Tables 1 to 3 (six S&P 500 contracts of 1983 and 1984, 65 dollars a trade) test an ADX level, not the ADXR: at n = 14 the average net result per contract rose from a loss of 5,709 dollars with a gate at 5 to a gain of 3,602 at 30. Evidence, not a reference.
- Pinned by
TestRecipeT6ADXR; runnable exampleExampleSeries_ADX_adxr.
ADX environments and the rising-ADX gate (Kramer; Le Beau and Lucas)
Bruce Kramer (“Using Indicators In Trading Ranges And Trends”, Stocks & Commodities V12:4, April 1994, pp. 153-157) finds that “an increasing ADX signals a trending market” and names four environments: “A flat market is characterized by ADX values declining to less than 10 to 15, while a trading range market has ADX values of 16 to 25, a trend will have ADX values of 26 to 40, and a hypertrend will be characterized by sharply increasing ADX values to greater than 41.” Charles Le Beau and David Lucas (Day Trading Systems & Methods) trade only “in the direction of the trend” when “the daily ADX is rising” and “in either direction” when it is declining. t6ADXEnvironments reads Kramer’s bands as integer ranges (15, 25 and 40 in the lower band, as his flat market of Figure 7 has an ADX “less than or equal to 15”), a hypertrend as above 40 and rising on the bar, and the trend’s direction as the larger directional indicator.
a := c.ADX(h, l, c, n)
d := a.Delta()
rise := d.GT(0.0)
env := a.GT(15.0).Add(a.GT(25.0)).Add(a.GT(40.0).Mul(rise)).MaskNonFinite(a).SetN(n+1, math.NaN())
trending := rise.MaskNonFinite(a).SetN(n+1, math.NaN())
pdi := c.DMIPlus(h, l, c, n)
mdi := c.DMIMinus(h, l, c, n)
longOK := d.LTE(0.0).Add(d.GT(0.0).Mul(pdi.GT(mdi))).SetN(n+1, 0)
shortOK := d.LTE(0.0).Add(d.GT(0.0).Mul(mdi.GT(pdi))).SetN(n+1, 0)- Inputs: highs, lows and closes, n (Kramer gives none, 14 assumed; Le Beau and Lucas 18 on daily bars).
- First valid index: n + 1 for
envandtrending(the one-bar change reads ADX’s warm-up 0 at bar n), NaN before and wherever the ADX is NaN;longOKandshortOKread 0 on bars 0 to n and wherever the ADX is missing. - Anchors:
envequals a loop of the bands;env.EQ(0)isa.LTE(15)on valid bars;MaskNonFinite(a)equals the dossier’sAdd(a.Sub(a))bit for bit; exact ties fall where they are written (an ADX of exactly 15 is flat, 25 a range and 40, rising, a trend), and an ADX unchanged on a bar is not rising, so both sides are allowed. - Traps: the dossier’s Le Beau form,
rising.Mul(pdi.GT(mdi)).Add(rising.Mul(-1).Add(1)).GT(0), reads 1, allowed, on the bars after a missing bar, wherelongOKreads 0; withoutMaskNonFinitea missing ADX reads 0, flat. Kramer’s bands leave gaps (9% of the bars of an ADX(14) random walk fall in them), and his two paragraphs disagree when the ADX is above 25 and falling, soenvandtrendingare given apart. The levels depend on n and on the bar size: ADX(4) below 30 on weekly bars, ADX(6) below 40 daily, ADX(10) below 25 on 30-minute bars. - Variant: single levels, each masked with
SetN(n, 0): Pezzutti’sc.ADX(h, l, c, 14).GT(18.0); D’Errico and Zaffino’s codea.LT(30.0)on a weekly ADX(4), and their prose’s “below 30 for the last four weeks”,a.SetN(4, math.NaN()).LT(30.0).Sum(4).EQ(4.0).SetN(7, 0); Unger’sa.LT(25.0)on a 30-minute ADX(10) anda.LT(40.0)on a daily ADX(6). - Variant: Kramer’s literal hypertrend,
a.GT(41.0), and the levels alone,a.GT(15.0).Add(a.GT(25.0)).Add(a.GT(40.0)).MaskNonFinite(a).SetN(n, math.NaN()). - Missing piece: holding a daily value on intraday bars (Unger’s daily gate, Le Beau and Lucas’s daily ADX): with no timestamps, the caller computes the flag on daily bars and applies the last completed session’s value to the next session’s bars.
- Evidence: Pezzutti’s ADX(14) above 18 cut 250 S&P 500 trades to 185 and raised the profit factor from 3.53 to 4.14; Unger’s ADX(10) below 25 raised gold’s net from 201,100 to 255,020 dollars over 2010 to 2023 and lowered it from 177,800 to 139,250 over 2024 to 2026; Summers’s Lotus labels (“Completing the DMI rules”, Stocks & Commodities V7:1, January 1989, pp. 30-34) use inclusive bounds at 20, 25 and 30 and reproduce all 99 printed rows of his Figure 1, four ties included. All in sample. Evidence, not a reference.
- Pinned by
TestRecipeT6ADXEnvironments; runnable exampleExampleSeries_ADX_kramerEnvironments.
Wilder’s own seed: DX, ADX and ADXR as in his worksheet (Wilder; Summers)
Jim Summers (“Finishing DMI calculations, Part 9”, Stocks & Commodities V6:9, September 1988, pp. 350-353) prints Wilder’s March 1978 wheat worksheet “with Wilder’s answers as my program computed them”, noting that Wilder “starts counting at the first row of price data, not at the first row of TR1 data. Thus, the first calculation of TR14 contains only 13 day’s worth of data”, then “Today’s TR14 = Previous TR14 - (Previous TR14/14) + TR1”, DX as “(DI DIFF/DI SUM)” times 100, and “The first ADX = 14-day sum of DX/14”. TA-Lib seeds the same way. t6WilderDMI writes the seed with RMA on a true range whose bar 0 is set to 0, so every smoothed sum is Wilder’s divided by n.
up := h.Delta()
dn := l.Delta().Mul(-1)
pdm := up.Max(0).Mul(up.GT(dn))
mdm := dn.Max(0).Mul(dn.GT(up))
atr := c.TrueRange(h, l, c).SetN(1, 0).RMA(n)
pdiW := pdm.RMA(n).Mul(100).Div(atr).SetN(n, math.NaN())
mdiW := mdm.RMA(n).Mul(100).Div(atr).SetN(n, math.NaN())
dxW := pdiW.Sub(mdiW).Abs().Mul(100).Div(pdiW.Add(mdiW))
adxW := h.Mul(0).Add(dxW.Window(-n).RMA(n)).SetN(n+n-1, math.NaN())
adxrW := adxW.Add(adxW.Shift(n - 1)).Div(2)- Inputs: highs, lows and closes, n >= 2 (14).
- First valid index: n for
pdiW,mdiWanddxW(TA-Lib’s first DX), 2n - 1 foradxWand 3n - 2 foradxrW(his day 41 at n = 14), NaN before; a bar with a missing high, low and close makes every output NaN from that bar on. - Anchors: on Summers’s Figure 2 (1 June to 29 July 1977, 42 bars) the smoothed sums times n match all 84 printed TR14, +DM14 and -DM14 values at 2 decimals, and the outputs all 99 printed +DI, -DI, DX and ADX integers after rounding; the first ADX is 15.514692926698602 and the last 28.942424641228108, bit for bit on every architecture (
RMAis fenced); the ADXR of days 41 and 42 is 21.52 and 22.86 (derived, since Summers prints no ADXR), which Wilder’s 25/20 gate leaves undetermined. - Traps: the figure’s slashed zero prints the TR14 of 11 July as “57.85”: the value is 57.05 (53.63 - 53.63/14 + 7.25), from which the next row’s 57.48 follows; a sum of the two indicators of exactly 0 gives a DX of 0 here (
Div’s zero rule), where TA-Lib treats a sum within 1e-14 of 0 as zero and repeats the previous bar’s DX; the package’s zero-seeded ADX reads 68.39, 33.94 and 34.79 on bars 14, 27 and 41 of the same data, so on a short history the two seeds give opposite gates. - Variant: Hartle’s sidebar sheet (“The ADX”, Stocks & Commodities V11:4, pp. 154-155) truncates every sum to 3 decimals and the indicators and DX to integers, seeds with 14 values and averages 13 DX values for the first ADX: a departure that reproduces only with his own formulas.
- Evidence: the worksheet illustrates the arithmetic on one market and tests nothing, and Wilder’s 1978 book was not read; on random walks the composition agrees with ports of TA-Lib’s DX, ADX and ADXR to about 7e-14 (measured when the recipe was extracted, not pinned by a test). Evidence, not a reference.
- Pinned by
TestRecipeT6WilderDMI; runnable exampleExampleSeries_RMA_wilderADX.
The helpers below take the two directional indicators and the ADX as series, so one block serves the package’s DMIPlus, DMIMinus and ADX (zero-seeded, first ADX on bar n), Wilder’s own seed (t6WilderDMI, the last section of the directional index page beside this one, which Summers’s program computes) and a printed table. A gate read in the first 6n to 8n bars compares seed transients: the share of bars on which the two seeds put the ADX on different sides of 20, 25 or 35 falls from about a third on bar 2n - 1 to a few per cent from bar 4n and under 1% from bar 6n (500 random walks of 560 bars, n = 14; the shares depend on the walk), the burn-in of that page’s opening paragraph. Signals act at the next open through Shift(1) unless a source fixes the close (Pruitt’s “this bar on close”); Summers’s (H+L+C)/3 fills are a convention of his spreadsheet, not an executable price. His Figure 1 is the December 1986 S&P 500 contract (his title says September, but the rows run to 8 December 1986). Values are NaN before their first valid index and flags read 0 there; prices are positive and finite, lengths are in bars and ADX levels in index points.
DMI signals with the ADX gate (Wilder; Summers)
Jim Summers (“Completing the DMI rules”, Stocks & Commodities V7:1, January 1989, pp. 30-34) programs Wilder’s rules in Lotus: when the DI lines cross, “Is ADX greater than 20? If not, no trend exists”, “Is ADX below both DI lines? If so, ignore the signal”, “Is ADX above both DI lines? If so; ignore the signal”, and “If the ADX goes above both DI lines and then turns down, exit”. His code tests >=20 and passes an ADX equal to the larger DI. t6DMISignals gives the gated crosses up and dn and the downturn turn. Wilder’s ADXR levels, 25 to trade and 20 to stand aside, read as a latch, are on t6-directional-index.md (“ADXR and Wilder’s 25/20 gate (Wilder; Drinka and Kille)”): a gate on the ADXR where this one reads the ADX.
above := a.GT(pdi).Add(a.GT(mdi))
gate := a.GTE(adxMin).Mul(above.EQ(1))
up := pdi.CrossesAboveS(mdi).Mul(gate)
dn := pdi.CrossesBelowS(mdi).Mul(gate)
turn := a.LT(a.Shift(1)).Mul(a.Shift(1).GT(a.Shift(2))).Mul(above.EQ(2)).SetN(f+2, 0)- Inputs:
pdi,mdiandaof one length: the package’s DMIs, those oft6WilderDMIor printed columns;adxMin(20, or 25);f, the first valid index of the ADX: n for the package’s, n + n - 1 for Wilder’s seed, 0 for a printed table. - First valid index: f + 2 for
turn, 0 before: the mask keeps the first rise from reading the ADX’s warm-up (with the package’s ADX and f = 0, bar n + 1 reads the warm-up 0 as a rise, and fires on one of the test’s walks);upanddnread 0 until the gate first opens (bar n at the earliest with the package’s ADX, 2n - 1 with Wilder’s seed). - Anchors: on Summers’s Figure 1 (99 printed rows in eight blocks of consecutive days, f = 0) every cross of the printed DIs carries its printed label: three valid signals (04/30, 08/12 and 10/17), 14 “No trend”, three “ADX<+/-DI”, three “ADX>+/-DI” and three adverse crosses of an open trade; the only turn is 05/20’s.
above.EQ(1)is his Entry3 without Entry4, min(DI) < ADX <= max(DI), and the gate equals a loop of Entry2 to Entry4 bit for bit;a.GTE(adxMin)passes an ADX of exactly 20.0. - Traps:
fis the ADX’s first valid index, not the DMI length:SetN(n+2, 0)with n = 14 masks the 05/20 turn of the printed table, and Summers’s first trade does not close.CrossesAboveSandCrossesBelowSread the prior bar inclusively where his code is strict on both bars: Figure 1 prints 22.3 and 22.3 on 09/10, which the recipe reads as the prior bar of a cross on 09/11 and his code as no cross. His prose says “greater than 20” where the code tests>=20, and the dossier’sSetN(28, 0)is neither n nor 2n - 1. A NaN in the inputs gives a closed gate and 0 flags, not NaN, since every comparison with NaN reads 0. - Variant: the dossier’s strict interval,
a.Sub(pdi).Mul(a.Sub(mdi)).LT(0)in place ofabove.EQ(1), which differs only where the ADX equals the larger DI, a tie of printed one-decimal tables. - Variant: Rule 4 off,
gate := a.GTE(adxMin).Mul(above.GT(0)), which takes the three “ADX>+/-DI” crosses of Figure 1. - Evidence: “In 245 days of trading, the DI lines crossed 32 times. Of those 32 times, only three constituted a valid trade using these rules!” (rows deleted from the print, so the count is not checkable). Evidence, not a reference.
- Pinned by
TestRecipeT6DMISignals.
Extreme Point stop and reverse (Wilder; Summers)
Summers’s rules continue: “If the DI lines cross against you, evaluate an exit in terms of the Extreme Point Rule”, the low of the day of a long’s entry signal and the high of a short’s; his code tests it as a standing stop on every bar of a trade, strictly, and reverses (“Wilder calls this process a stop-and-reverse or SAR”) when a valid opposite signal comes on a bar that breaks it. t6DMIExtremePoint books the signals at the next open on PositionSignedRules with OppositeOnStopOnly: true: each trade’s stop is the signal bar’s low (a long) or high (a short), sampled on the entry bar and frozen for the trade, and touched by the decision bar’s low or high, l.Shift(1) and h.Shift(1); an opposite signal reverses the trade only on a bar whose stop fires, a stop without one goes flat, a turn closes the trade while its stop holds, and a stopped trade takes the next valid signal. Summers’s test is strict (“is the low lower than the day of the entry signal? If so, exit”) and the touch is inclusive, so the levels move one ulp outwards, lower and raise, which is exact for every finite level: a low x < ep is x <= math.Nextafter(ep, math.Inf(-1)).
lower := func(x float64) float64 { return math.Nextafter(x, math.Inf(-1)) }
raise := func(x float64) float64 { return math.Nextafter(x, math.Inf(1)) }
pos := h.PositionSignedRules(up.Shift(1), turn.Shift(1), dn.Shift(1), turn.Shift(1), PositionRules{
OppositeOnStopOnly: true,
LongStop: PositionLevel{Level: l.Shift(1).Map(lower), Touch: l.Shift(1)},
ShortStop: PositionLevel{Level: h.Shift(1).Map(raise), Touch: h.Shift(1)},
})
epL := l.Shift(1).EntryValue(pos)
epH := h.Shift(1).EntryValue(pos)- Inputs: highs and lows, and
up,dnandturnof the previous section, of one length. The receiverhgives the length only, since both stops have aTouch. - First valid index:
posreads 0 until the bar after the first valid signal;epLandepH, the Extreme Points read back frompos, are NaN while it is flat. - Anchors: on Figure 1 the three trades reproduce: the short of 05/01 (Extreme Point 245.40) leaves on 05/21 after the 05/20 turn; the long of 08/13 (242.10) is stopped on 09/12 after the low of 09/11, 234.10 (“STOP HIT!!!”, “Extreme Pt Rule”, on a bar without a cross); the short of 10/20 (239.35) is stopped on 10/24 after the high of 10/23, 240.60. The six fills
h.Add(l).Add(c).Div(3)are the printed four-decimal values truncated (the exit of 10/24 is 238.45000000000002, printed 238.4500). A loop of Wilder’s rules equalsposon every bar of Summers’s eight blocks, of the constructed tables9and of 84 runs on random walks (706 trades). - Traps: the dossier’s
l.ValueWhen(setup)latches at the latest setup, not at the trade’s entry, and moves on an ignored same-side signal; itsc.LT(ep)is a close test where Summers tests the low on every bar. Without the one-ulp move a low equal to the Extreme Point stops, which is the inclusive touch, not Summers’s strict test. The touch is the decision bar’s low,l.Shift(1), not the fill bar’s: the signals and the stop act at the next open, and the entry bar itself is not tested. Summers’s code departures not modelled: the stale “SAR?” flag (set by a valid signal of either side while a trade is open and cleared only by an exit, so that a later adverse cross failing the gate can still reverse), the adverse-cross tie (a low equal to the Extreme Point on an adverse-cross bar stops), and the downturn exit on signal and SAR bars with Rule 4 off. - Variant: the stop pattern of the trade-state pages on the stopless book
base := h.PositionSigned(up.Shift(1), turn.Shift(1), dn.Shift(1), turn.Shift(1)), the form this page printed beforePositionSignedRules(t6DMISystem, which the clean-room references pin): it cuts a base trade on the bar after its Extreme Point breaks and waits for the base’s next entry, so it equalsposon every bar before the first bar of a same-side re-entry after a stop or of a base reversal while the Extreme Point held, and can part from there (38 such events in the 706 trades of the 84 runs). - Evidence: Summers reports that “none of the trades made money” on the contract; at his fills the three trades lose 1.62, 16.52 and 3.28 points (derived). Evidence, not a reference.
- Pinned by
TestRecipeT6DMISystem; runnable exampleExampleSeries_PositionSignedRules_wilderDMI.
The Extreme Point as an entry trigger (Agostino and Dolan)
Kenneth Agostino and Brian Dolan (“Make The Trend Your Friend In Forex”, Stocks & Commodities V22:9, September 2004, pp. 14-20) use the Extreme Point as an entry trigger: “when the DI+/- lines cross, traders should note the extreme point for that period in the direction of the crossover (the high if DI+ crosses up over DI-; the low if DI- crosses up over DI+). Only if that extreme point is breached in the subsequent period is a trade signal confirmed”, and they exit “When the ADX begins to move lower from its highest level”. t6EPTrigger reads “in the subsequent period” as the next bar.
up0 := pdi.CrossesAboveS(mdi).SetN(2, 0)
dn0 := pdi.CrossesBelowS(mdi).SetN(2, 0)
le := up0.Shift(1).Mul(h.GT(h.Shift(1)))
se := dn0.Shift(1).Mul(l.LT(l.Shift(1)))
turnA := a.LT(a.Shift(1)).Mul(a.Shift(1).GT(a.Shift(2))).SetN(f+2, 0)
pos := h.PositionSigned(le, turnA, se, turnA)- Inputs: highs and lows,
pdi,mdianda, andfas in the signals section (they give no DMI length). - First valid index: 3 for
leandse(the crosses are masked withSetN(2, 0): on bar 1 the package’s DIs read their bar-0 zeros as a cross); f + 2 for the downturn;posreads 0 before the first entry. - Anchors:
le,seandposequal a loop of the one-bar rule bit for bit (the test’s walks, with Wilder’s seed and with the package’s DMIs), and no bar has both entries. The armed reading, waiting until the breach or until the DIs cross back, composes: witharm := up0.Sub(dn0).Hysteresis(0, 0)andtrigL := h.GT(h.ValueWhen(up0)).Mul(arm.GT(0)),firstL := trigL.Mul(trigL.SumSince(up0).EQ(1))equals its loop bit for bit; it differs fromlewhere the breach comes later than the next bar or the DIs cross back on it. - Traps: the breach is strict: a high equal to the cross bar’s high does not confirm. Their exit is the bare downturn, without Summers’s condition that the ADX lies above both DIs. The dossier’s “a multi-bar wait needs state” is the armed form above.
- Evidence: their two charts (daily EUR/USD, an up cross on 13 November 2003 breached “the following day (November 14)”; hourly Australian dollar), with no DMI length, fills or statistics. Evidence, not a reference.
- Pinned by
TestRecipeT6EPTrigger.
ADX above 35 with a three-close stop (Pruitt)
George Pruitt (The Ultimate Algorithmic Trading System Toolbox, Wiley, 2016, ch. 2, Box 2.1, pp. 30-33) states Wilder’s system as “If 14-day ADX is greater than 35 then If +DI > -DI, then Buy market on close”, with the mirror “SellShort market on close”, and, below 35, “If position is long and close is less than lowest close of prior three days, then Sell market on close”, the short the mirror; his p-code writes close < Lowest(close[1],3). t6DMIPruitt uses the package’s DMIs and books his rules at the close.
a := c.ADX(h, l, c, n)
pdi := c.DMIPlus(h, l, c, n)
mdi := c.DMIMinus(h, l, c, n)
on := a.GT(lvl)
off := a.LT(lvl)
le := on.Mul(pdi.GT(mdi))
se := on.Mul(mdi.GT(pdi))
lx := off.Mul(c.LT(c.Lowest(3).Shift(1)))
sx := off.Mul(c.GT(c.Highest(3).Shift(1)))
pos := c.PositionSigned(le, lx, se, sx)- Inputs: highs, lows and closes; n (14) and
lvlin index points (35; the test also runs 25). - First valid index: n for
leandse(the package’s ADX is 0 before, sooffis 1 there, but no position exists);posreads 0 until the first entry. - Anchors: the book equals a loop of the p-code with TradeStation’s order semantics (a Buy while long ignored, a SellShort while long reversing, exits only from a position, all at the close) bit for bit at 35 and 25; an ADX of exactly 35 neither enters nor exits, and a close equal to the lowest of the three closes before does not exit (strict, as the p-code).
- Traps: the burn-in: on Wilder’s own wheat (Summers, Stocks & Commodities V6:9, September 1988) the package’s zero-seeded ADX is above 35 on bars 14 to 25 and Wilder’s seed on none, so the gate opens on a seed transient; the mask
a.SetN(n+n-1, math.NaN())before the flags keeps the entries to bar 2n - 1 and later. His Figure 2.3 flowchart departs from the p-code (“Lowest Close 4 Days” for three, and an ADX of 35 on the exit branch), and his ADXR formula(ADX[1] + ADX[14]) / 14is a misprint that plays no part here. On the test’s walks no ADX lies within 0.02 of a level and no pair of DIs within 0.2 where the ADX is above it, so the rounding of the package’s recursions, which differs between arm64 and amd64, decides no flag there; near a level it can. - Variant: the flowchart’s ties,
off := a.LTE(lvl)withlx := off.Mul(c.LTE(c.Lowest(3).Shift(1)))and the mirror forsx. - Evidence: his Table 2.1 (35 futures markets; no platform, period or costs printed, most likely AmiBroker runs, as he “used it for most of the testing in Chapters 2 and 3”, p. 141): 68,261.80 dollars summed over 1,445 trades, 21 markets positive; the table adds up (each average P/L is the net over the trades to the cent). Evidence, not a reference.
- Pinned by
TestRecipeT6DMIPruitt; runnable exampleExampleSeries_ADX_pruitt35.
The recipe below reads daily opens, highs, lows and closes, the open o only for the fill price. Prices are positive and finite, lengths are in bars and series are paired by position, so the caller aligns them by timestamp first. Recipe values and levels are NaN before their first valid index (SetN(F, math.NaN())), and flags, states and latches read 0 there: the package’s ADX(n) reads 0 on bars 0 to n - 1 and XAverage(n) passes the close through before bar n - 1, so both are masked before they are compared, and every shifted series a pad can satisfy is masked, or the flag is (the prior high’s +0 pad on bar 0 meets a shifted touch of 0). A resting stop is touched when the high reaches it (GTE) unless the source says “above”, which is strict (on a tick grid the caller adds the tick), a protective stop below is touched when the low reaches it (LTE), and a stop fill price is max(o, level), written o.Maximum(level). The package’s ADX, DMIPlus and DMIMinus are zero-seeded, so for about the first 6n bars a level compares seed transients (the directional index page t6-directional-index.md), and Go fuses their recursions and the exponential average on arm64, which moves them by rounding only. The book’s exhibits are charts over data we do not have: evidence, not a reference. Counts on probe paths that the tests do not reproduce are illustrations, not pins.
Holy Grail (Raschke and Connors)
Linda Bradford Raschke and Laurence A. Connors (Street Smarts, M. Gordon Publishing, 1995, ch. 10, pp. 80-86) require that “A 14-period ADX must initially be greater than 30 and rising”, “Look for a retracement in price to the 20-period exponential moving average”, and “When the price touches the 20-period exponential moving average, put a buy stop above the high of the previous bar”; once filled, “enter a protective sell stop at the newly formed swing low” and “look to exit at the most recent swing high”. t6HolyGrailFrozen arms on the first bar of each spell of an ADX above 30 and rising, takes the long side where +DI is above -DI (implied by the book: its next chapter says “+DI and -DI indicate the direction of the trend”), and renews a one-bar buy stop above each touch bar’s high until one fills. It returns the fills, their price px, the target tgt (the highest high since the arm, to the bar before the fill), the stop stp (the lowest low since that high), both frozen at the fill that opens a trade and read back while it is open, and the trade, which PositionSignedRules closes on a low at or below the stop or a high at or above the target.
a := c.ADX(h, l, c, n).SetN(n, math.NaN())
e := c.XAverage(ne).SetN(ne-1, math.NaN())
up := c.DMIPlus(h, l, c, n).GT(c.DMIMinus(h, l, c, n))
strong := a.GT(30)
sr := strong.Mul(a.GT(a.Shift(1)))
arm := sr.Mul(sr.Shift(1).EQ(0))
touch := l.LTE(e).Mul(strong).Mul(up)
lvl := h.Shift(1)
brk := touch.Shift(1).Mul(h.GT(lvl))
gate := c.Position(arm, brk)
fill := gate.Exits()
px := o.Maximum(lvl)
peak := h.HighestSince(gate.Entries())
swLow := l.LowestSince(h.EQ(peak))
trade := c.PositionSignedRules(fill, nil, nil, nil, PositionRules{
LongTarget: PositionLevel{Level: peak.Shift(1), Touch: h},
LongStop: PositionLevel{Level: swLow.Shift(1), Touch: l},
})
tgt := peak.Shift(1).EntryValue(trade)
stp := swLow.Shift(1).EntryValue(trade)- Inputs: daily opens, highs, lows and closes; n 14 (the ADX and the DMIs) and ne 20 (the exponential average of the closes). The open enters only
px; the tick above the high is the caller’s. Shorts are the mirror (“SELLS ARE REVERSED”). - First valid index: n (14) for the ADX
a, NaN before;srreads 0 on bar n as well, since it compares with the masked bar n - 1, soarmcan fire from n + 1; ne - 1 (19) for the average and the touch; 20 forfillandtrade, 0 before;tgtandstpare NaN on every bar without an open trade. TheDMIPlusandDMIMinusof the direction are live from bar 1 (0 on bar 0 only).lvlis unmasked: its +0 pad on bar 0 reaches no fill, since the shifted touch is 0 there, andpxis meaningful on fill bars only. - Anchors: the gate
c.Position(arm, brk)equals bit for bit a state-machine loop (an arm while armed is ignored, and the first stop fill disarms),pxequals max(o[t], h[t-1]), andtgtandstpequal loops of “the highest high from the opening arm to the bar before the fill” and “the lowest low from the last bar at that high to the bar before the fill”, sampled at the fill that opens the trade, andtradea loop of the gate with the levels frozen there (bit for bit on the 320-bar group and on random paths). On the test’s 320-bar path the stop fills on bars 29, 81, 270 and 280, with (px,tgt,stp) = (101.40625, 102.3125, 100.875), (112.859375, 116.203125, 111.671875) and (111.984375, 128.3125, 106.59375) at the first three; the fill on bar 280, at 114.3125, comes inside the trade from bar 270, which ignores it and keeps its target and stop to the end of the path, where neither is touched.tradeis 1 on bars 29, 81 to 83 and 270 to 319, because bar 30’s low equals the stop (LTE) and bar 84’s high the target (GTE), while bar 80’s high equals the prior bar’s high and does not fill (the stop is strictly above). The five outputs agree bit for bit across architectures although the fused recursions do not: on the test dataais at least 0.357543 from 30, each change ofaat least 0.00444484 from 0, +DI at least 0.00435232 from -DI and the low at least 0.0111456 from the average. - Traps: the dossier’s composition leaves
e := c.XAverage(20)unmasked, sol.LTE(e)compares the low with the close on bars 0 to 18 and holds on all of them; it has no “rising” and no re-arm. “Initially greater than 30 and rising” is nearly vacuous for spells that start by crossing 30: an ADX that crosses 30 from at or below is rising on the crossing bar (by construction: the crossing bar is a rising bar), soarmmarks the first bar of each spell of “above 30 and rising”, and rule 6’s re-arm is the next such spell, an upturn while above 30 (the recrossa.CrossesAboveS(30)contradicts Exhibits 10.1 and 10.2, which take a second trade with the ADX above 30 throughout). Rule 2 expects “a turndown in the ADX” during the retracement, so the touch asks only that the ADX stay above 30. Anchoring the target on everyarmin place ofgate.Entries()restarts the high on an upturn during the pullback: on a probe path the target and the stop then matched their loops on only 11 and 12 of 15 fills (not pinned). The strictness ofa.GT(30)and of the touchl.LTE(e)cannot be pinned without bypassing the ADX and the average, whose values are not dyadic; the strict breakout, the target and the stop are pinned by the planted bars above, and the exit on a bar that reaches both stop and target by a constructed bar (bar 30’s high raised to the target), which the rule set closes, its stop winning over its target, at a price the book leaves to the caller. A NaN high or low inside a spell makes the running high and low, and so the target and the stop of later fills in that spell, NaN until the gate next opens, and a trade opened on a NaN level has no exit at that level, since the rule set reads a NaN level as no level. - Variant: the direction latched at the arm,
up.ValueWhen(arm)in place ofup(NaN before the first arm, which the latches read as no signal). - Variant: a touch that straddles the average,
l.LTE(e).Mul(h.GTE(e))in place ofl.LTE(e), so that a bar wholly below the average does not count. - Departures: the gate asks for an arm between consecutive fills, where rule 6, read for every trade, asks for one after the previous trade’s exit (the book says “After a successful trade”), so an arm inside an open trade opens the gate for the next fill. On the 320-bar path one fill is gated so, on bar 280, by the arm on bar 273 inside the trade from bar 270, and the trade ignores it, so the page’s trade and a loop of rule 6 agree on every bar there; on the test’s 300 random trending paths of 600 bars they part on 104 paths and 2,979 bars (pinned). Rules 5 and 6 as the book states them, “If stopped out, re-enter this trade by placing a new buy stop at the original entry price” and “After a successful trade, the ADX must once again turn up above 30 before another retracement to the moving average can be traded”, need a loop: rule 5 is a resting order across bars at the original price, and rule 6 conditions the re-arm on a trade whose exit reads levels frozen at fills the gate decides, so
PositionArmed(nil, exit, nil, arm, entry)would read the latch’s own output. The trailing stop and the partial exit of rule 4 are discretionary and are not written. - Evidence: the chapter’s Exhibits 10.1 to 10.4 (CBOT wheat and Citicorp in 1995, the Russell 2000 and a 60-minute orange juice contract) print price axes and an ADX pane with no bar values, no statistics and no costs; in Exhibits 10.1 and 10.4 the entry follows a second touch bar, as a one-bar order renewed on each touch bar takes it. Evidence, not a reference.
- Pinned by
TestRecipeT6HolyGrail; runnable exampleExampleSeries_ADX_holyGrail.
Aroon
AroonDown
func (s Series) AroonDown(n int) Series
AroonDown returns Chande’s Aroon-Down over n bars, which measures how recently the lowest low occurred. The window at bar i is the current bar plus the n prior bars, s[i-n] to s[i] (n+1 bars in all), and the value is (n - b) / n * 100, evaluated in that order, where b is how many bars back the lowest value in the window lies. The range is 0 to 100 inclusive: 100 when the current bar is the lowest and 0 when the lowest is exactly n bars back. On ties the most recent lowest bar counts. A NaN never displaces a number as the lowest, and a NaN current bar gives 100. Indices 0 to n-1 are 50 (warm-up), and every value is 50 when n >= len(s); every value is 0 when n < 1. This matches TA-Lib, TradingView and Chande’s stated definition; releases before this change, like Chande’s printed SuperCharts code and TradeStation, used an n-bar window whose minimum was 100/n. Note: The input series should always be the lows for this calculation.
The first valid index is n and the minimum length is n+1. A flat window gives 100, because on ties the most recent lowest bar counts (b = 0), so the warm-up (50) and the flat value differ. 50 reads as neither a strong down-trend (above 70) nor a weak one (below 30), and an AroonUp/AroonDown crossover rule compares 50 with 50 on warm-up bars, so trim (Window(-n)) or mask (SetN(n, math.NaN())) the first n bars. This warm-up was reviewed in GLE-254 (3 October 2026) and kept.
AroonUp
func (s Series) AroonUp(n int) Series
AroonUp returns Chande’s Aroon-Up over n bars, which measures how recently the highest high occurred. The window at bar i is the current bar plus the n prior bars, s[i-n] to s[i] (n+1 bars in all), and the value is (n - b) / n * 100, evaluated in that order, where b is how many bars back the highest value in the window lies. The range is 0 to 100 inclusive: 100 when the current bar is the highest and 0 when the highest is exactly n bars back. On ties the most recent highest bar counts. A NaN never displaces a number as the highest, and a NaN current bar gives 100. Indices 0 to n-1 are 50 (warm-up), and every value is 50 when n >= len(s); every value is 0 when n < 1. This matches TA-Lib, TradingView and Chande’s stated definition; releases before this change, like Chande’s printed SuperCharts code and TradeStation, used an n-bar window whose minimum was 100/n. Note: The input series should always be the highs for this calculation.
The first valid index is n and the minimum length is n+1. A flat window gives 100, because on ties the most recent highest bar counts (b = 0), so the warm-up (50) and the flat value differ. 50 reads as neither a strong up-trend (above 70) nor a weak one (below 30), and an AroonUp/AroonDown crossover rule compares 50 with 50 on warm-up bars, so trim (Window(-n)) or mask (SetN(n, math.NaN())) the first n bars. This warm-up was reviewed in GLE-254 (3 October 2026) and kept.
Vortex Indicator
VortexMinus
func (s Series) VortexMinus(h, l, c Series, n int) Series
VortexMinus implements the -VI component of the Vortex indicator, described by Etienne Botes and Douglas Siepman in TASC Jan 2010.
The warm-up reads 0, not NaN: bars 0 to n-1 are 0, below the indicator’s usual range of about 0.5 to 1.5.
VortexPlus
func (s Series) VortexPlus(h, l, c Series, n int) Series
VortexPlus implements the +VI component of the Vortex indicator, described by Etienne Botes and Douglas Siepman in TASC Jan 2010.
The warm-up reads 0, not NaN: bars 0 to n-1 are 0, below the indicator’s usual range of about 0.5 to 1.5.
Random Walk Index
RandomWalkIndexHigh
func (s Series) RandomWalkIndexHigh(h, l, c Series, minN, maxN int) Series
RandomWalkIndexHigh returns the Random Walk Index of the highs, how far each bar’s high stands above the low of a past bar in units of the move a random walk would make over that many bars, at its largest over the lags minN to maxN.
The receiver is not used. The bars are the highs h, lows l and closes c, one bundle of bars rather than a base and a comparison series, so they are not right-aligned: if the three lengths differ, the result is an empty Series. For lag k at bar t the numerator is h[t] - l[t-k] and the denominator is AR_k times sqrt(k), with AR_k the arithmetic mean of the true ranges of lags 1 to k, the symmetric true range of TrueRange, that is max(c[j-1], h[j]) - min(c[j-1], l[j]), over bars t-k to t-1. The sum S_k of those true ranges is formed in increasing lag order and incrementally across the lags, and the lag’s value is num / ((S_k / k) * sqrt(k)), with the product rounded on its own; the result is the largest of the values of lags minN to maxN. It keeps its sign, so a high below every one of the band’s lows gives a negative value rather than 0, and a zero result is +0. A lag whose computed average range S_k / k is 0 (flat bars with no gap, or a sum so small that the division underflows, so that a longer lag can be left out while a shorter one is kept) is left out, and a bar on which every lag is left out is 0.
The source is E. Michael Poulos, “Of Trends And Random Walks”, in Stocks & Commodities V9:2 (February 1991), with the symmetric true range of his September 1992 article (V10:9). That article is “Are There Persistent Cycles?”, in the same journal. He reads a value above 1 as a move beyond a random walk: on the long band (8, 64) as a trend, an uptrend from the highs and a downtrend from the lows, and on the short band (2, 7) as an overbought or oversold reading, a short-term high or low. The threshold is uncalibrated: on driftless random-walk bars a large share of the valid bars exceed 1 on either side, for both bands.
This is the lag pairing of Poulos’s formula text and of Investor/RT: lag k pairs the low k bars ago with sqrt(k) and the mean range of the k bars before today. Not provided are the MetaStock-style documentation and the TradeStation forum code, whose averages include today, Hartle’s spreadsheet, which pairs the extreme k-1 bars ago with sqrt(k) and uses a one-sided true range, Wilder smoothing of the range, and the anchored drunkard’s walk.
The warm-up reads 0, not NaN: bars 0 to maxN are 0 and the first valid index is maxN+1. The minimum length is maxN+2, and minN < 1, maxN < minN or maxN > len(h)-2 gives len(h) zeros, so maxN = len(h)-2 gives one valid bar, the last.
At a valid bar t the method reads h of bars t-maxN to t, l of bars t-maxN to t-1 and c of bars t-maxN-1 to t-2, whatever minN is, and the bar is NaN when any value read is NaN or an infinity, checked before the zero-range rule. On finite data whose sums overflow, a lag’s value can be 0 (an infinite average range) or NaN (an infinite numerator over one), so a bar can read 0 or NaN although no value it reads is bad. Today’s and yesterday’s closes are not read, so the value can be taken intrabar. Each value depends only on the bars it reads, so the method is window-local and start-invariant bit for bit: dropping bars from the front leaves every later valid bar unchanged. The cost is O(maxN) per valid bar.
The mirror RandomWalkIndexHigh(-l, -h, -c, minN, maxN), with -x the exact negation x.Mul(-1), equals RandomWalkIndexLow(h, l, c, minN, maxN) bit for bit on every input. Where no lag of the band is left out, the band’s value is the largest of the single-lag values of lags minN to maxN, and widening the band does not lower the value at a bar valid for both bands as long as the narrower band keeps a lag there. A single lag k equals h.Sub(l.Shift(k)).Div(c.ATR(h, l, c, k).Shift(1).Mul(math.Sqrt(float64(k)))) from bar k+1 wherever the lag’s average range is not 0, bit for bit on dyadic data, where every sum is exact, and to rounding otherwise. Scaling h, l and c by a power of two leaves the result unchanged bit for bit while nothing is subnormal or overflows. RandomWalkIndexLow is the mirror for the lows.
RandomWalkIndexLow
func (s Series) RandomWalkIndexLow(h, l, c Series, minN, maxN int) Series
RandomWalkIndexLow returns the Random Walk Index of the lows, how far each bar’s low stands below the high of a past bar in units of the move a random walk would make over that many bars, at its largest over the lags minN to maxN.
The receiver is not used. The bars are the highs h, lows l and closes c, one bundle of bars rather than a base and a comparison series, so they are not right-aligned: if the three lengths differ, the result is an empty Series. For lag k at bar t the numerator is h[t-k] - l[t] and the denominator is AR_k times sqrt(k), with AR_k the arithmetic mean of the true ranges of lags 1 to k, the symmetric true range of TrueRange, that is max(c[j-1], h[j]) - min(c[j-1], l[j]), over bars t-k to t-1. The sum S_k of those true ranges is formed in increasing lag order and incrementally across the lags, and the lag’s value is num / ((S_k / k) * sqrt(k)), with the product rounded on its own; the result is the largest of the values of lags minN to maxN. It keeps its sign, so a low above every one of the band’s highs gives a negative value rather than 0, and a zero result is +0. A lag whose computed average range S_k / k is 0 (flat bars with no gap, or a sum so small that the division underflows, so that a longer lag can be left out while a shorter one is kept) is left out, and a bar on which every lag is left out is 0.
The source is E. Michael Poulos, “Of Trends And Random Walks”, in Stocks & Commodities V9:2 (February 1991), with the symmetric true range of his September 1992 article (V10:9). That article is “Are There Persistent Cycles?”, in the same journal. He reads a value above 1 as a move beyond a random walk: on the long band (8, 64) as a trend, an uptrend from the highs and a downtrend from the lows, and on the short band (2, 7) as an overbought or oversold reading, a short-term high or low. The threshold is uncalibrated: on driftless random-walk bars a large share of the valid bars exceed 1 on either side, for both bands.
This is the lag pairing of Poulos’s formula text and of Investor/RT: lag k pairs the high k bars ago with sqrt(k) and the mean range of the k bars before today. Not provided are the MetaStock-style documentation and the TradeStation forum code, whose averages include today, Hartle’s spreadsheet, which pairs the extreme k-1 bars ago with sqrt(k) and uses a one-sided true range, Wilder smoothing of the range, and the anchored drunkard’s walk. On Hartle’s ten bars, with the blank close of the last bar set to NaN since it is not read, the band (2, 8) gives 1.4504754485877898 at bar 9, the value of lag 2, where his sheet prints 1.25, the largest of its lookbacks.
The warm-up reads 0, not NaN: bars 0 to maxN are 0 and the first valid index is maxN+1. The minimum length is maxN+2, and minN < 1, maxN < minN or maxN > len(h)-2 gives len(h) zeros, so maxN = len(h)-2 gives one valid bar, the last.
At a valid bar t the method reads h of bars t-maxN to t-1, l of bars t-maxN to t and c of bars t-maxN-1 to t-2, whatever minN is, and the bar is NaN when any value read is NaN or an infinity, checked before the zero-range rule. On finite data whose sums overflow, a lag’s value can be 0 (an infinite average range) or NaN (an infinite numerator over one), so a bar can read 0 or NaN although no value it reads is bad. Today’s and yesterday’s closes are not read, so the value can be taken intrabar. Each value depends only on the bars it reads, so the method is window-local and start-invariant bit for bit: dropping bars from the front leaves every later valid bar unchanged. The cost is O(maxN) per valid bar.
The mirror RandomWalkIndexLow(-l, -h, -c, minN, maxN), with -x the exact negation x.Mul(-1), equals RandomWalkIndexHigh(h, l, c, minN, maxN) bit for bit on every input, and RandomWalkIndexHigh(-l, -h, -c, minN, maxN) equals this result. Where no lag of the band is left out, the band’s value is the largest of the single-lag values of lags minN to maxN, and widening the band does not lower the value at a bar valid for both bands as long as the narrower band keeps a lag there. A single lag k equals h.Shift(k).Sub(l).Div(c.ATR(h, l, c, k).Shift(1).Mul(math.Sqrt(float64(k)))) from bar k+1 wherever the lag’s average range is not 0, bit for bit on dyadic data, where every sum is exact, and to rounding otherwise. Scaling h, l and c by a power of two leaves the result unchanged bit for bit while nothing is subnormal or overflows. RandomWalkIndexHigh is the mirror for the highs.
Choppiness Index
Chop
func (s Series) Chop(h, l, c Series, n int) Series
Chop computes the Choppiness Index from a single trailing sum of true ranges. At bar i it computes
100 * log10(sum(TR[j]) / (max(h[j]) - min(l[j]))) / log10(n)
over j = i-n+1 through i, where
TR[j] = max(h[j], c[j-1]) - min(l[j], c[j-1]), j >= 1.
The receiver is ignored. Invalid n, empty high, or mismatched OHLC lengths return an empty Series; otherwise the output has len(h) entries. For n >= 2, the first valid index is n, since index zero has no previous close. Earlier entries, insufficient history, and all entries for n == 1 are zero.
A zero range with otherwise finite active TR and extrema returns zero. Nonfinite values propagate naturally, with NaN taking precedence over that guard, and expire with their affected windows. Boundary gaps to the previous close can produce values above 100; results are not clipped. Formula reference: https://www.tradingview.com/support/solutions/43000501980-choppiness-index-chop/
The output is nominally on a 0 to 100 scale. The warm-up reads 0, not NaN: the first valid index is n and the minimum length is n + 1. 0 reads as a perfect trend, since a value below 38.2 is usually read as trending, so trim (Window(-n)) or mask (SetN(n, math.NaN())) the warm-up first.
Efficiency Ratio
EfficiencyRatio
func (s Series) EfficiencyRatio(n int) Series
EfficiencyRatio calculates the Kaufman Efficiency Ratio for a specified length n on a series: the absolute change over the last n bars divided by the sum of the absolute one-bar changes over those bars. Each computed ratio lies in [0, 1]; rounding can put the quotient fractionally above one, so it is clamped to exactly 1 (a NaN is left as NaN). A window with no movement at all (zero total absolute change) has an efficiency of zero. It returns a new Series of the same length without modifying s.
It is the absolute value of Chande’s momentum oscillator over 100: CMO(n) is the signed form times 100, s.Delta(n).Div(s.Delta(1).Abs().Sum(n)).Mul(100) from bar n. s.CMO(n).Abs() equals s.EfficiencyRatio(n).Mul(100) bit for bit on prices whose one-bar changes and window sums are exact, such as prices on a quarter grid, and within 2 ulps in general, and s.CMO(n).Abs().Div(100) is within 2 ulps of the ratio but not bit for bit. VIDYACMO is the exponential average whose constant this ratio drives.
The Vertical Horizontal Filter shares its denominator: it divides the range of the last n closes, c.Highest(n).Sub(c.Lowest(n)), by c.Delta(1).Abs().Sum(n), and the ratio equals c.Delta(n).Abs().Div(c.Delta(1).Abs().Sum(n)).Clamp(0, 1), bit for bit on ordinary prices and to rounding in general. VHF >= ER does not hold: the n-bar change reaches the close before the range’s window, so the closes 0, 10, 10, 10, 10, 10 give a VHF of 0 and an ER of 1 at n = 5, while the range of n+1 closes over the same sum is at least ER. The recipe is listed under “Compositions” in the “Efficiency Ratio” category.
For n >= 1, bars 0 to n-1 (the first min(n, len(s)) bars) are 0. The first valid index is n, and the minimum length for one valid bar is n + 1. n >= len(s) gives all zeros, as does n < 1.
The warm-up reads 0, not NaN. A warm-up 0 is indistinguishable from a computed “no net movement” (perfectly choppy) window, so an untrimmed rule such as ER < 0.3 (chop) fires on every warm-up bar, while a rule such as ER >= 0.3 (trend) does not. Callers should mask or trim the first n bars: er.Window(-n) drops them; er.SetN(n, math.NaN()) returns a copy with them marked NaN. Window(m) returns the last m values for positive m and all but the first -m values for negative m.
Releases before this change gave 0.5 on the warm-up bars. KAMA is unaffected because it reads the ratio only from bar n on. BreakoutModeIndex counts a ratio of at most 0.2 as one of its four conditions.
Compositions
The Vertical Horizontal Filter below divides the range of the last n closes by the sum of the last n absolute close changes: a trend-strength reading without a direction, (n - 1)/n on a straight line (the sum holds one change more than the range spans) and near 0 in congestion. It shares its denominator with EfficiencyRatio, which divides the n-bar change instead of the range. Values are NaN before their first valid index; prices are positive and finite and lengths are in bars. A flat window reads 0, as TA-Lib’s VHF (v0.8.1, September 2026) gives, where Tulip Indicators and pandas-ta give NaN.
Vertical Horizontal Filter (White; Chande; Gopalakrishnan)
Jayanthi Gopalakrishnan (“Vertical Horizontal Filter”, Stocks & Commodities V18:7, July 2000, pp. 42-48) reports Adam White’s 1991 indicator (Futures, August 1991) with Tushar Chande’s sidebar spreadsheet: “the numerator is the difference between the highest close and the lowest close for the last 28 days and the denominator is the 28-day sum of the absolute value of the one-day price change”. The sheet’s columns fix the windows, 28 closes for the range and 28 changes, reaching one close further back, for the sum. “A rising VHF line indicates the trend is strong”, while “it does not indicate trend direction”. t6VHF gives the close form and the high-low form over the same denominator.
den := c.Delta(1).Abs().Sum(n)
vhf := c.Highest(n).Sub(c.Lowest(n)).Div(den).SetN(n, math.NaN())
hl := h.Highest(n).Sub(l.Lowest(n)).Div(den).SetN(n, math.NaN())- Inputs: highs, lows and closes of one length;
n(28; Katsanos tests 36). - First valid index: n, NaN before. Bar n - 1 holds only n - 1 changes (
Delta’s bar-0 zero fills the n-th slot): on Chande’s sheet it would read 3.9375/14.5 = 0.2716, a value the sheet does not print. - Anchors: Chande’s sheet (33 rows in sixteenths, so every value is exact): its column F is the close changes, its column G the 28-day ranges (3.9375 and 3.875), and its five VHF cells in column H are 21/79, 63/212, 63/199, 62/199 and 62/201 bit for bit, printed 0.265823, 0.29717, 0.316583, 0.311558 and 0.308458. Achelis’s vector (Technical Analysis from A to Z, p. 354, through Tulip Indicators’ atoz.txt) gives 18/29, 21/40, 41/45 and 1 bit for bit, and Tulip’s untest vector agrees at its printed three decimals.
c.EfficiencyRatio(n)isc.Delta(n).Abs().Div(den).Clamp(0, 1)with the samedenbit for bit, and the range of n + 1 closes overden,c.Highest(n+1).Sub(c.Lowest(n+1)).Div(den), is at least ER on every bar. - Traps: VHF >= ER does not hold: ER’s change reaches the close before the range’s window, so closes 0, 10, 10, 10, 10, 10, 10.5 give VHF 0 against ER 1 at n = 5 (VHF < ER on 197 bars of the test path). The high-low form is at least the close form where l <= c <= h but is not bounded by 1: highs of 11, lows of 9 and closes of 10 rising to 10.1 on the last bar give 20.000000000000071 at n = 5, and the test path reads 19.75 on the bar after a flat stretch. The dossier masks with 0, which a congestion rule such as
vhf.LT(0.3)reads as congestion on every warm-up bar. The sidebar to Chande’s 1993 article (“Rating Trend Strength”, Stocks & Commodities V11:9, September 1993) prints price differences in its equation but fractional changes in its cell formula and prose, a range over a dimensionless sum; the 2000 sheet reproduces only with price changes, and its formula prints “+-” for the minus. pandas-ta 0.4.71b0 adds the float epsilon to every bar’s range when any window is flat. A NaN close gives NaN on the n + 1 bars whose windows hold it, and an infinite close NaN on n bars and 0 on the next (a finite range over an infinite sum). - Variant: White’s later 18-bar VHF smoothed by a 6-bar average (reported by IncredibleCharts and TA-Lib’s documentation),
vhf.Average(6), first valid at n + 5. - Variant: Markos Katsanos’s two entry conditions (“Which Trend Indicator Wins?”, Stocks & Commodities V34:11, October 2016) on the high-low form at n = 36,
v.CrossesAboveS(0.38).Mul(v.LT(0.45)).Mul(v.GT(v.Shift(10)))andv.GT(v.Lowest(10).Mul(1.5)).Mul(v.CrossesAboveS(0.24))withv := h.Highest(36).Sub(l.Lowest(36)).Div(c.Delta(1).Abs().Sum(36)).SetN(36, math.NaN()); his 50-day average filter, exits and next-open fills are the caller’s. - Evidence: Katsanos’s out-of-sample test (USO, April 2011 to March 2016, TradeStation’s high-low VHF, a cent a share): 21,257 dollars net on 18 trades against 44,592 for the moving average alone, “the worst performer”; on driftless random walks the 28-bar VHF is above 0.35 about a third of the time, so the published thresholds pass much noise. Evidence, not a reference.
- Pinned by
TestRecipeT6VHF; runnable exampleExampleSeries_Highest_verticalHorizontalFilter.
Congestion Index
CongestionIndex
func (s Series) CongestionIndex(h, l, c Series, n int) Series
CongestionIndex implements Markos Katsanos’s Congestion Index (as described in his book “Intermarket Trading Strategies”).
The output is roughly -100 to 100, a percentage rate of change over the range as a fraction of the low. The warm-up reads 0, not NaN: bars 0 to n-2 are 0, which reads as congestion.
If h, l and c differ in length the result is an empty Series. Otherwise it has their length, and every bar is 0 when n < 2 or n > len(h): a history shorter than the window gives zeros rather than an empty Series, so CongestionIndex over a prefix of the bars is that prefix of CongestionIndex over all of them. Releases before this change returned an empty Series when n < 2 or n > len(h). The receiver is not used; a nil receiver gives the same result.
Follow-Through Index
FTI
func (s Series) FTI(minPeriod, maxPeriod, halfLength, lookback int, beta, noiseCut float64) Series
FTI returns the Follow-Through Index at the optimal period for each bar. Khalsa’s FTI measures how strongly a market trends relative to its noise at each candidate cycle period. The optimal period is the local maximum (including endpoints) with the highest FTI value.
Defaults: minPeriod=5, maxPeriod=65, halfLength=40, lookback=100, beta=0.9, noiseCut=0.2.
minPeriod must be at least 3: the period-2 filter passes its input unchanged, so the channel width is 0 and the index would reflect only the floor. A smaller minPeriod is invalid and gives all zeros.
One bar costs about P*(lookback - halfLength)*(2*halfLength + 1) multiply-adds, where P = maxPeriod - minPeriod + 1 is the number of periods: about 300,000 at the defaults.
Memory is bounded by the input and a fixed budget whatever the period range: the periods’ filter coefficients are formed in batches of at most 2^20 values (one period at a time when its halfLength + 1 values are more), so a call allocates on the order of len(s) + lookback + halfLength + 2^20 floats. Releases before this change formed one table of P*(halfLength + 1) values, which for period ranges of the order of the input length could exceed memory (about 149 GiB for FTI(3, 199998, 99999, 100000, 0.9, 0.2) on 100,000 bars) or overflow an int and panic; every output is unchanged.
beta is the fractile, a fraction strictly between 0 and 1, and noiseCut is a fraction of the longest leg with 0 <= noiseCut < 1: a leg counts only if it is longer than noiseCut times the longest leg. The defaults are 0.9 and 0.2; beta 90, noiseCut 20 or a NaN for either gives all zeros (releases before this change accepted a NaN, and a NaN beta gave values that depended on the CPU). The warm-up reads 0, not NaN: bars 0 to lookback-2 are 0.
The channel width has a floor of 1e-5 times the absolute mean of the lookback window’s prices, so the index does not depend on the price unit: scaling the input by a power of 2 leaves every bar unchanged. Releases before this change added 1e-5 in price units, negligible at equity prices but material near 1 and below (8% low at a level of 0.01).
FTIAt
func (s Series) FTIAt(period, halfLength, lookback int, beta, noiseCut float64) Series
FTIAt returns the FTI at a specific fixed period.
period must be at least 3, as minPeriod in FTI; a smaller period is invalid and gives all zeros.
beta is a fraction strictly between 0 and 1 and noiseCut a fraction with 0 <= noiseCut < 1, as in FTI. The warm-up reads 0, not NaN: bars 0 to lookback-2 are 0.
The channel width’s floor is relative to the window’s mean price, as in FTI.
FTILog
func (s Series) FTILog(minPeriod, maxPeriod, halfLength, lookback int, beta, noiseCut float64) Series
FTILog is FTI on log prices, the form in which Aronson and Masters describe the source; its channel-width floor of 1e-5 log units is already scale-free. It is not FTI of the logged input, whose floor is relative to the window’s mean.
minPeriod must be at least 3, as in FTI; a smaller minPeriod is invalid and gives all zeros.
Cost and memory are as in FTI: memory is bounded by the input and a fixed budget whatever the period range.
beta is a fraction strictly between 0 and 1 and noiseCut a fraction with 0 <= noiseCut < 1, as in FTI. The warm-up reads 0, not NaN: bars 0 to lookback-2 are 0.
FTIPeriod
func (s Series) FTIPeriod(minPeriod, maxPeriod, halfLength, lookback int, beta, noiseCut float64) Series
FTIPeriod returns the optimal cycle period at each bar.
minPeriod must be at least 3, as in FTI; a smaller minPeriod is invalid and gives all zeros.
Cost and memory are as in FTI: memory is bounded by the input and a fixed budget whatever the period range.
beta is a fraction strictly between 0 and 1 and noiseCut a fraction with 0 <= noiseCut < 1, as in FTI. The warm-up reads 0, not NaN: bars 0 to lookback-2 are 0, which lies outside [minPeriod, maxPeriod], so it cannot be mistaken for a period.
The channel width’s floor is relative to the window’s mean price, as in FTI.
Regime Detection
BreakoutModeIndex
func (s Series) BreakoutModeIndex(h, l, c Series, n int) Series
BreakoutModeIndex is Ruggiero’s breakout-mode (“confusion”) index, after Linda Raschke’s “breakout mode”. It is described in the “Market Modes” section of chapter 4, “Trading Using Technical Analysis”, of Murray A. Ruggiero Jr., Cybernetic Trading Strategies (Wiley, 1997). On each bar from 29 on it scores four conditions, 0 or 1 each, and the index is the score averaged over n bars (n is Ruggiero’s averaging length N and has no default; he tested 4 to 30). A trade is taken only when the index is at least 2, so the gate is the caller’s idx.GTE(2). The receiver is not used.
The four conditions on a bar are:
- (a) momentum confusion: the 5-bar, 10-bar and 20-bar momentum of the close do not all have the same sign. A zero momentum has no sign, so it counts as confusion.
- (b) mid-range stochastics: the 3-bar averages of the 9-bar and the 14-bar Stochastic of the close (slow %K in its SMA form; TradeStation’s SlowK smooths the stochastic once, by a formula that Harris, TradeStation Made Easy! (Wiley, 2011), does not print, and the 3-bar length is this package’s choice) both lie in the inclusive band 40 to 60. A flat 14-bar window gives Stochastic’s 0, not 50, so it is not mid-range.
- (c) low-volatility latch: the volatility is ATRWilder(10). A latch reads low when the volatility equals its 20-bar lowest, otherwise high when it equals its 20-bar highest, otherwise it holds its last reading. The condition holds while the latch reads low. A flat volatility is both the highest and the lowest, and reads low. The latch starts with neither reading, so (c) is 0 until the first 20-bar low, even while the volatility sits at its high.
- (d) inefficiency: EfficiencyRatio(10) is at most 0.2, inclusive (this package’s reading of Ruggiero’s printed “+/-.20”). A window with no movement has ratio 0, so it counts.
The index on bar t is the integer sum of the counts on the n bars ending at t, converted to float64 and divided by float64(n) once, so index >= 2 holds exactly when the sum is at least 2n. The warm-up reads 0, not NaN: bars 0 to n+27 are 0 and the first valid index is n+28, so the minimum length is n+29. A computed 0 (no condition held on any bar of the window) reads the same as the warm-up. If h, l and c differ in length the result is the empty Series{}; if n < 1 or len(h) < n+29 it is len(h) zeros, even when an input is NaN or infinite. It takes O(len(h)) time for any n.
Neither Harris nor TradeStation’s help prints the formula of its Volatility function, so ATRWilder(10), Wilder’s form of the average true range, is this method’s choice for the volatility.
For finite inputs, from bar n+28 the index equals this composition of existing methods, the latch being Hysteresis’s event form:
m5, m10, m20 := c.Momentum(5), c.Momentum(10), c.Momentum(20)
same := m5.GT(0).Mul(m10.GT(0)).Mul(m20.GT(0)).Add(m5.LT(0).Mul(m10.LT(0)).Mul(m20.LT(0)))
a := same.Mul(-1).Add(1)
k9, k14 := c.Stochastic(h, l, 9).Average(3), c.Stochastic(h, l, 14).Average(3)
b := k9.GTE(40).Mul(k9.LTE(60)).Mul(k14.GTE(40)).Mul(k14.LTE(60))
v := c.ATRWilder(h, l, c, 10)
hi, lo := v.EQ(v.Highest(20)), v.EQ(v.Lowest(20))
cc := hi.Sub(hi.Mul(lo)).Sub(lo).SetN(29, 0).Hysteresis(0, 0).LT(0)
d := c.EfficiencyRatio(10).LTE(0.2)
idx := a.Add(b).Add(cc).Add(d).SetN(29, 0).Average(n)
Its bars before n+28 are not the warm-up zeros: mask them.
NaN: from the first bar p at which h, l or c is NaN or infinite, the result is NaN to the end, bar 0 included (unlike ADXTrendMode, which follows ADX from max(p, 1)). Bars before p are exactly as for finite inputs. No count is computed at or after p: ATRWilder does not recover where it goes NaN, a held latch would show a stale state, and a bad bar 0, which ATRWilder leaves out, is poisoned by this rule.
The index is prefix-invariant: the result on a prefix of the inputs is the prefix of the result. It is path-dependent and not start-invariant: ATRWilder is recursive and the latch holds its reading, so a different start can change a bar.
The evidence for the index is one market (Deutsche mark futures), in-sample, over an optimised range of N, with no random-subsampling control.
BullBearIndex
func (s Series) BullBearIndex(h, l Series, n int) Series
BullBearIndex returns Siroky’s Bull Bear Index, the Student-t distribution function with n-1 degrees of freedom evaluated at the t-score of the difference between the frequencies of new highs and new lows over the last n bars.
The new-high and new-low counts over the last n comparisons are Siroky’s strict bar tests, an outside bar counting in both and an inside bar in neither, and equal counts give exactly 0.5 without the transform. At bar t the window is the n comparisons over bars t-n to t: a new high is a high strictly above the previous bar’s high and a new low a low strictly below the previous bar’s low; with CH new highs, CL new lows and S = CH+CL, the t-score is (CH-CL)/sqrt(S(2n-S)/(2n)), Siroky’s Eq 2, and the output is the Student-t distribution function with n-1 degrees of freedom at that score, the author’s choice. Equal counts include a window of inside or equal bars (S = 0) and one of outside bars (S = 2n), where the score would be 0/0.
h and l are right-aligned at the most recent bar and the receiver is not used; with m the overlap and off = len(h)-m, the result has len(h), bars 0 to off-1 read 0, the first valid index is n within the overlap (bar off+n), the minimum overlap is n+1, and n below 2 or at least m, or an empty l, gives len(h) zeros; this departs from TrueRange, ADX and Chop, which return an empty series for unequal lengths. The warm-up reads 0, not NaN: overlap bars 0 to n-1 are +0 (output bars off to off+n-1), and a non-finite value inside the warm-up does not make a warm-up bar NaN. An n of 3,037,000,500 or more is an invalid call, as n below 2 is, and gives len(h) zeros: from there the integer product S(2n-S) in the score can overflow a 64-bit int.
A 0 is the alignment prefix, the warm-up or an invalid call; no computed value is 0 at the published windows, since an all-new-low window first reads exactly 0 at n = 1349 and is 3.2e-63 at n = 256, while an all-new-high window is exactly 1 from n = 64. A warm-up 0 lies below Siroky’s 0.25 bear line and latches Hysteresis(0.75, 0.25) to -1 from bar 0, so trim with Window(-n) on equal lengths or mask with SetN(off+n, math.NaN()) before the latch.
The method is window-local: a NaN or infinite high or low at overlap bar p makes overlap bars max(p, n) to p+n NaN, n+1 bars, one more than Sum, and the output recovers bit for bit after them. Bar p enters comparisons p and p+1, hence the extra bar; infinities compare as ordered values, but their bars lie inside the footprint, so no spurious count shows.
The output is not a calibrated probability: the two-proportion test treats the new highs and new lows as independent samples, though they share bars and an outside bar counts in both, and the index saturates asymmetrically, at long windows (an all-new-high window reads exactly 1 from n = 64 while an all-new-low window stays positive to n = 1348) and in low-activity windows, where a single new high or new low moves it far from 0.5. The author published no backtest, and the index is not a Markov model: it reports a transformed count, not a state or a transition rate. The 0.75 and 0.25 levels are interpretive, Siroky’s bull and bear lines, and are best applied with strict tests after the trim above, since the warm-up 0 would otherwise read as bearish.
OutsideBars marks a bar that passes both tests, and InsideBars is the engulfing-bar recursion, with equal highs or lows inside, not a bar that passes neither; ElderBullPower and ElderBearPower are the high and the low less an average of the close, price distances rather than counts of new extremes.
Sources: Siroky, “Trend Direction And Probability: The Bull Bear Index”, Technical Analysis of Stocks & Commodities, November 2020, pp.14-18 (the bar tests p.15, Eq 2 and the degrees of freedom p.16); Siroky’s reply to a reader, the same journal, January 2021, p.6, which sets the degrees of freedom at n-1. The article’s worked example (its Fig 2) prints a probability that matches neither n-1 degrees of freedom nor this index, which gives 0.0256 for that figure at n = 10.
Cost: per computed bar, O(1) count updates and, for unequal counts only, one continued-fraction evaluation, stopped at the first factor that is exactly 1 (a bar with equal counts returns 0.5 without one): 12 iterations on the worked example, at most 58 on the kernel grid and 67 over every window to n = 256, and 121 in the slowest window found to n = 10,000, far below the cap of 5,000; one O(n) prefactor per call, computed once after validation; and one allocation per call, the output, with no buffer.
This method is listed under “Compositions” in the “Regime Detection” category.
Verification: a Python reference and a Julia reference, written apart, compute the counts and the kernel and agree with the method bit for bit on the 79,250 count pairs of the kernel grid and on the goldens, natively and as amd64; both also evaluate the exact Student-t distribution function by its finite series to 120 digits or more, and the output lies within n*1e-16 of it; anchors check the counts against GT, LT, Shift and Sum, the sign, scale and mirror identities, and the closed forms at n = 2 and n = 3.
BullBearRatio
func (s Series) BullBearRatio(h, l Series, n int) Series
BullBearRatio returns Siroky’s 2022 bull-bear ratio, the number of new highs divided by the total number of new highs and new lows over the last n bars.
It is Siroky’s later estimate from the same counts, the count ratio without the Student-t transform, and reads 0.5 when the window has no new high and no new low. With nh := h.GT(h.Shift(1)).Sum(n) and nl := l.LT(l.Shift(1)).Sum(n), it equals nh.Ratio(nh.Add(nl)) from bar n on equal lengths, except that it reads 0.5 when the window has no new high and no new low, where the recipe nh.Ratio(nh.Add(nl)) gives 0. The ratio is formed as float64(CH)/float64(CH+CL), rounded once: equal counts read exactly 0.5 and a window with no new low reads exactly 1.
h and l are right-aligned at the most recent bar and the receiver is not used; with m the overlap and off = len(h)-m, the result has len(h), bars 0 to off-1 read 0, the first valid index is n within the overlap (bar off+n), the minimum overlap is n+1, and n below 2 or at least m, or an empty l, gives len(h) zeros; this departs from TrueRange, ADX and Chop, which return an empty series for unequal lengths. The warm-up reads 0, not NaN: overlap bars 0 to n-1 are +0, and a non-finite value inside the warm-up does not make a warm-up bar NaN.
A computed 0 is any window with no new high and at least one new low, so the warm-up 0 is not a sentinel here: trim with Window(-n) on equal lengths, or mask with SetN(off+n, math.NaN()), before treating a low value as bearish.
The method is window-local: a NaN or infinite high or low at overlap bar p makes overlap bars max(p, n) to p+n NaN, n+1 bars, one more than Sum, and the output recovers bit for bit after them. Bar p enters comparisons p and p+1, hence the extra bar; infinities compare as ordered values, but their bars lie inside the footprint, so no spurious count shows.
The ratio is not a calibrated probability: it is the share of the window’s new extremes that are new highs, with no transform, no backtest published by the author, and the same strict bar tests as BullBearIndex, so a window with one new high and no new low reads 1 at any n.
OutsideBars marks a bar that passes both tests, and InsideBars is the engulfing-bar recursion, with equal highs or lows inside, not a bar that passes neither; ElderBullPower and ElderBearPower are the high and the low less an average of the close, price distances rather than counts of new extremes.
Sources: Siroky, “Linear Regression Of Price And Time, Part 4: Logistic Asset Allocation”, Technical Analysis of Stocks & Commodities, August 2022, pp.23-24, which uses the ratio over 25 days; the counts are the bar tests of Siroky’s “Trend Direction And Probability: The Bull Bear Index”, the same journal, November 2020, pp.14-18.
Cost: O(1) per computed bar, the count updates and one division; one allocation per call, the output, with no buffer.
This method is listed under “Compositions” in the “Regime Detection” category.
Verification: a Python reference with exact fractions and a Julia reference agree with the method bit for bit on the goldens, natively and as amd64; anchors check it against nh.Ratio(nh.Add(nl)) built from GT, LT, Shift, Sum and Add, and its side of 0.5 against BullBearIndex’s.
DFAAlpha
func (s Series) DFAAlpha(n int) Series
DFAAlpha computes the DFA (DFA1 / linear detrending) scaling exponent alpha over a rolling window of length n.
By default, this implementation applies DFA to first differences (returns) of the input series. This aligns the typical trading interpretation where alpha ≈ 0.5 corresponds to a random walk in returns, >0.5 trending persistence, and <0.5 mean reversion.
Implementation notes: - Scales considered are integers s in [4, n/4]. If fewer than two scales are available, the alpha for that bar is 0. - For each scale s, the profile is split into floor(n/s) non-overlapping segments from the start and again from the end (2*m segments total). Linear least squares detrending is applied within each segment and the total mean squared residual across all segments is used to compute F(s). - Alpha is estimated as the slope of the linear regression of log(F(s)) versus log(s) across the chosen scales.
Bars 0 to n-2 are exactly 0: the first valid index is n-1 and the minimum length is n. n must be at least 20, which gives the two scales (4 and 5) a fit needs; a smaller n is invalid and gives all zeros, as it did before. alpha = 0 reads as strongly mean-reverting, well below 0.5, so mask (SetN(n-1, math.NaN())) the bars before n-1.
DirectionalChange
func (s Series) DirectionalChange(theta float64, thetaDown ...float64) Series
DirectionalChange returns the confirmed directional-change state of a price series, +1 in an upward run, -1 in a downward run and 0 before the first confirmation, a run being confirmed when price moves by more than the fraction theta from its running extreme.
The machine is the directional change of Chen and Tsang (2021), Eq 2.1 and Appendix A, with this library’s strict tie rule. Here up is theta, and down is thetaDown[0] when thetaDown has at least one element, else theta: only thetaDown[0] is read, and further elements are ignored whatever their values. An upward run is confirmed when the price has risen from the running low LL by more than the fraction up, and a downward run when it has fallen from the running high LH by more than the fraction down. Before the first confirmation the machine tracks both extremes from the first valid bar; in an upward run it tracks only LH, and in a downward run only LL. On each later valid bar with price p the extremes extend first, a tie moving the extreme and its bar to the latest bar; then a downward run is confirmed when (LH - p)/LH > down, and otherwise an upward run when (p - LL)/LL > up. The bar whose price completes the move is the confirmation bar; the extreme the move was measured from (the peak for a downward run, the trough for an upward run) becomes the last confirmed extreme ref, at bar iRef, and the other extreme restarts at the confirming bar. Each test is one subtraction and then one division, not a product limit such as LL*(1+up). DirectionalChangeExtension gives the extension (p - ref)/ref in the same shape, DirectionalChangeAge the age t - iRef and DirectionalChangeEvent the confirmations themselves.
The state is defined on every bar and is not NaN. It is +1 from a bar that confirms an upward run and -1 from a bar that confirms a downward run, held until the next confirmation, and 0 only before the first confirmation: once non-zero it is not 0 again. Before the first confirmation the down test comes first; with these ratio tests the two cannot both hold on one bar for valid thresholds, so the order is not observable and at most one confirmation fires on a bar.
The thresholds are valid if and only if 0 < up < +Inf and 0 < down < 1; NaN fails every comparison, so a symmetric theta must be below 1. An invalid thetaDown does not fall back to theta: DirectionalChange(0.1, 1) is invalid although DirectionalChange(0.1) is valid, and an empty thetaDown is the same as none. Every invalid pair gives len(s) zeros, and an empty or nil receiver gives an empty result.
Units. theta and thetaDown are fractions: 0.05 means a 5% move. This differs on purpose from the older price-move thresholds in nseries, which take percentages: UpDown, UpDownString and UpDownSum (tolerance), and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The DirectionalChange family follows the directional-change literature (Chen & Tsang, Eq 2.1), where the threshold and the extension are fractions. DirectionalChangeExtension is therefore a fraction; DeltaPercent gives the same move multiplied by 100. The two conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. To use a percentage p, pass p/100. Go folds constant expressions exactly, so the constants 0.7/100 and 350.01 equal 0.007 and 0.35. The caveat is for p a float64 variable, where p/100 is computed at run time: for a whole-number percentage it equals the decimal literal (p = 5 gives 0.05), but for a fractional one it can differ from the literal in the last bit (p = 0.7 gives p/100 == 0.006999999999999999, not 0.007), and p0.01 can differ even for whole numbers (p = 35 gives p0.01 == 0.35000000000000003). Write the fraction literal (0.007) when a rule is stated in decimals. Because the tests are strict and exact, a one-bit difference in theta can move a confirmation that lands exactly on the threshold. For the same reason, a percentage test such as (p-LL)/LL100 > 7 is not the same test as (p-LL)/LL > 0.07: on [13.00, 13.91] the percentage test fires and the fraction test does not. For thresholds in points, see DirectionalChangePoints.
A threshold is crossed only when it is exceeded: a move exactly equal to its threshold does not confirm, so on [100, 110] at 0.1 nothing is confirmed, because (110 - 100)/100 is exactly the float64 0.1. To reproduce a source that counts equality as a crossing, pass math.Nextafter(theta, 0) and, for an asymmetric pair, math.Nextafter(thetaDown[0], 0): both tests use >, so both thresholds move towards 0, and a ratio exceeds math.Nextafter(x, 0) exactly when it is at least x, for every float64 ratio, because no float64 lies between a value and its neighbour. The one edge is a threshold of 5e-324, where math.Nextafter gives 0, which is invalid: pass 5e-324 unchanged, since no relative move between two distinct positive float64 prices is at most 5e-324, so both rules agree there.
The first valid index is 0 and the minimum length is 1. There is no warm-up: bar 0 of a valid series gives state 0. The 0 before the first confirmation is the undetermined state, not a warm-up, and DirectionalChange(theta, thetaDown…).EQ(0) detects exactly the undetermined bars, where the age and the event are 0. Callers that feed the state to a latch, a rank or a state builder mask the 0 first.
A bar is missing when its price is not finite or is at most 0: a missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. On a missing bar the state is the previous bar’s state, which is 0 at bar 0 and before the first confirmation. Missing bars are invisible except to the clock: deleting every missing bar from s gives the same state, event and extension on the remaining bars, and after a missing bar the machine carries on exactly as if the bar were absent. Non-positive finite prices are missing by design, because relative thresholds need positive prices, and so are +Inf and -Inf; the bar-count swing views treat infinities and non-positive values as ordered values instead.
The machine is a latch: it remembers its last confirmation, so it is not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars. On a 20,000-bar quarter-step random walk, runs started at 104 later bars agreed bit for bit with the full run, on the state, the extension and the age together, after a median of 14.5, 65.5 and 450.5 bars (maximum 58, 221 and 1062) at theta 0.01, 0.03 and 0.1, each within one confirmation of the full run.
The method is causal and deterministic: each output at bar t reads only s[0..t], every prefix of s gives the same first values bit for bit, and nothing is revised. Each confirmation is stamped at the bar whose price completes the move, and the extreme it confirms lies in the past, so the machine lags each turn by at least a threshold’s move: a rise of more than up from the trough, or a fall of more than down from the peak. A zigzag, Pivots, PivotIndices, Swings, SwingsHL and SwingPoints place turning points with hindsight and are not causal. Brown (2004) shows what ignoring the delay costs, 718.5% against 36.4% a year.
The settings of the sources are documentation, not causal parameters. Chen and Tsang (2021) use thresholds from 0.001 to 0.01 on intraday FX and 0.003 (and 0.004) for daily index tracking, with the inclusive Eq 2.1, which is DirectionalChange(math.Nextafter(theta, 0)). Vakkur (1997) uses 0.10 on monthly S&P 500 closes, which the caller supplies; his spreadsheet is strict, close to DirectionalChange(0.10), from which it differs only by the rounding of its product tests and its assumed upward start, and his prose is inclusive (“100 to 110” fires), which is DirectionalChange(math.Nextafter(0.10, 0)). Merrill (1988) uses 0.05 for market averages and 0.10 for stocks, measured from the low point, “5% or more”: with f a float64 variable, so that f/(1+f) is computed at run time, this is DirectionalChange(math.Nextafter(f, 0), math.Nextafter(f/(1+f), 0)), and the plain DirectionalChange(f, f/(1+f)) is the strict rule “more than f”. The variable matters: Go folds the constant 1 - 1/1.05 exactly, to the constant 0.05/1.05, while at run time 1 - 1/1.05 is 0.04761904761904767 and, even after math.Nextafter, does not confirm the decline on [100, 105, 100]. The two calls equal Merrill’s literal rule, (H - p)/p against f, only away from rounding ties, because each rule rounds its own quotient: on [64.47, 61.4] at f = 0.05 his quotient rounds to 0.05, so his strict test misses a decline that DirectionalChange(f, f/(1+f)) confirms, and that the exact decline of those float64 prices, just above 5%, warrants; on [14.07, 13.4] the inclusive call confirms a decline just below 5%. They agree on every bar of the AAPL closes of 2023 and of a quarter-step and a cent random walk at f = 0.01, 0.05 and 0.10. Dai, Zhang and Zhu use a rally of “24% or more” and a decline of “more than 19%”, which is DirectionalChange(math.Nextafter(0.24, 0), 0.19), and their segment tables are full-sample. Raftopoulos (2003) uses 0.10 to 0.18, inclusive, which is DirectionalChange(math.Nextafter(f, 0)) with f the chosen setting.
DirectionalChange is not a Markov model but a state source for one, and no trading edge is demonstrated: Vakkur’s r^2 of 0.084 is in-sample, and Chen and Tsang score their tracking against labels drawn with hindsight.
AutoTuneDC is unrelated: DC there is the dominant cycle. Hysteresis is a latch on a value’s level against two fixed thresholds, not on a relative move from a running extreme. The swing views SwingHighValue, SwingLowValue, MarketStructure, ClearMethodDirection, GannSwingDirection, SwingTrend, WilliamsSwingDirection and BasingPointDirection build bar-count, Clear and basing-point swings; none of them confirms a swing by a threshold move. PointAndFigureDirection on log closes with a box of math.Log1p(p) is close to DirectionalChange((1+p)^reversal - 1) but not equal to it: it counts whole boxes from a grid level, not a relative move from the exact extreme.
The cost is one pass, O(1) per bar, and the method allocates only the result: one allocation per call whatever the length and whether the thresholds are valid, and none for an empty receiver.
Recipes built on the DirectionalChange methods are listed under “Compositions” in the “Regime Detection” category. Meyers’s percentage reversal on a regression forecast curve is under “Linear Regression”. The run-state alphabet under “Markov Models” maps the state to 0 and 1. Vakkur’s extendedness strata under “Markov Models” take their state from it.
Verification: all four outputs agree bit for bit with two independent references, one transcribed from the steps above and one from Chen and Tsang’s Eq 2.1 and Appendix A, and with the published examples of Chen and Tsang (their Fig 2.1 and Fig 5.2); on Vakkur’s Fig 1 the extension times 100 is within 0.1 of his printed figures on rows 11 to 13. On finite positive data, at a confirmation bar t with age k, and with p here the previous event bar (the first valid bar for the first event), the confirmed extreme s[t-k] is s.Highest(t-p+1)[t] for a -1 event and s.Lowest(t-p+1)[t] for a +1 event, and k is (t-p) - s.IndexOfHighestS(t-p+1)[t] for a -1 event and (t-p) - s.IndexOfLowestS(t-p+1)[t] for a +1 event. When up is below every one-bar rise (s[t] - s[t-1])/s[t-1] and down below every one-bar fall (s[t-1] - s[t])/s[t-1], the state is the forward-filled sign of s.Momentum(1), and 0 before the first non-zero move.
DirectionalChangeAge
func (s Series) DirectionalChangeAge(theta float64, thetaDown ...float64) Series
DirectionalChangeAge returns the number of bars from the last confirmed extreme of the directional-change state machine to the current bar.
The machine is that of DirectionalChange: the directional change of Chen and Tsang (2021), Eq 2.1 and Appendix A, with a strict tie rule. Here up is theta, and down is thetaDown[0] when thetaDown has at least one element, else theta: only thetaDown[0] is read, and further elements are ignored. Before the first confirmation the machine tracks both the running high LH and the running low LL from the first valid bar; in an upward run it tracks only LH, and in a downward run only LL. On each later valid bar with price p the extremes extend first, a tie moving the extreme and its bar to the latest bar; then a downward run is confirmed when (LH - p)/LH > down, and otherwise an upward run when (p - LL)/LL > up. The extreme the move was measured from (the peak for a downward run, the trough for an upward run) becomes the last confirmed extreme ref, at bar iRef, and the other extreme restarts at the confirming bar. DirectionalChange gives the state, DirectionalChangeExtension the extension (p - ref)/ref, DirectionalChangeAge the age t - iRef and DirectionalChangeEvent the confirmations.
The age at bar t is t - iRef: Chen and Tsang’s T(i), counted in bars rather than in physical time. It is a whole number, 0 before the first confirmation and at least 1 (and at most t) wherever the state is not 0. On a confirmation bar it is the distance back to the extreme just confirmed, which by the tie rule is the latest bar holding that extreme value since the previous confirmation. It is a bar-index difference, so it counts missing bars, and it is not NaN. StateAge of the state counts from the confirmation bar, not from the extreme.
The thresholds are valid if and only if 0 < up < +Inf and 0 < down < 1; NaN fails every comparison. An invalid thetaDown does not fall back to theta: DirectionalChangeAge(0.1, 1) is invalid although DirectionalChangeAge(0.1) is valid. Every invalid pair gives len(s) zeros, and an empty or nil receiver gives an empty result.
Units. theta and thetaDown are fractions: 0.05 means a 5% move. This differs on purpose from the older price-move thresholds in nseries, which take percentages: UpDown, UpDownString and UpDownSum (tolerance), and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The DirectionalChange family follows the directional-change literature (Chen & Tsang, Eq 2.1), where the threshold and the extension are fractions. DirectionalChangeExtension is therefore a fraction; DeltaPercent gives the same move multiplied by 100. The two conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. To use a percentage p, pass p/100. Go folds constant expressions exactly, so the constants 0.7/100 and 350.01 equal 0.007 and 0.35. The caveat is for p a float64 variable, where p/100 is computed at run time: for a whole-number percentage it equals the decimal literal (p = 5 gives 0.05), but for a fractional one it can differ from the literal in the last bit (p = 0.7 gives p/100 == 0.006999999999999999, not 0.007), and p0.01 can differ even for whole numbers (p = 35 gives p0.01 == 0.35000000000000003). Write the fraction literal (0.007) when a rule is stated in decimals. Because the tests are strict and exact, a one-bit difference in theta can move a confirmation that lands exactly on the threshold. For the same reason, a percentage test such as (p-LL)/LL100 > 7 is not the same test as (p-LL)/LL > 0.07: on [13.00, 13.91] the percentage test fires and the fraction test does not. For thresholds in points, see DirectionalChangePoints.
A threshold is crossed only when it is exceeded: a move exactly equal to its threshold does not confirm, so on [100, 110] at 0.1 nothing is confirmed, because (110 - 100)/100 is exactly the float64 0.1. To reproduce a source that counts equality as a crossing, pass math.Nextafter(theta, 0) and, for an asymmetric pair, math.Nextafter(thetaDown[0], 0): both tests use >, so both thresholds move towards 0, and a ratio exceeds math.Nextafter(x, 0) exactly when it is at least x, for every float64 ratio, because no float64 lies between a value and its neighbour. The one edge is a threshold of 5e-324, where math.Nextafter gives 0, which is invalid: pass 5e-324 unchanged, since no relative move between two distinct positive float64 prices is at most 5e-324, so both rules agree there.
The first valid index is 0 and the minimum length is 1. There is no warm-up: bar 0 of a valid series gives age 0. The 0 before the first confirmation is the undetermined state, not a warm-up, and DirectionalChange(theta, thetaDown…).EQ(0) detects exactly the undetermined bars, which are the bars where the age is 0.
A bar is missing when its price is not finite or is at most 0: a missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. On a missing bar the age is the previous bar’s age plus 1 when the state is not 0, and 0 otherwise. Deleting every missing bar from s changes the age only by the missing bars it counts: with them present, the age is the bar-index distance to the same extreme bar.
The machine is a latch: it remembers its last confirmation, so it is not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars. On a 20,000-bar quarter-step random walk, runs started at 104 later bars agreed bit for bit with the full run, on the state, the extension and the age together, after a median of 14.5, 65.5 and 450.5 bars (maximum 58, 221 and 1062) at theta 0.01, 0.03 and 0.1, each within one confirmation of the full run.
The method is causal and deterministic: each output at bar t reads only s[0..t], every prefix of s gives the same first values bit for bit, and nothing is revised. Each confirmation is stamped at the bar whose price completes the move, and its extreme lies in the past, so the output lags each turn by the confirmation delay.
The settings of the sources are documentation, not causal parameters, and DirectionalChange gives their calls: Chen and Tsang (2021) use thresholds from 0.001 to 0.01 on intraday FX and 0.003 (and 0.004) for daily index tracking, inclusive; Vakkur (1997) uses 0.10 on monthly S&P 500 closes, which the caller supplies, his spreadsheet strict and his prose inclusive; Merrill (1988) uses 0.05 for market averages and 0.10 for stocks, from the low point, “5% or more”; Dai, Zhang and Zhu use 0.24 up (inclusive) and 0.19 down (strict), and their segment tables are full-sample; Raftopoulos (2003) uses 0.10 to 0.18, inclusive. The machine is not a Markov model but a state source for one, and no trading edge is demonstrated: Vakkur’s r^2 of 0.084 is in-sample, and Chen and Tsang score their tracking against labels drawn with hindsight.
The cost is one pass, O(1) per bar, and the method allocates only the result: one allocation per call whatever the length and whether the thresholds are valid, and none for an empty receiver.
Recipes built on the DirectionalChange methods are listed under “Compositions” in the “Regime Detection” category.
Verification: on finite positive data, at a confirmation bar t with age k, and with p here the previous event bar (the first valid bar for the first event), k equals (t-p) - s.IndexOfHighestS(t-p+1)[t] for a -1 event and (t-p) - s.IndexOfLowestS(t-p+1)[t] for a +1 event; this needs the rule that a tie moves the extreme to the latest bar, and a first-occurrence rule fails it. All four outputs also agree bit for bit with two independent references and with the published examples of Chen and Tsang (their Fig 2.1 and Fig 5.2).
DirectionalChangeEvent
func (s Series) DirectionalChangeEvent(theta float64, thetaDown ...float64) Series
DirectionalChangeEvent returns +1 on each bar that confirms an upward directional change, -1 on each bar that confirms a downward one, and 0 on every other bar.
The machine is that of DirectionalChange: the directional change of Chen and Tsang (2021), Eq 2.1 and Appendix A, with a strict tie rule. Here up is theta, and down is thetaDown[0] when thetaDown has at least one element, else theta: only thetaDown[0] is read, and further elements are ignored. Before the first confirmation the machine tracks both the running high LH and the running low LL from the first valid bar; in an upward run it tracks only LH, and in a downward run only LL. On each later valid bar with price p the extremes extend first, a tie moving the extreme and its bar to the latest bar; then a downward run is confirmed when (LH - p)/LH > down, and otherwise an upward run when (p - LL)/LL > up. The extreme the move was measured from (the peak for a downward run, the trough for an upward run) becomes the last confirmed extreme ref, at bar iRef, and the other extreme restarts at the confirming bar. DirectionalChange gives the state, DirectionalChangeExtension the extension (p - ref)/ref, DirectionalChangeAge the age t - iRef and DirectionalChangeEvent the confirmations.
The event is the confirmation itself: at most one fires on a bar, the event is non-zero exactly on confirmation bars and equals the new state there, and the first confirmation out of the undetermined state is an event. It is 0 on a missing bar and is not NaN. It equals DirectionalChange(theta, thetaDown…).Delta().Clamp(-1, 1) bit for bit on every bar, missing bars and invalid thresholds included, but is computed without forming the state. At an event bar t with age k, as DirectionalChangeAge gives it, the confirmed extreme is bar t-k: a swing high for a -1 event and a swing low for a +1 event.
The thresholds are valid if and only if 0 < up < +Inf and 0 < down < 1; NaN fails every comparison. An invalid thetaDown does not fall back to theta: DirectionalChangeEvent(0.1, 1) is invalid although DirectionalChangeEvent(0.1) is valid. Every invalid pair gives len(s) zeros, and an empty or nil receiver gives an empty result.
Units. theta and thetaDown are fractions: 0.05 means a 5% move. This differs on purpose from the older price-move thresholds in nseries, which take percentages: UpDown, UpDownString and UpDownSum (tolerance), and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The DirectionalChange family follows the directional-change literature (Chen & Tsang, Eq 2.1), where the threshold and the extension are fractions. DirectionalChangeExtension is therefore a fraction; DeltaPercent gives the same move multiplied by 100. The two conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. To use a percentage p, pass p/100. Go folds constant expressions exactly, so the constants 0.7/100 and 350.01 equal 0.007 and 0.35. The caveat is for p a float64 variable, where p/100 is computed at run time: for a whole-number percentage it equals the decimal literal (p = 5 gives 0.05), but for a fractional one it can differ from the literal in the last bit (p = 0.7 gives p/100 == 0.006999999999999999, not 0.007), and p0.01 can differ even for whole numbers (p = 35 gives p0.01 == 0.35000000000000003). Write the fraction literal (0.007) when a rule is stated in decimals. Because the tests are strict and exact, a one-bit difference in theta can move a confirmation that lands exactly on the threshold. For the same reason, a percentage test such as (p-LL)/LL100 > 7 is not the same test as (p-LL)/LL > 0.07: on [13.00, 13.91] the percentage test fires and the fraction test does not. For thresholds in points, see DirectionalChangePoints.
A threshold is crossed only when it is exceeded: a move exactly equal to its threshold does not confirm, so on [100, 110] at 0.1 nothing is confirmed, because (110 - 100)/100 is exactly the float64 0.1. To reproduce a source that counts equality as a crossing, pass math.Nextafter(theta, 0) and, for an asymmetric pair, math.Nextafter(thetaDown[0], 0): both tests use >, so both thresholds move towards 0, and a ratio exceeds math.Nextafter(x, 0) exactly when it is at least x, for every float64 ratio, because no float64 lies between a value and its neighbour. The one edge is a threshold of 5e-324, where math.Nextafter gives 0, which is invalid: pass 5e-324 unchanged, since no relative move between two distinct positive float64 prices is at most 5e-324, so both rules agree there.
The first valid index is 0 and the minimum length is 1. There is no warm-up: bar 0 of a valid series gives event 0. The 0 before the first confirmation is the undetermined state, not a warm-up, and DirectionalChange(theta, thetaDown…).EQ(0) detects exactly the undetermined bars, where the event is 0.
A bar is missing when its price is not finite or is at most 0: a missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. The event is 0 on a missing bar. Deleting every missing bar from s gives the same events on the remaining bars, and after a missing bar the machine carries on exactly as if the bar were absent.
The machine is a latch: it remembers its last confirmation, so it is not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars. On a 20,000-bar quarter-step random walk, runs started at 104 later bars agreed bit for bit with the full run, on the state, the extension and the age together, after a median of 14.5, 65.5 and 450.5 bars (maximum 58, 221 and 1062) at theta 0.01, 0.03 and 0.1, each within one confirmation of the full run.
The method is causal and deterministic: each output at bar t reads only s[0..t], every prefix of s gives the same first values bit for bit, and nothing is revised. Each confirmation is stamped at the bar whose price completes the move, and its extreme lies in the past, so the output lags each turn by the confirmation delay.
The settings of the sources are documentation, not causal parameters, and DirectionalChange gives their calls: Chen and Tsang (2021) use thresholds from 0.001 to 0.01 on intraday FX and 0.003 (and 0.004) for daily index tracking, inclusive; Vakkur (1997) uses 0.10 on monthly S&P 500 closes, which the caller supplies, his spreadsheet strict and his prose inclusive; Merrill (1988) uses 0.05 for market averages and 0.10 for stocks, from the low point, “5% or more”; Dai, Zhang and Zhu use 0.24 up (inclusive) and 0.19 down (strict), and their segment tables are full-sample; Raftopoulos (2003) uses 0.10 to 0.18, inclusive. The machine is not a Markov model but a state source for one, and no trading edge is demonstrated: Vakkur’s r^2 of 0.084 is in-sample, and Chen and Tsang score their tracking against labels drawn with hindsight.
The cost is one pass, O(1) per bar, and the method allocates only the result: one allocation per call whatever the length and whether the thresholds are valid, and none for an empty receiver.
Recipes built on the DirectionalChange methods are listed under “Compositions” in the “Regime Detection” category.
Verification: DirectionalChangeEvent(theta, thetaDown…) equals DirectionalChange(theta, thetaDown…).Delta().Clamp(-1, 1) bit for bit on every bar, missing bars and invalid thresholds included, because the state changes only at confirmations, by 1 or by 2, and a held state gives Delta 0. All four outputs also agree bit for bit with two independent references and with the published examples of Chen and Tsang (their Fig 2.1 and Fig 5.2).
DirectionalChangeExtension
func (s Series) DirectionalChangeExtension(theta float64, thetaDown ...float64) Series
DirectionalChangeExtension returns the signed fractional move (p - ref)/ref of each price from the last confirmed extreme of the directional-change state machine.
The machine is that of DirectionalChange: the directional change of Chen and Tsang (2021), Eq 2.1 and Appendix A, with a strict tie rule. Here up is theta, and down is thetaDown[0] when thetaDown has at least one element, else theta: only thetaDown[0] is read, and further elements are ignored. Before the first confirmation the machine tracks both the running high LH and the running low LL from the first valid bar; in an upward run it tracks only LH, and in a downward run only LL. On each later valid bar with price p the extremes extend first, a tie moving the extreme and its bar to the latest bar; then a downward run is confirmed when (LH - p)/LH > down, and otherwise an upward run when (p - LL)/LL > up. The extreme the move was measured from (the peak for a downward run, the trough for an upward run) becomes the last confirmed extreme ref, at bar iRef, and the other extreme restarts at the confirming bar. DirectionalChange gives the state, DirectionalChangeExtension the extension (p - ref)/ref, DirectionalChangeAge the age t - iRef and DirectionalChangeEvent the confirmations.
The extension at a valid bar with price p is (p - ref)/ref, a signed fraction: positive above ref and negative below it. It is the test’s own shape, one subtraction and then one division, so on a confirmation bar it equals the test’s own value, above up on a +1 confirmation and below -down on a -1 confirmation, exactly. It is Vakkur’s extendedness as a fraction (he forms p/ref - 1, which can differ in the last bit), and |ext|/theta is Chen and Tsang’s TMV, Eq 4.1 written literally as (|Ps - Pe|/Ps)/theta with Ps the last confirmed extreme and Pe the current price, bit for bit. It is at least -1, it is +Inf when the ratio overflows (on [1e-300, 1e10] at 0.1 it is +Inf at bar 1), and it is not -Inf. It is 0 on valid bars before the first confirmation, and NaN on a missing bar and only there, so a non-positive price gives NaN by design.
Because the extension is a fraction, the exact bridge to percent outputs is DeltaPercent: on finite positive data, at every bar t where the state is not 0, the extension times 100 is s.DeltaPercent(k)[t] bit for bit, with k the age at t.
The thresholds are valid if and only if 0 < up < +Inf and 0 < down < 1; NaN fails every comparison. An invalid thetaDown does not fall back to theta: DirectionalChangeExtension(0.1, 1) is invalid although DirectionalChangeExtension(0.1) is valid. Every invalid pair gives len(s) zeros, and an empty or nil receiver gives an empty result.
Units. theta and thetaDown are fractions: 0.05 means a 5% move. This differs on purpose from the older price-move thresholds in nseries, which take percentages: UpDown, UpDownString and UpDownSum (tolerance), and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The DirectionalChange family follows the directional-change literature (Chen & Tsang, Eq 2.1), where the threshold and the extension are fractions. DirectionalChangeExtension is therefore a fraction; DeltaPercent gives the same move multiplied by 100. The two conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. To use a percentage p, pass p/100. Go folds constant expressions exactly, so the constants 0.7/100 and 350.01 equal 0.007 and 0.35. The caveat is for p a float64 variable, where p/100 is computed at run time: for a whole-number percentage it equals the decimal literal (p = 5 gives 0.05), but for a fractional one it can differ from the literal in the last bit (p = 0.7 gives p/100 == 0.006999999999999999, not 0.007), and p0.01 can differ even for whole numbers (p = 35 gives p0.01 == 0.35000000000000003). Write the fraction literal (0.007) when a rule is stated in decimals. Because the tests are strict and exact, a one-bit difference in theta can move a confirmation that lands exactly on the threshold. For the same reason, a percentage test such as (p-LL)/LL100 > 7 is not the same test as (p-LL)/LL > 0.07: on [13.00, 13.91] the percentage test fires and the fraction test does not. For thresholds in points, see DirectionalChangePoints.
A threshold is crossed only when it is exceeded: a move exactly equal to its threshold does not confirm, so on [100, 110] at 0.1 nothing is confirmed, because (110 - 100)/100 is exactly the float64 0.1. To reproduce a source that counts equality as a crossing, pass math.Nextafter(theta, 0) and, for an asymmetric pair, math.Nextafter(thetaDown[0], 0): both tests use >, so both thresholds move towards 0, and a ratio exceeds math.Nextafter(x, 0) exactly when it is at least x, for every float64 ratio, because no float64 lies between a value and its neighbour. The one edge is a threshold of 5e-324, where math.Nextafter gives 0, which is invalid: pass 5e-324 unchanged, since no relative move between two distinct positive float64 prices is at most 5e-324, so both rules agree there.
The first valid index is 0 and the minimum length is 1. There is no warm-up: bar 0 of a valid series gives extension 0. The 0 before the first confirmation is the undetermined state, not a warm-up, and DirectionalChange(theta, thetaDown…).EQ(0) detects exactly the undetermined bars, where the extension is 0 or, on a missing bar, NaN.
A bar is missing when its price is not finite or is at most 0: a missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. The extension is NaN on a missing bar: a leading run of missing bars gives NaN until the first valid bar starts the machine, and an all-missing series gives NaN throughout. Deleting every missing bar from s gives the same extension bits on the remaining bars, and after a missing bar the machine carries on exactly as if the bar were absent.
The machine is a latch: it remembers its last confirmation, so it is not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars. On a 20,000-bar quarter-step random walk, runs started at 104 later bars agreed bit for bit with the full run, on the state, the extension and the age together, after a median of 14.5, 65.5 and 450.5 bars (maximum 58, 221 and 1062) at theta 0.01, 0.03 and 0.1, each within one confirmation of the full run.
The method is causal and deterministic: each output at bar t reads only s[0..t], every prefix of s gives the same first values bit for bit, and nothing is revised. Each confirmation is stamped at the bar whose price completes the move, and its extreme lies in the past, so the output lags each turn by the confirmation delay.
The settings of the sources are documentation, not causal parameters, and DirectionalChange gives their calls: Chen and Tsang (2021) use thresholds from 0.001 to 0.01 on intraday FX and 0.003 (and 0.004) for daily index tracking, inclusive; Vakkur (1997) uses 0.10 on monthly S&P 500 closes, which the caller supplies, his spreadsheet strict and his prose inclusive; Merrill (1988) uses 0.05 for market averages and 0.10 for stocks, from the low point, “5% or more”; Dai, Zhang and Zhu use 0.24 up (inclusive) and 0.19 down (strict), and their segment tables are full-sample; Raftopoulos (2003) uses 0.10 to 0.18, inclusive. The machine is not a Markov model but a state source for one, and no trading edge is demonstrated: Vakkur’s r^2 of 0.084 is in-sample, and Chen and Tsang score their tracking against labels drawn with hindsight.
The cost is one pass, O(1) per bar, and the method allocates only the result: one allocation per call whatever the length and whether the thresholds are valid, and none for an empty receiver.
Recipes built on the DirectionalChange methods are listed under “Compositions” in the “Regime Detection” category. Vakkur’s extendedness strata under “Markov Models” read it in fractions of the price.
Verification: on finite positive data, at every bar t where the state is not 0, with k the age at t, the extension times 100 equals s.DeltaPercent(k)[t] bit for bit, the extension equals s.Momentum(k)[t] divided by s[t-k] bit for bit, and the extension times 100 agrees with s.RateOfChange(k)[t], which forms (p/ref - 1)100, to rounding, within 1002^-50*(1 + |ext|). All four outputs also agree bit for bit with two independent references and with the published examples of Chen and Tsang (their Fig 2.1 and Fig 5.2).
DirectionalChangePoints
func (s Series) DirectionalChangePoints(h float64, hDown ...float64) Series
DirectionalChangePoints returns the directional-change state with thresholds in the receiver’s own units: +1 in a confirmed upward run, -1 in a confirmed downward run and 0 before the first confirmation.
The machine is the directional change of DirectionalChange, after Chen and Tsang (2021), Eq 2.1 and Appendix A, with its ratio tests replaced by differences, so that the thresholds are absolute moves in the receiver’s units rather than fractions. Here up is h, and down is hDown[0] when hDown has at least one element, else h: only hDown[0] is read, and further elements are ignored whatever their values. Before the first confirmation the machine tracks both the running high LH and the running low LL from the first valid bar; in an upward run it tracks only LH, and in a downward run only LL. On each later valid bar with value p the extremes extend first, a tie moving the extreme and its bar to the latest bar; then a downward run is confirmed when (LH - p) > down, and otherwise an upward run when (p - LL) > up. The extreme the move was measured from (the peak for a downward run, the trough for an upward run) becomes the last confirmed extreme ref, at bar iRef, and the other extreme restarts at the confirming bar. Each test is one subtraction, not a level such as LL + up, which can round differently: on [0.1, 0.30000000000000004] at h = 0.2 the difference 0.20000000000000004 exceeds h and confirms, while the level 0.1 + 0.2 equals the second value and would not. DirectionalChangePoints gives the state, DirectionalChangePointsExtension the extension p - ref and DirectionalChangePointsAge the age t - iRef; the confirmations themselves are DirectionalChangePoints(h, hDown…).Delta().Clamp(-1, 1).
The state is defined on every bar and is not NaN. It is +1 from a bar that confirms an upward run and -1 from a bar that confirms a downward run, held until the next confirmation, and 0 only before the first confirmation: once non-zero it is not 0 again. Before the first confirmation the down test comes first; with these thresholds the two tests cannot both hold on one bar, so the order is not observable and at most one confirmation fires on a bar.
The thresholds are valid if and only if 0 <= h < +Inf and 0 <= hDown < +Inf; NaN fails every comparison. A threshold of 0 is valid: any non-zero move then confirms, so the state is the sign of the last non-zero change and is 0 only while every valid value equals the first. An invalid hDown does not fall back to h: DirectionalChangePoints(1, -1) is invalid although DirectionalChangePoints(1) is valid, and an empty hDown is the same as none. Every invalid pair gives len(s) zeros, and an empty or nil receiver gives an empty result.
Units. h and hDown are in receiver units, the units of the series itself: points or pips on prices, log units on a log series, and the indicator’s own units on an oscillator or a spread. This is a third convention beside the fractions of the DirectionalChange family (0.05 means a 5% move) and the percentages of UpDown, UpDownString and UpDownSum (tolerance) and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. On a log series, h = ln(1+f) approximates the relative rule of DirectionalChange(f) but is not the same float test. Because the tests are strict and exact, a one-bit difference in h can move a confirmation that lands exactly on the threshold. Go folds constant expressions exactly, so the constant 360.0001 equals 0.0036, but a threshold computed at run time, such as a pip count p times a pip size, can differ from the literal in the last bit (p = 36 gives p0.0001 == 0.0036000000000000003, not 0.0036): write the literal when a rule states one. For a threshold series, see DirectionalChangePointsScaled.
A threshold is crossed only when it is exceeded: a move exactly equal to its threshold does not confirm, so on [100, 101] at h = 1 nothing is confirmed. To reproduce a source that counts equality as a crossing, pass math.Nextafter(h, math.Inf(-1)) and, for an asymmetric pair, math.Nextafter(hDown[0], math.Inf(-1)): both tests use >, so both thresholds move down, and a move exceeds math.Nextafter(x, math.Inf(-1)) exactly when it is at least x, for every float64 move, because no float64 lies between a value and its neighbour. At a threshold of 5e-324 the nudge gives 0, which is valid, and the recipe stays exact. There is no recipe at 0, where the nudge gives -5e-324, which is invalid; an inclusive test at 0 would confirm on every unchanged bar.
Zero and negative values are valid, so the method serves oscillators, spreads and differences as well as prices; only a value that is not finite is missing. An upstream warm-up of zeros is therefore read as data: mask it with SetN(F, math.NaN()), with F the input’s first valid index, before passing the series.
The first valid index is 0 and the minimum length is 1. There is no warm-up: bar 0 of a valid series gives state 0. The 0 before the first confirmation is the undetermined state, not a warm-up, and DirectionalChangePoints(h, hDown…).EQ(0) detects exactly the undetermined bars. Callers that feed the state to a latch, a rank or a state builder mask the 0 first.
A bar is missing when its value is not finite: a missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. On a missing bar the state is the previous bar’s state, which is 0 at bar 0 and before the first confirmation. Missing bars are invisible except to the clock: deleting every missing bar from s gives the same state on the remaining bars, and after a missing bar the machine carries on exactly as if the bar were absent.
A difference of two finite values of opposite signs near MaxFloat64 can overflow: (p - LL) or (LH - p) is then +Inf, which exceeds every valid threshold and confirms, and the extension is +Inf or -Inf.
The machine is a latch: it remembers its last confirmation, so it is not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars. On a 20,000-bar quarter-step random walk with values from 21.5 to 106.75, runs started at 104 later bars agreed bit for bit with the full run, on the state, the extension and the age together, after a median of 17, 75 and 568 bars (maximum 69, 251 and 1161) at h 1, 3 and 10.
The method is causal and deterministic: each output at bar t reads only s[0..t], every prefix of s gives the same first values bit for bit, and nothing is revised. Each confirmation is stamped at the bar whose value completes the move, and the extreme it confirms lies in the past, so the machine lags each turn by more than a threshold’s move.
The settings of the sources are documentation, not causal parameters. Poster (2020) measures directional changes on FX in pips, from the highest or lowest price of the zigzag segment, and words the rule as a move of more than the threshold, which is this method’s strict test with h the pip count times the pip size. Poster (2024) overlays a zigzag of 15 pips on EURUSD and finds 10 pips the best threshold for his whipsaw filter there; his listing reverses on a move of at least the threshold (>= and <=), 15 pips by default, which is DirectionalChangePoints(math.Nextafter(h, math.Inf(-1))). Raftopoulos (2003) offers a points mode beside his percent mode, inclusive as well (>= and <=), which is the same recipe with h his amount in points. Chen and Tsang (2021) define the machine with relative thresholds; the absolute form follows Poster.
DirectionalChangePoints is not a Markov model but a state source for one, and no trading edge is demonstrated: Poster fits his scaling laws to the whole sample.
DirectionalChange is the fraction family: the same machine with the ratio tests (LH - p)/LH > down and (p - LL)/LL > up, which needs positive prices and treats zero and negative values as missing bars. Hysteresis is a latch on a value’s level against two fixed thresholds, also in receiver units, not on a move from a running extreme. The swing views SwingHighValue, SwingLowValue, MarketStructure, ClearMethodDirection, GannSwingDirection, SwingTrend, WilliamsSwingDirection and BasingPointDirection build bar-count, Clear and basing-point swings; none of them confirms a swing by a threshold move, and they read infinities as ordered values where this method holds its state. PointAndFigureDirection is the same kind of latch on a grid: it reads highs and lows at the levels of a fixed box in receiver units and reverses on a whole number of boxes counted from the column’s extreme level, so its moves are quantised to the grid where this method’s are exact differences. KagiYang runs this machine step for step with one reversal amount as both thresholds and adds the kagi chart’s thickness latch: +1 once a rising line passes the latest shoulder, -1 once a falling line passes the latest waist, held between such breaks, and the first line sets it to its own direction.
The cost is one pass, O(1) per bar, and the method allocates only the result: one allocation per call whatever the length and whether the thresholds are valid, and none for an empty receiver.
Recipes built on the DirectionalChangePoints methods are listed under “Compositions” in the “Regime Detection” and “Kagi” categories.
Verification: all three outputs agree bit for bit with two independent references, one transcribed from the steps above and one written from the absolute-threshold formulation of the directional change. On finite data, with uo the ConsecUpOrEqual and do the ConsecDownOrEqual of s, DirectionalChangePoints(0) equals uo.GT(do).Sub(uo.LT(do)) bit for bit; when up is below every one-bar rise s[t] - s[t-1] and down below every one-bar fall s[t-1] - s[t], the state is the forward-filled sign of s.Momentum(1), and 0 before the first non-zero move; at a confirmation bar t with age k, and with p here the previous event bar (the first valid bar for the first event), the confirmed extreme s[t-k] is s.Highest(t-p+1)[t] for a -1 event and s.Lowest(t-p+1)[t] for a +1 event; negating s negates the state and swaps h and hDown; and on the base-2 exponents a of a series of powers of two 2^a the state at (h, hDown) = (u, d), whole numbers from 1 to 53, equals DirectionalChange(2^u - 1, 1 - 2^-d) on the series itself.
DirectionalChangePointsAge
func (s Series) DirectionalChangePointsAge(h float64, hDown ...float64) Series
DirectionalChangePointsAge returns the number of bars since the last confirmed extreme of DirectionalChangePoints.
The machine is the directional change of DirectionalChange, after Chen and Tsang (2021), Eq 2.1 and Appendix A, with its ratio tests replaced by differences, so that the thresholds are absolute moves in the receiver’s units rather than fractions. Here up is h, and down is hDown[0] when hDown has at least one element, else h: only hDown[0] is read, and further elements are ignored whatever their values. Before the first confirmation the machine tracks both the running high LH and the running low LL from the first valid bar; in an upward run it tracks only LH, and in a downward run only LL. On each later valid bar with value p the extremes extend first, a tie moving the extreme and its bar to the latest bar; then a downward run is confirmed when (LH - p) > down, and otherwise an upward run when (p - LL) > up. The extreme the move was measured from (the peak for a downward run, the trough for an upward run) becomes the last confirmed extreme ref, at bar iRef, and the other extreme restarts at the confirming bar. Each test is one subtraction, not a level such as LL + up, which can round differently: on [0.1, 0.30000000000000004] at h = 0.2 the difference 0.20000000000000004 exceeds h and confirms, while the level 0.1 + 0.2 equals the second value and would not. DirectionalChangePoints gives the state, DirectionalChangePointsExtension the extension p - ref and DirectionalChangePointsAge the age t - iRef; the confirmations themselves are DirectionalChangePoints(h, hDown…).Delta().Clamp(-1, 1).
The age at bar t is t - iRef, counted in bars. It is a whole number, 0 before the first confirmation and at least 1 (and at most t) wherever the state is not 0. On a confirmation bar it is the distance back to the extreme just confirmed, which by the tie rule is the latest bar holding that extreme value since the previous confirmation. It is a bar-index difference, so it counts missing bars, and it is not NaN. StateAge of the state counts from the confirmation bar, not from the extreme.
The thresholds are valid if and only if 0 <= h < +Inf and 0 <= hDown < +Inf; NaN fails every comparison. A threshold of 0 is valid: any non-zero move then confirms, so the state is the sign of the last non-zero change and is 0 only while every valid value equals the first. An invalid hDown does not fall back to h: DirectionalChangePointsAge(1, -1) is invalid although DirectionalChangePointsAge(1) is valid, and an empty hDown is the same as none. Every invalid pair gives len(s) zeros, and an empty or nil receiver gives an empty result.
Units. h and hDown are in receiver units, the units of the series itself: points or pips on prices, log units on a log series, and the indicator’s own units on an oscillator or a spread. This is a third convention beside the fractions of the DirectionalChange family (0.05 means a 5% move) and the percentages of UpDown, UpDownString and UpDownSum (tolerance) and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. On a log series, h = ln(1+f) approximates the relative rule of DirectionalChange(f) but is not the same float test. Because the tests are strict and exact, a one-bit difference in h can move a confirmation that lands exactly on the threshold. Go folds constant expressions exactly, so the constant 360.0001 equals 0.0036, but a threshold computed at run time, such as a pip count p times a pip size, can differ from the literal in the last bit (p = 36 gives p0.0001 == 0.0036000000000000003, not 0.0036): write the literal when a rule states one. For a threshold series, see DirectionalChangePointsScaled.
A threshold is crossed only when it is exceeded: a move exactly equal to its threshold does not confirm, so on [100, 101] at h = 1 nothing is confirmed. To reproduce a source that counts equality as a crossing, pass math.Nextafter(h, math.Inf(-1)) and, for an asymmetric pair, math.Nextafter(hDown[0], math.Inf(-1)): both tests use >, so both thresholds move down, and a move exceeds math.Nextafter(x, math.Inf(-1)) exactly when it is at least x, for every float64 move, because no float64 lies between a value and its neighbour. At a threshold of 5e-324 the nudge gives 0, which is valid, and the recipe stays exact. There is no recipe at 0, where the nudge gives -5e-324, which is invalid; an inclusive test at 0 would confirm on every unchanged bar.
Zero and negative values are valid, so the method serves oscillators, spreads and differences as well as prices; only a value that is not finite is missing. An upstream warm-up of zeros is therefore read as data: mask it with SetN(F, math.NaN()), with F the input’s first valid index, before passing the series.
The first valid index is 0 and the minimum length is 1. There is no warm-up: bar 0 of a valid series gives age 0. The 0 before the first confirmation is the undetermined state, not a warm-up, and DirectionalChangePoints(h, hDown…).EQ(0) detects exactly the undetermined bars. Callers that feed the state to a latch, a rank or a state builder mask the 0 first.
A bar is missing when its value is not finite: a missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. On a missing bar the age is the previous bar’s age plus 1 when the state is not 0, and 0 otherwise. Deleting every missing bar from s changes the age only by the missing bars it counts: with them present, the age is the bar-index distance to the same extreme bar.
The machine is a latch: it remembers its last confirmation, so it is not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars. On a 20,000-bar quarter-step random walk with values from 21.5 to 106.75, runs started at 104 later bars agreed bit for bit with the full run, on the state, the extension and the age together, after a median of 17, 75 and 568 bars (maximum 69, 251 and 1161) at h 1, 3 and 10.
The method is causal and deterministic: each output at bar t reads only s[0..t], every prefix of s gives the same first values bit for bit, and nothing is revised. Each confirmation is stamped at the bar whose value completes the move, and the extreme it confirms lies in the past, so the machine lags each turn by more than a threshold’s move.
The settings of the sources are documentation, not causal parameters, and DirectionalChangePoints gives their calls: Poster (2020) words his pip rule as strict, and the listing of Poster (2024) is inclusive (>= and <=), 15 pips by default on EURUSD; Raftopoulos (2003) offers an inclusive points mode. The machine is not a Markov model but a state source for one, and no trading edge is demonstrated: Poster fits his scaling laws to the whole sample.
The cost is one pass, O(1) per bar, and the method allocates only the result: one allocation per call whatever the length and whether the thresholds are valid, and none for an empty receiver.
Recipes built on the DirectionalChangePoints methods are listed under “Compositions” in the “Regime Detection” and “Kagi” categories.
Verification: on finite data, at a confirmation bar t with age k, and with p here the previous event bar (the first valid bar for the first event), k equals (t-p) - s.IndexOfHighestS(t-p+1)[t] for a -1 event and (t-p) - s.IndexOfLowestS(t-p+1)[t] for a +1 event; this needs the rule that a tie moves the extreme to the latest bar, and a first-occurrence rule fails it. All three outputs also agree bit for bit with two independent references.
DirectionalChangePointsAgeScaled
func (s Series) DirectionalChangePointsAgeScaled(h Series, hDown ...Series) Series
DirectionalChangePointsAgeScaled returns the number of bars since the last confirmed extreme of DirectionalChangePointsScaled.
The machine is that of DirectionalChangePoints, the directional change of Chen and Tsang (2021), Eq 2.1 and Appendix A, with difference tests in the receiver’s units, and Scaled means that its thresholds are series read bar by bar: bar t tests its up move against its own up_t, the bar of h aligned with it, and its down move against its own down_t, the aligned bar of hDown[0] when hDown has at least one element, else of h. Only hDown[0] is read, and further elements are ignored whatever their values and lengths. Before the first confirmation the machine tracks both the running high LH and the running low LL from the first valid bar; in an upward run it tracks only LH, and in a downward run only LL. On each later valid bar t with value p the extremes extend first, a tie moving the extreme and its bar to the latest bar; then a downward run is confirmed when (LH - p) > down_t, and otherwise an upward run when (p - LL) > up_t. The extreme the move was measured from (the peak for a downward run, the trough for an upward run) becomes the last confirmed extreme ref, at bar iRef, and the other extreme restarts at the confirming bar. Each test is one subtraction compared with the bar’s own threshold, not a level such as LL + up_t, which can round differently. DirectionalChangePointsScaled gives the state, DirectionalChangePointsExtensionScaled the extension p - ref and DirectionalChangePointsAgeScaled the age t - iRef; the confirmations themselves are DirectionalChangePointsScaled(h, hDown…).Delta().Clamp(-1, 1).
The age at bar t is t - iRef, counted in bars of s. It is a whole number, 0 before the first confirmation and on the bars before the overlap, and at least 1 (and at most t - off) wherever the state is not 0. On a confirmation bar it is the distance back to the extreme just confirmed, which by the tie rule is the latest bar holding that extreme value since the previous confirmation. It is a bar-index difference, so it counts missing bars, those missing for their thresholds included, and it is not NaN. StateAge of the state counts from the confirmation bar, not from the extreme.
h and hDown[0] are right-aligned with s at their most recent bar. With m the minimum overlap, min(len(s), len(h)), or min(len(s), len(h), len(hDown[0])) when hDown is supplied, and off = len(s) - m, bar t of s from off on is paired with the bar of h and of hDown[0] at the same distance from their last bars, so a longer threshold series loses its oldest bars. The result has len(s), and the off bars before the overlap are 0 on every output, the extension included: they are not missing bars, and the machine has not started. The machine starts at the first valid bar at or after off. An empty h, or an empty hDown[0], leaves no overlap and gives len(s) zeros; an empty hDown, with no element, is the same as none; an empty or nil receiver gives an empty result. MarketStructure and the other swing views that take a second series return an empty Series when the lengths differ; this method right-aligns, as Add does.
A bar’s thresholds are valid if and only if 0 <= up_t < +Inf and 0 <= down_t < +Inf; NaN fails every comparison. A threshold of 0 is valid, and -0 behaves as 0: any non-zero move against the run, or in either direction before the first confirmation, then confirms on that bar. A bar is missing when its value s[t] is not finite or its thresholds are not valid, so a threshold that is NaN, infinite or negative on one bar makes that one bar missing and leaves the rest of the run alone, where an invalid constant threshold gives DirectionalChangePointsAge len(s) zeros. There is no fallback: when hDown is supplied, an invalid down_t makes bar t missing even where h is valid there.
Units. h and hDown are in receiver units, the units of the series itself: points or pips on prices, log units on a log series, and the indicator’s own units on an oscillator or a spread. This is a third convention beside the fractions of the DirectionalChange family (0.05 means a 5% move) and the percentages of UpDown, UpDownString and UpDownSum (tolerance) and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. A threshold series built from other series is in their units, so build it from the receiver’s own bars: an average true range of the same highs, lows and closes is in the closes’ units. Because the tests are strict and exact, a one-bit difference in a threshold can move a confirmation that lands exactly on it.
A threshold is crossed only when it is exceeded: a move exactly equal to its bar’s threshold does not confirm, so on [100, 101] with h = [1, 1] nothing is confirmed. To reproduce a source that counts equality as a crossing, nudge every positive finite threshold down by one float64 and leave the others alone, with h.Map(func(x float64) float64 { if x > 0 && x < math.Inf(1) { return math.Nextafter(x, math.Inf(-1)) }; return x }) and the same map on hDown[0]: both tests use >, and a move exceeds math.Nextafter(x, math.Inf(-1)) exactly when it is at least x, for every float64 move, because no float64 lies between a value and its neighbour. The guard keeps a bad bar bad, since math.Nextafter(+Inf, math.Inf(-1)) is MaxFloat64, a valid threshold, and it leaves a threshold of 0 strict: there is no recipe at 0, where the nudge gives -5e-324, which is invalid, and an inclusive test at 0 would confirm on every unchanged bar. At a threshold of 5e-324 the nudge gives 0, which is valid, and the recipe stays exact.
Bar t is compared with its own threshold as supplied; to commit each threshold before its bar, pass h.Shift(1).SetN(1, math.NaN()), as DirectionalChangePointsScaled describes, with its average-true-range form.
Zero and negative values of s are valid, so the method serves oscillators, spreads and differences as well as prices, and an upstream warm-up of zeros is read as data: mask it with SetN(F, math.NaN()), with F the input’s first valid index, before passing the series. A threshold warm-up of zeros is valid too, a 0 meaning that any move confirms, so mask a threshold series’ warm-up the same way: its bars are then missing, and the machine starts at the first bar with a valid threshold.
The first valid index is 0, counted from the start of the overlap, and the minimum overlap is 1. There is no warm-up: the first bar of the overlap gives age 0. The 0 before the first confirmation is the undetermined state, not a warm-up, and DirectionalChangePointsScaled(h, hDown…).EQ(0) detects exactly the undetermined bars and the bars before the overlap, which are the bars where the age is 0. Callers that feed the state to a latch, a rank or a state builder mask these bars first.
A missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. On a missing bar the age is the previous bar’s age plus 1 when the state is not 0, and 0 otherwise. Deleting every missing bar from the aligned s, h and hDown[0] together changes the age only by the missing bars it counts: with them present, the age is the bar-index distance to the same extreme bar.
The machine is a latch: it remembers its last confirmation, so it is not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars; with a constant threshold series the settling lengths are those that DirectionalChangePoints gives.
The method is causal and deterministic: each output at bar t reads only the bars of s, h and hDown[0] up to bar t as aligned, cutting the same number of bars from the end of every input gives the same first values bit for bit, and nothing is revised. Each confirmation is stamped at the bar whose value completes the move, and the extreme it confirms lies in the past, so the machine lags each turn by more than a threshold’s move.
The settings of the source are documentation, not causal parameters, and DirectionalChangePointsScaled gives Raschke’s average-true-range filter, illustrated on charts only. The machine is not a Markov model but a state source for one, and no trading edge is demonstrated.
The cost is one pass, O(1) per bar, and the method allocates only the result: one allocation per call whatever the lengths and thresholds, and none for an empty receiver.
Recipes built on the DirectionalChangePointsScaled methods are listed under “Compositions” in the “Regime Detection” category.
Verification: on finite data with valid thresholds, at a confirmation bar t with age k, and with p here the previous event bar (the first bar of the overlap for the first event), k equals (t-p) - s.IndexOfHighestS(t-p+1)[t] for a -1 event and (t-p) - s.IndexOfLowestS(t-p+1)[t] for a +1 event, which needs the rule that a tie moves the extreme to the latest bar; when every bar of h is the valid value x, and every bar of hDown[0], if supplied, the valid value y, the age equals DirectionalChangePointsAge(x, y) bit for bit on the overlap. All three outputs also agree bit for bit with two independent references.
DirectionalChangePointsExtension
func (s Series) DirectionalChangePointsExtension(h float64, hDown ...float64) Series
DirectionalChangePointsExtension returns the signed move of each bar from the last confirmed extreme of DirectionalChangePoints, in the receiver’s units.
The machine is the directional change of DirectionalChange, after Chen and Tsang (2021), Eq 2.1 and Appendix A, with its ratio tests replaced by differences, so that the thresholds are absolute moves in the receiver’s units rather than fractions. Here up is h, and down is hDown[0] when hDown has at least one element, else h: only hDown[0] is read, and further elements are ignored whatever their values. Before the first confirmation the machine tracks both the running high LH and the running low LL from the first valid bar; in an upward run it tracks only LH, and in a downward run only LL. On each later valid bar with value p the extremes extend first, a tie moving the extreme and its bar to the latest bar; then a downward run is confirmed when (LH - p) > down, and otherwise an upward run when (p - LL) > up. The extreme the move was measured from (the peak for a downward run, the trough for an upward run) becomes the last confirmed extreme ref, at bar iRef, and the other extreme restarts at the confirming bar. Each test is one subtraction, not a level such as LL + up, which can round differently: on [0.1, 0.30000000000000004] at h = 0.2 the difference 0.20000000000000004 exceeds h and confirms, while the level 0.1 + 0.2 equals the second value and would not. DirectionalChangePoints gives the state, DirectionalChangePointsExtension the extension p - ref and DirectionalChangePointsAge the age t - iRef; the confirmations themselves are DirectionalChangePoints(h, hDown…).Delta().Clamp(-1, 1).
The extension at a valid bar with value p is p - ref, one subtraction, in the receiver’s units: positive above ref and negative below it. It is the test’s own shape, so on a confirmation bar it equals the test’s own value, above up on a +1 confirmation and below -down on a -1 confirmation, exactly, because a rounded difference changes sign with its operands, and it is -0 when p is -0 and ref is +0. It is +Inf or -Inf when the difference overflows. It is 0 on valid bars before the first confirmation, and NaN on a missing bar and only there.
The thresholds are valid if and only if 0 <= h < +Inf and 0 <= hDown < +Inf; NaN fails every comparison. A threshold of 0 is valid: any non-zero move then confirms, so the state is the sign of the last non-zero change and is 0 only while every valid value equals the first. An invalid hDown does not fall back to h: DirectionalChangePointsExtension(1, -1) is invalid although DirectionalChangePointsExtension(1) is valid, and an empty hDown is the same as none. Every invalid pair gives len(s) zeros, and an empty or nil receiver gives an empty result.
Units. h and hDown are in receiver units, the units of the series itself: points or pips on prices, log units on a log series, and the indicator’s own units on an oscillator or a spread. This is a third convention beside the fractions of the DirectionalChange family (0.05 means a 5% move) and the percentages of UpDown, UpDownString and UpDownSum (tolerance) and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. On a log series, h = ln(1+f) approximates the relative rule of DirectionalChange(f) but is not the same float test. Because the tests are strict and exact, a one-bit difference in h can move a confirmation that lands exactly on the threshold. Go folds constant expressions exactly, so the constant 360.0001 equals 0.0036, but a threshold computed at run time, such as a pip count p times a pip size, can differ from the literal in the last bit (p = 36 gives p0.0001 == 0.0036000000000000003, not 0.0036): write the literal when a rule states one. For a threshold series, see DirectionalChangePointsScaled.
A threshold is crossed only when it is exceeded: a move exactly equal to its threshold does not confirm, so on [100, 101] at h = 1 nothing is confirmed. To reproduce a source that counts equality as a crossing, pass math.Nextafter(h, math.Inf(-1)) and, for an asymmetric pair, math.Nextafter(hDown[0], math.Inf(-1)): both tests use >, so both thresholds move down, and a move exceeds math.Nextafter(x, math.Inf(-1)) exactly when it is at least x, for every float64 move, because no float64 lies between a value and its neighbour. At a threshold of 5e-324 the nudge gives 0, which is valid, and the recipe stays exact. There is no recipe at 0, where the nudge gives -5e-324, which is invalid; an inclusive test at 0 would confirm on every unchanged bar.
Zero and negative values are valid, so the method serves oscillators, spreads and differences as well as prices; only a value that is not finite is missing. An upstream warm-up of zeros is therefore read as data: mask it with SetN(F, math.NaN()), with F the input’s first valid index, before passing the series.
The first valid index is 0 and the minimum length is 1. There is no warm-up: bar 0 of a valid series gives extension 0. The 0 before the first confirmation is the undetermined state, not a warm-up, and DirectionalChangePoints(h, hDown…).EQ(0) detects exactly the undetermined bars. Callers that feed the state to a latch, a rank or a state builder mask the 0 first.
A bar is missing when its value is not finite: a missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. The extension is NaN on a missing bar: a leading run of missing bars gives NaN until the first valid bar starts the machine, and an all-missing series gives NaN throughout. Deleting every missing bar from s gives the same extension bits on the remaining bars.
The machine is a latch: it remembers its last confirmation, so it is not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars. On a 20,000-bar quarter-step random walk with values from 21.5 to 106.75, runs started at 104 later bars agreed bit for bit with the full run, on the state, the extension and the age together, after a median of 17, 75 and 568 bars (maximum 69, 251 and 1161) at h 1, 3 and 10.
The method is causal and deterministic: each output at bar t reads only s[0..t], every prefix of s gives the same first values bit for bit, and nothing is revised. Each confirmation is stamped at the bar whose value completes the move, and the extreme it confirms lies in the past, so the machine lags each turn by more than a threshold’s move.
The settings of the sources are documentation, not causal parameters, and DirectionalChangePoints gives their calls: Poster (2020) words his pip rule as strict, and the listing of Poster (2024) is inclusive (>= and <=), 15 pips by default on EURUSD; Raftopoulos (2003) offers an inclusive points mode. The machine is not a Markov model but a state source for one, and no trading edge is demonstrated: Poster fits his scaling laws to the whole sample.
The cost is one pass, O(1) per bar, and the method allocates only the result: one allocation per call whatever the length and whether the thresholds are valid, and none for an empty receiver.
Recipes built on the DirectionalChangePoints methods are listed under “Compositions” in the “Regime Detection” and “Kagi” categories.
Verification: on finite data, at every bar t where the state is not 0, with k the age at t, the extension equals s.Momentum(k)[t] bit for bit, the same subtraction; on the base-2 exponents a of a series of powers of two 2^a, at (h, hDown) = (u, d), whole numbers from 1 to 53, 2 raised to the extension, less 1, equals DirectionalChangeExtension(2^u - 1, 1 - 2^-d) wherever the extension is at most 52 in size. All three outputs also agree bit for bit with two independent references.
DirectionalChangePointsExtensionScaled
func (s Series) DirectionalChangePointsExtensionScaled(h Series, hDown ...Series) Series
DirectionalChangePointsExtensionScaled returns the signed move of each bar from the last confirmed extreme of DirectionalChangePointsScaled, in the receiver’s units.
The machine is that of DirectionalChangePoints, the directional change of Chen and Tsang (2021), Eq 2.1 and Appendix A, with difference tests in the receiver’s units, and Scaled means that its thresholds are series read bar by bar: bar t tests its up move against its own up_t, the bar of h aligned with it, and its down move against its own down_t, the aligned bar of hDown[0] when hDown has at least one element, else of h. Only hDown[0] is read, and further elements are ignored whatever their values and lengths. Before the first confirmation the machine tracks both the running high LH and the running low LL from the first valid bar; in an upward run it tracks only LH, and in a downward run only LL. On each later valid bar t with value p the extremes extend first, a tie moving the extreme and its bar to the latest bar; then a downward run is confirmed when (LH - p) > down_t, and otherwise an upward run when (p - LL) > up_t. The extreme the move was measured from (the peak for a downward run, the trough for an upward run) becomes the last confirmed extreme ref, at bar iRef, and the other extreme restarts at the confirming bar. Each test is one subtraction compared with the bar’s own threshold, not a level such as LL + up_t, which can round differently. DirectionalChangePointsScaled gives the state, DirectionalChangePointsExtensionScaled the extension p - ref and DirectionalChangePointsAgeScaled the age t - iRef; the confirmations themselves are DirectionalChangePointsScaled(h, hDown…).Delta().Clamp(-1, 1).
The extension at a valid bar with value p is p - ref, one subtraction, in the receiver’s units: positive above ref and negative below it. It is the test’s own shape, so on a confirmation bar it equals the test’s own value, above up_t on a +1 confirmation and below -down_t on a -1 confirmation, exactly, because a rounded difference changes sign with its operands, and it is -0 when p is -0 and ref is +0. It is +Inf or -Inf when the difference overflows. It is 0 on valid bars before the first confirmation and on the bars before the overlap, and NaN on a missing bar of the overlap and only there, whether the bar is missing for its value or for its thresholds.
h and hDown[0] are right-aligned with s at their most recent bar. With m the minimum overlap, min(len(s), len(h)), or min(len(s), len(h), len(hDown[0])) when hDown is supplied, and off = len(s) - m, bar t of s from off on is paired with the bar of h and of hDown[0] at the same distance from their last bars, so a longer threshold series loses its oldest bars. The result has len(s), and the off bars before the overlap are 0 on every output, the extension included: they are not missing bars, and the machine has not started. The machine starts at the first valid bar at or after off. An empty h, or an empty hDown[0], leaves no overlap and gives len(s) zeros; an empty hDown, with no element, is the same as none; an empty or nil receiver gives an empty result. MarketStructure and the other swing views that take a second series return an empty Series when the lengths differ; this method right-aligns, as Add does.
A bar’s thresholds are valid if and only if 0 <= up_t < +Inf and 0 <= down_t < +Inf; NaN fails every comparison. A threshold of 0 is valid, and -0 behaves as 0: any non-zero move against the run, or in either direction before the first confirmation, then confirms on that bar. A bar is missing when its value s[t] is not finite or its thresholds are not valid, so a threshold that is NaN, infinite or negative on one bar makes that one bar missing and leaves the rest of the run alone, where an invalid constant threshold gives DirectionalChangePointsExtension len(s) zeros. There is no fallback: when hDown is supplied, an invalid down_t makes bar t missing even where h is valid there.
Units. h and hDown are in receiver units, the units of the series itself: points or pips on prices, log units on a log series, and the indicator’s own units on an oscillator or a spread. This is a third convention beside the fractions of the DirectionalChange family (0.05 means a 5% move) and the percentages of UpDown, UpDownString and UpDownSum (tolerance) and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. A threshold series built from other series is in their units, so build it from the receiver’s own bars: an average true range of the same highs, lows and closes is in the closes’ units. Because the tests are strict and exact, a one-bit difference in a threshold can move a confirmation that lands exactly on it.
A threshold is crossed only when it is exceeded: a move exactly equal to its bar’s threshold does not confirm, so on [100, 101] with h = [1, 1] nothing is confirmed. To reproduce a source that counts equality as a crossing, nudge every positive finite threshold down by one float64 and leave the others alone, with h.Map(func(x float64) float64 { if x > 0 && x < math.Inf(1) { return math.Nextafter(x, math.Inf(-1)) }; return x }) and the same map on hDown[0]: both tests use >, and a move exceeds math.Nextafter(x, math.Inf(-1)) exactly when it is at least x, for every float64 move, because no float64 lies between a value and its neighbour. The guard keeps a bad bar bad, since math.Nextafter(+Inf, math.Inf(-1)) is MaxFloat64, a valid threshold, and it leaves a threshold of 0 strict: there is no recipe at 0, where the nudge gives -5e-324, which is invalid, and an inclusive test at 0 would confirm on every unchanged bar. At a threshold of 5e-324 the nudge gives 0, which is valid, and the recipe stays exact.
Bar t is compared with its own threshold as supplied; to commit each threshold before its bar, pass h.Shift(1).SetN(1, math.NaN()), as DirectionalChangePointsScaled describes, with its average-true-range form.
Zero and negative values of s are valid, so the method serves oscillators, spreads and differences as well as prices, and an upstream warm-up of zeros is read as data: mask it with SetN(F, math.NaN()), with F the input’s first valid index, before passing the series. A threshold warm-up of zeros is valid too, a 0 meaning that any move confirms, so mask a threshold series’ warm-up the same way: its bars are then missing, and the extension is NaN there.
The first valid index is 0, counted from the start of the overlap, and the minimum overlap is 1. There is no warm-up: the first bar of the overlap gives extension 0 when its bar is valid. The 0 before the first confirmation is the undetermined state, not a warm-up, and DirectionalChangePointsScaled(h, hDown…).EQ(0) detects exactly the undetermined bars and the bars before the overlap. Callers that feed the state to a latch, a rank or a state builder mask these bars first.
A missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. The extension is NaN on a missing bar: a leading run of missing bars gives NaN until the first valid bar starts the machine, and an overlap of missing bars gives NaN throughout it. Deleting every missing bar from the aligned s, h and hDown[0] together gives the same extension bits on the remaining bars.
The machine is a latch: it remembers its last confirmation, so it is not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars; with a constant threshold series the settling lengths are those that DirectionalChangePoints gives.
The method is causal and deterministic: each output at bar t reads only the bars of s, h and hDown[0] up to bar t as aligned, cutting the same number of bars from the end of every input gives the same first values bit for bit, and nothing is revised. Each confirmation is stamped at the bar whose value completes the move, and the extreme it confirms lies in the past, so the machine lags each turn by more than a threshold’s move.
The settings of the source are documentation, not causal parameters, and DirectionalChangePointsScaled gives Raschke’s average-true-range filter, illustrated on charts only. The machine is not a Markov model but a state source for one, and no trading edge is demonstrated.
The cost is one pass, O(1) per bar, and the method allocates only the result: one allocation per call whatever the lengths and thresholds, and none for an empty receiver.
Recipes built on the DirectionalChangePointsScaled methods are listed under “Compositions” in the “Regime Detection” category.
Verification: at every valid bar t of the overlap where the state is not 0, with k the age at t, the extension equals s.Momentum(k)[t] bit for bit, the same subtraction; when every bar of h is the valid value x, and every bar of hDown[0], if supplied, the valid value y, the extension equals DirectionalChangePointsExtension(x, y) bit for bit on the overlap. All three outputs also agree bit for bit with two independent references.
DirectionalChangePointsScaled
func (s Series) DirectionalChangePointsScaled(h Series, hDown ...Series) Series
DirectionalChangePointsScaled returns DirectionalChangePoints’s state with a threshold series h in the receiver’s units, compared bar by bar.
The state is +1 in a confirmed upward run, -1 in a confirmed downward run and 0 before the first confirmation. The machine is that of DirectionalChangePoints, the directional change of Chen and Tsang (2021), Eq 2.1 and Appendix A, with difference tests in the receiver’s units, and Scaled means that its thresholds are series read bar by bar: bar t tests its up move against its own up_t, the bar of h aligned with it, and its down move against its own down_t, the aligned bar of hDown[0] when hDown has at least one element, else of h. Only hDown[0] is read, and further elements are ignored whatever their values and lengths. Before the first confirmation the machine tracks both the running high LH and the running low LL from the first valid bar; in an upward run it tracks only LH, and in a downward run only LL. On each later valid bar t with value p the extremes extend first, a tie moving the extreme and its bar to the latest bar; then a downward run is confirmed when (LH - p) > down_t, and otherwise an upward run when (p - LL) > up_t. The extreme the move was measured from (the peak for a downward run, the trough for an upward run) becomes the last confirmed extreme ref, at bar iRef, and the other extreme restarts at the confirming bar. Each test is one subtraction compared with the bar’s own threshold, not a level such as LL + up_t, which can round differently. DirectionalChangePointsScaled gives the state, DirectionalChangePointsExtensionScaled the extension p - ref and DirectionalChangePointsAgeScaled the age t - iRef; the confirmations themselves are DirectionalChangePointsScaled(h, hDown…).Delta().Clamp(-1, 1).
The state is defined on every bar and is not NaN. It is +1 from a bar that confirms an upward run and -1 from a bar that confirms a downward run, held until the next confirmation, and 0 only before the first confirmation: once non-zero it is not 0 again. Before the first confirmation the down test comes first, and with thresholds that change from bar to bar both tests can hold on one bar: on [0, 10, 5] with h = [100, 100, 1] the fall of 5 and the rise of 5 both exceed 1 at bar 2, and the state is -1 there, measured from the high at bar 1. At most one confirmation fires on a bar.
h and hDown[0] are right-aligned with s at their most recent bar. With m the minimum overlap, min(len(s), len(h)), or min(len(s), len(h), len(hDown[0])) when hDown is supplied, and off = len(s) - m, bar t of s from off on is paired with the bar of h and of hDown[0] at the same distance from their last bars, so a longer threshold series loses its oldest bars. The result has len(s), and the off bars before the overlap are 0 on every output, the extension included: they are not missing bars, and the machine has not started. The machine starts at the first valid bar at or after off. An empty h, or an empty hDown[0], leaves no overlap and gives len(s) zeros; an empty hDown, with no element, is the same as none; an empty or nil receiver gives an empty result. MarketStructure and the other swing views that take a second series return an empty Series when the lengths differ; this method right-aligns, as Add does.
A bar’s thresholds are valid if and only if 0 <= up_t < +Inf and 0 <= down_t < +Inf; NaN fails every comparison. A threshold of 0 is valid, and -0 behaves as 0: any non-zero move against the run, or in either direction before the first confirmation, then confirms on that bar. A bar is missing when its value s[t] is not finite or its thresholds are not valid, so a threshold that is NaN, infinite or negative on one bar makes that one bar missing and leaves the rest of the run alone, where an invalid constant threshold gives DirectionalChangePoints len(s) zeros. There is no fallback: when hDown is supplied, an invalid down_t makes bar t missing even where h is valid there.
Units. h and hDown are in receiver units, the units of the series itself: points or pips on prices, log units on a log series, and the indicator’s own units on an oscillator or a spread. This is a third convention beside the fractions of the DirectionalChange family (0.05 means a 5% move) and the percentages of UpDown, UpDownString and UpDownSum (tolerance) and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. A threshold series built from other series is in their units, so build it from the receiver’s own bars: an average true range of the same highs, lows and closes is in the closes’ units. Because the tests are strict and exact, a one-bit difference in a threshold can move a confirmation that lands exactly on it.
A threshold is crossed only when it is exceeded: a move exactly equal to its bar’s threshold does not confirm, so on [100, 101] with h = [1, 1] nothing is confirmed. To reproduce a source that counts equality as a crossing, nudge every positive finite threshold down by one float64 and leave the others alone, with h.Map(func(x float64) float64 { if x > 0 && x < math.Inf(1) { return math.Nextafter(x, math.Inf(-1)) }; return x }) and the same map on hDown[0]: both tests use >, and a move exceeds math.Nextafter(x, math.Inf(-1)) exactly when it is at least x, for every float64 move, because no float64 lies between a value and its neighbour. The guard keeps a bad bar bad, since math.Nextafter(+Inf, math.Inf(-1)) is MaxFloat64, a valid threshold, and it leaves a threshold of 0 strict: there is no recipe at 0, where the nudge gives -5e-324, which is invalid, and an inclusive test at 0 would confirm on every unchanged bar. At a threshold of 5e-324 the nudge gives 0, which is valid, and the recipe stays exact.
Bar t is compared with its own threshold as supplied, so a threshold may use bar t’s own data: an average true range that includes bar t is causal, but it grows with the bar it tests. To commit each threshold before its bar, pass h.Shift(1).SetN(1, math.NaN()): Shift(1) moves each threshold one bar later and pads bar 0 with 0, a valid threshold, which SetN masks. Raschke (in Bensignor, 2000) draws swing charts with a volatility filter after Wilder: a new up wave when price rallies k times the 10-bar simple average of TrueRange above the swing low, with k from 2 to 3, and a new down wave when the close falls below the swing high by as much. With closes c, highs hi and lows lo, the pre-committed filter on closes is c.DirectionalChangePointsScaled(dist) with dist = c.ATR(hi, lo, c, n).Mul(k).Shift(1).SetN(n+1, math.NaN()) and n = 10. ATR passes TrueRange through on bars 0 to n-2, and its first average, at bar n-1, includes bar 0’s range hi[0] - lo[0], which has no previous close; the shift moves these to bars 1 to n, and SetN masks them with the shift’s 0 at bar 0, so the machine starts at bar n+1, the first bar whose threshold averages n true ranges that each have a previous close. This method reads one series, so both of Raschke’s tests run on closes; her up test on highs is not built here.
Zero and negative values of s are valid, so the method serves oscillators, spreads and differences as well as prices, and an upstream warm-up of zeros is read as data: mask it with SetN(F, math.NaN()), with F the input’s first valid index, before passing the series. A threshold warm-up of zeros is valid too, a 0 meaning that any move confirms, so mask a threshold series’ warm-up the same way: its bars are then missing, and the machine starts at the first bar with a valid threshold.
The first valid index is 0, counted from the start of the overlap, and the minimum overlap is 1. There is no warm-up: the first bar of the overlap gives state 0 whatever its value and thresholds. The 0 before the first confirmation is the undetermined state, not a warm-up, and DirectionalChangePointsScaled(h, hDown…).EQ(0) detects exactly the undetermined bars and the bars before the overlap. Callers that feed the state to a latch, a rank or a state builder mask these bars first.
A missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. On a missing bar the state is the previous bar’s state, which is 0 before the first confirmation. Missing bars are invisible except to the clock: deleting every missing bar from the aligned s, h and hDown[0] together gives the same state on the remaining bars, and after a missing bar the machine carries on exactly as if the bar were absent.
A difference of two finite values of opposite signs near MaxFloat64 can overflow: (p - LL) or (LH - p) is then +Inf, which exceeds every valid threshold and confirms, and the extension is +Inf or -Inf.
The machine is a latch: it remembers its last confirmation, so it is not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars; with a constant threshold series the settling lengths are those that DirectionalChangePoints gives.
The method is causal and deterministic: each output at bar t reads only the bars of s, h and hDown[0] up to bar t as aligned, cutting the same number of bars from the end of every input gives the same first values bit for bit, and nothing is revised. Each confirmation is stamped at the bar whose value completes the move, and the extreme it confirms lies in the past, so the machine lags each turn by more than a threshold’s move.
The settings of the source are documentation, not causal parameters: Raschke’s ten bars and k from 2 to 3 are illustrated on charts only. The machine is not a Markov model but a state source for one, and no trading edge is demonstrated.
DirectionalChangePoints is this machine with constant thresholds: when every bar of h is the valid value x, and every bar of hDown[0], if supplied, the valid value y, the three outputs equal those of DirectionalChangePoints(x, y) on the overlap bit for bit. An invalid constant differs: DirectionalChangePoints gives len(s) zeros, while here every bar is missing, so the extension is NaN on the overlap. DirectionalChange is the fraction family: its moves are fractions of the running extreme, which is not known when a threshold series is formed, so it is not this method with any threshold series. Hysteresis is a latch on a value’s level against two fixed thresholds, not on a move from a running extreme. The swing views SwingHighValue, SwingLowValue, MarketStructure, ClearMethodDirection, GannSwingDirection, SwingTrend, WilliamsSwingDirection and BasingPointDirection build bar-count, Clear and basing-point swings; none of them confirms a swing by a threshold move, and they read infinities as ordered values where this method holds its state.
The cost is one pass, O(1) per bar, and the method allocates only the result: one allocation per call whatever the lengths and thresholds, and none for an empty receiver.
Recipes built on the DirectionalChangePointsScaled methods are listed under “Compositions” in the “Regime Detection” category. The jump override of Meyers’s percentage reversal, run on the log of a regression forecast curve, is under “Linear Regression”.
Verification: when every bar of h is the valid value x, and every bar of hDown[0], if supplied, the valid value y, the state equals DirectionalChangePoints(x, y) bit for bit on the overlap; on finite data as long as h, with every threshold valid and below every non-zero one-bar move |s[t] - s[t-1]|, the state is the forward-filled sign of s.Momentum(1), and 0 before the first non-zero move; a threshold that is invalid on bar t gives the outputs of a valid threshold there with s[t] replaced by NaN. All three outputs also agree bit for bit with two independent references.
DirectionalChangeTMV
func (s Series) DirectionalChangeTMV(theta float64, thetaDown ...float64) Series
DirectionalChangeTMV returns the total move of the last finished directional-change trend, its extreme-to-extreme relative price move divided by the threshold of its own direction, stamped at the bar that confirms its end.
The machine is that of DirectionalChange: the directional change of Chen and Tsang (2021), Eq 2.1 and Appendix A, with a strict tie rule. Here up is theta, and down is thetaDown[0] when thetaDown has at least one element, else theta: only thetaDown[0] is read, and further elements are ignored. A trend runs from one confirmed extreme to the next. At each confirmation bar t from the second on, the trend that has just finished runs from the previous confirmed extreme b, at bar ib, to the extreme a, at bar ia, that the confirmation at t confirms, with ib < ia < t, and DirectionalChangeAge is t - ia at t. Its move is |a - b|/b, one subtraction, an absolute value and one division, and its threshold thetaDir is that of its own direction: up for a rising trend, which ends at a peak and is stamped at a -1 confirmation, and down for a falling one, stamped at a +1 confirmation. Chen and Tsang use one threshold; normalising each trend by the threshold of its own direction is this library’s extension. The TMV is move/thetaDir, Chen and Tsang’s Eq 4.1 with the trend’s own threshold. Their Eq 2.2 writes |a - b|/(b*theta), the same quantity in exact arithmetic; in floating point the two can differ in the last bits, so it is not the form used. Normalising a falling trend by theta instead of down can put it below 1 when down is below up: on [100, 126, 123.75, 160] at (0.25, 0.01) it would give 0.07142857142857142 at bar 3, where the TMV is 1.7857142857142856.
At every emission the TMV is above 1: the confirmation that began the trend found a move above thetaDir, and a is at least as extreme as that bar’s price. It is unsigned and not NaN. The finished trend runs opposite to the current DirectionalChange state: a rising trend is stamped when a -1 confirmation sets the state to -1. The TMV is +Inf when move/thetaDir overflows, as at theta 1e-310 on [100, 101, 99, 101], where it is 1.000000000000003e+308 at bar 2 and +Inf at bar 3, and when the ratio of the two extreme prices exceeds about 1.8e308, as on [1, 1e-300, 1e10, 1] at 0.5, where it is +Inf at bar 3.
The thresholds are valid if and only if 0 < up < +Inf and 0 < down < 1; NaN fails every comparison. An invalid thetaDown does not fall back to theta: DirectionalChangeTMV(0.1, 1) is invalid although DirectionalChangeTMV(0.1) is valid. Every invalid pair gives len(s) zeros, and an empty or nil receiver gives an empty result.
Units. theta and thetaDown are fractions: 0.05 means a 5% move. This differs on purpose from the older price-move thresholds in nseries, which take percentages: UpDown, UpDownString and UpDownSum (tolerance), and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The DirectionalChange family follows the directional-change literature (Chen & Tsang, Eq 2.1), where the threshold and the extension are fractions. DirectionalChangeExtension is therefore a fraction; DeltaPercent gives the same move multiplied by 100. The two conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. To use a percentage p, pass p/100. Go folds constant expressions exactly, so the constants 0.7/100 and 350.01 equal 0.007 and 0.35. The caveat is for p a float64 variable, where p/100 is computed at run time: for a whole-number percentage it equals the decimal literal (p = 5 gives 0.05), but for a fractional one it can differ from the literal in the last bit (p = 0.7 gives p/100 == 0.006999999999999999, not 0.007), and p0.01 can differ even for whole numbers (p = 35 gives p0.01 == 0.35000000000000003). Write the fraction literal (0.007) when a rule is stated in decimals. Because the tests are strict and exact, a one-bit difference in theta can move a confirmation that lands exactly on the threshold. For the same reason, a percentage test such as (p-LL)/LL100 > 7 is not the same test as (p-LL)/LL > 0.07: on [13.00, 13.91] the percentage test fires and the fraction test does not. For thresholds in points, see DirectionalChangePoints. The TMV is dimensionless, a multiple of the trend’s threshold; the speed is a fraction per bar, and the trend length T is in bars.
A threshold is crossed only when it is exceeded: a move exactly equal to its threshold does not confirm, so on [100, 110] at 0.1 nothing is confirmed, because (110 - 100)/100 is exactly the float64 0.1. To reproduce a source that counts equality as a crossing, pass math.Nextafter(theta, 0) and, for an asymmetric pair, math.Nextafter(thetaDown[0], 0): both tests use >, so both thresholds move towards 0, and a ratio exceeds math.Nextafter(x, 0) exactly when it is at least x, for every float64 ratio, because no float64 lies between a value and its neighbour. The one edge is a threshold of 5e-324, where math.Nextafter gives 0, which is invalid: pass 5e-324 unchanged, since no relative move between two distinct positive float64 prices is at most 5e-324, so both rules agree there. With the nudged thresholds the three methods give the inclusive machine’s events, trend lengths and speeds bit for bit, but the TMV is then divided by the nudged threshold, so it can exceed the literal inclusive value by one or two bit steps: on [21, 20, 21, 22, 23, 21] at 0.05 the nudged call gives 3 at bar 5, where the literal value is 2.9999999999999996, and on the AAPL daily prices of 2023 at 0.003 the two differ on 164 of the 200 bars. The literal value is DirectionalChangeExtension(math.Nextafter(theta, 0)).Abs().Div(theta) at the extreme bar ia.
The first valid index is the second confirmation bar, and the minimum length is 3: a trend needs two confirmed extremes, and its end is known only at the next confirmation. The three outputs are 0 before the second confirmation. The warm-up reads 0, not NaN: no emission is 0, because the TMV is above 1, T is at least 1 and the speed is above 0, so DirectionalChangeTrendBars(theta).GT(0), with the same thetaDown, detects exactly the bars from the first emission on. The first emitted trend is left-censored: it starts at the extreme reached since the first valid bar, so its values depend on where the series starts. On the AAPL daily prices of 2023 at 0.003, starting 1 to 59 bars later changed the first emission in 33 of the 59 starts and no later emission; that is a measurement on one series, not a guarantee.
A bar is missing when its price is not finite or is at most 0: a missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. The three outputs hold their values on a missing bar and are not NaN there, because they read the confirmed extremes and not the current price, and leading missing bars give 0. T counts the missing bars inside a trend, so deleting the missing bars from s leaves the TMV unchanged on the remaining bars and can shorten T, and with it raise the speed: on a 50,000-bar cent-step random walk with one missing bar in every 97, at 0.003, deleting the 516 missing bars left the TMV unchanged on all 49,484 remaining bars and changed T on 4,507 of them.
Each output is a step series: it changes only at confirmation bars and holds its value until the next one. The held series is bar-weighted: an Average, StdDev or PercentRank over it weights each trend by the number of bars until the next confirmation, not once. To take per-trend statistics, sample at the emissions with FuncWhere, whose condition DirectionalChangeEvent(theta).Abs().Mul(DirectionalChangeTrendBars(theta).GT(0)) is 1 exactly on the emission bars. The logarithm of the held speed is -Inf in the warm-up.
The machine is a latch: it remembers its last confirmation, so the outputs are not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars.
The method is causal and deterministic: each output at bar t reads only s[0..t], every leading segment of s gives the same first values bit for bit, and nothing is revised. Each trend is stamped one confirmation after it ends, at the first bar at which its end is known, so the outputs lag the trend’s end by at least one bar. Chen and Tsang’s Eq 2.4 stamps R at the trend’s extreme, which reads one directional-change event ahead.
The settings of the sources are documentation, not causal parameters: Chen and Tsang (2021) use 0.004 on second-by-second FX (Chapter 3), ten thresholds from 0.001 to 0.01 (Chapter 4) and 0.003 on daily index prices (Chapters 5 and 6), all with the inclusive Eq 2.1, which here is the call with math.Nextafter(theta, 0). Their T is physical time, on second-by-second data in Chapter 3; here T counts bars, and it equals elapsed time only on evenly spaced bars without gaps.
The outputs describe the previous swing one directional-change event late, and on daily bars at small thresholds most trends are short: 49 of the 76 trends of the AAPL daily prices of 2023 at 0.003 last 1 or 2 bars, so the speed there is dominated by the whole-number bar count. The book’s Tables 6.6 to 6.8 report that regime information lowered final wealth in 8 of 9 cells, and no trading edge is demonstrated. The statistics are not a Markov model but observations for one.
The cost is two passes, the machine’s and one over its age, O(1) per bar, and the method allocates only the result: one allocation per call whatever the length and whether the thresholds are valid, and none for an empty receiver.
Recipes built on the DirectionalChange methods are listed under “Compositions” in the “Regime Detection” category.
Verification: at each emission t, with k the age at t, ia = t - k and T the trend’s length, the TMV equals math.Abs(DirectionalChangeExtension(theta, thetaDown…)[ia])/thetaDir bit for bit, which for a symmetric theta is DirectionalChangeExtension(theta).Abs().Div(theta) at bar ia, the tracking TMV at the extreme, and it equals math.Abs(s.Momentum(T)[ia])/s[ib]/thetaDir bit for bit. On finite positive data, with q the event bar before t and p the one before q (the first valid bar for the first trend), a is s.Highest(t-q+1)[t] and b is s.Lowest(q-p+1)[q] for a -1 event, swapped for a +1 event. All three outputs also agree bit for bit with two independent references, one built on the machine’s reference and one written from Chen and Tsang’s Eqs 2.1 to 2.4, 4.1 and 4.2 and Appendix A, and with the trend length of 6 that their Fig 2.1 shows, from Time 3 to Time 9.
DirectionalChangeTrendBars
func (s Series) DirectionalChangeTrendBars(theta float64, thetaDown ...float64) Series
DirectionalChangeTrendBars returns the length in bars of the last finished directional-change trend, from extreme to extreme, stamped at the bar that confirms its end.
The machine is that of DirectionalChange: the directional change of Chen and Tsang (2021), Eq 2.1 and Appendix A, with a strict tie rule. Here up is theta, and down is thetaDown[0] when thetaDown has at least one element, else theta: only thetaDown[0] is read, and further elements are ignored. A trend runs from one confirmed extreme to the next. At each confirmation bar t from the second on, the trend that has just finished runs from the previous confirmed extreme b, at bar ib, to the extreme a, at bar ia, that the confirmation at t confirms, with ib < ia < t, and DirectionalChangeAge is t - ia at t. Its move is |a - b|/b, one subtraction, an absolute value and one division, and its threshold thetaDir is that of its own direction: up for a rising trend, which ends at a peak and is stamped at a -1 confirmation, and down for a falling one, stamped at a +1 confirmation. Chen and Tsang use one threshold; normalising each trend by the threshold of its own direction is this library’s extension. The trend length T is ia - ib, Chen and Tsang’s Eq 2.3 counted in bars: the number of bars from extreme to extreme. By the tie rule ia is the latest bar holding the extreme value a since the previous confirmation, and ib likewise for b, so T depends on the tie rule where the TMV does not; with a tie leaving the extreme at its first bar, [100, 106, 103, 106, 100, 107] at 0.05 would give T 1 at bar 4 and 3 at bar 5, where the method gives 3 and 1.
At every emission T is a whole number of at least 1. It is not NaN and not infinite. The finished trend runs opposite to the current DirectionalChange state: a rising trend is stamped when a -1 confirmation sets the state to -1. T is a bar-index difference, so it counts the missing bars inside a trend, as DirectionalChangeAge does. T stays finite where the TMV or the speed is +Inf: at a tiny theta, or where the ratio of the two extreme prices exceeds about 1.8e308.
The thresholds are valid if and only if 0 < up < +Inf and 0 < down < 1; NaN fails every comparison. An invalid thetaDown does not fall back to theta: DirectionalChangeTrendBars(0.1, 1) is invalid although DirectionalChangeTrendBars(0.1) is valid. Every invalid pair gives len(s) zeros, and an empty or nil receiver gives an empty result.
Units. theta and thetaDown are fractions: 0.05 means a 5% move. This differs on purpose from the older price-move thresholds in nseries, which take percentages: UpDown, UpDownString and UpDownSum (tolerance), and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The DirectionalChange family follows the directional-change literature (Chen & Tsang, Eq 2.1), where the threshold and the extension are fractions. DirectionalChangeExtension is therefore a fraction; DeltaPercent gives the same move multiplied by 100. The two conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. To use a percentage p, pass p/100. Go folds constant expressions exactly, so the constants 0.7/100 and 350.01 equal 0.007 and 0.35. The caveat is for p a float64 variable, where p/100 is computed at run time: for a whole-number percentage it equals the decimal literal (p = 5 gives 0.05), but for a fractional one it can differ from the literal in the last bit (p = 0.7 gives p/100 == 0.006999999999999999, not 0.007), and p0.01 can differ even for whole numbers (p = 35 gives p0.01 == 0.35000000000000003). Write the fraction literal (0.007) when a rule is stated in decimals. Because the tests are strict and exact, a one-bit difference in theta can move a confirmation that lands exactly on the threshold. For the same reason, a percentage test such as (p-LL)/LL100 > 7 is not the same test as (p-LL)/LL > 0.07: on [13.00, 13.91] the percentage test fires and the fraction test does not. For thresholds in points, see DirectionalChangePoints. The TMV is dimensionless, a multiple of the trend’s threshold; the speed is a fraction per bar, and the trend length T is in bars.
A threshold is crossed only when it is exceeded: a move exactly equal to its threshold does not confirm, so on [100, 110] at 0.1 nothing is confirmed, because (110 - 100)/100 is exactly the float64 0.1. To reproduce a source that counts equality as a crossing, pass math.Nextafter(theta, 0) and, for an asymmetric pair, math.Nextafter(thetaDown[0], 0): both tests use >, so both thresholds move towards 0, and a ratio exceeds math.Nextafter(x, 0) exactly when it is at least x, for every float64 ratio, because no float64 lies between a value and its neighbour. The one edge is a threshold of 5e-324, where math.Nextafter gives 0, which is invalid: pass 5e-324 unchanged, since no relative move between two distinct positive float64 prices is at most 5e-324, so both rules agree there. With the nudged thresholds the three methods give the inclusive machine’s events, trend lengths and speeds bit for bit, but the TMV is then divided by the nudged threshold, so it can exceed the literal inclusive value by one or two bit steps: on [21, 20, 21, 22, 23, 21] at 0.05 the nudged call gives 3 at bar 5, where the literal value is 2.9999999999999996, and on the AAPL daily prices of 2023 at 0.003 the two differ on 164 of the 200 bars. The literal value is DirectionalChangeExtension(math.Nextafter(theta, 0)).Abs().Div(theta) at the extreme bar ia.
The first valid index is the second confirmation bar, and the minimum length is 3: a trend needs two confirmed extremes, and its end is known only at the next confirmation. The three outputs are 0 before the second confirmation. The warm-up reads 0, not NaN: no emission is 0, because the TMV is above 1, T is at least 1 and the speed is above 0, so DirectionalChangeTrendBars(theta).GT(0), with the same thetaDown, detects exactly the bars from the first emission on. The first emitted trend is left-censored: it starts at the extreme reached since the first valid bar, so its values depend on where the series starts. On the AAPL daily prices of 2023 at 0.003, starting 1 to 59 bars later changed the first emission in 33 of the 59 starts and no later emission; that is a measurement on one series, not a guarantee.
A bar is missing when its price is not finite or is at most 0: a missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. The three outputs hold their values on a missing bar and are not NaN there, because they read the confirmed extremes and not the current price, and leading missing bars give 0. T counts the missing bars inside a trend, so deleting the missing bars from s leaves the TMV unchanged on the remaining bars and can shorten T, and with it raise the speed: on a 50,000-bar cent-step random walk with one missing bar in every 97, at 0.003, deleting the 516 missing bars left the TMV unchanged on all 49,484 remaining bars and changed T on 4,507 of them.
Each output is a step series: it changes only at confirmation bars and holds its value until the next one. The held series is bar-weighted: an Average, StdDev or PercentRank over it weights each trend by the number of bars until the next confirmation, not once. To take per-trend statistics, sample at the emissions with FuncWhere, whose condition DirectionalChangeEvent(theta).Abs().Mul(DirectionalChangeTrendBars(theta).GT(0)) is 1 exactly on the emission bars. The logarithm of the held speed is -Inf in the warm-up.
The machine is a latch: it remembers its last confirmation, so the outputs are not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars.
The method is causal and deterministic: each output at bar t reads only s[0..t], every leading segment of s gives the same first values bit for bit, and nothing is revised. Each trend is stamped one confirmation after it ends, at the first bar at which its end is known, so the outputs lag the trend’s end by at least one bar. Chen and Tsang’s Eq 2.4 stamps R at the trend’s extreme, which reads one directional-change event ahead.
The settings of the sources are documentation, not causal parameters: Chen and Tsang (2021) use 0.004 on second-by-second FX (Chapter 3), ten thresholds from 0.001 to 0.01 (Chapter 4) and 0.003 on daily index prices (Chapters 5 and 6), all with the inclusive Eq 2.1, which here is the call with math.Nextafter(theta, 0). Their T is physical time, on second-by-second data in Chapter 3; here T counts bars, and it equals elapsed time only on evenly spaced bars without gaps.
The outputs describe the previous swing one directional-change event late, and on daily bars at small thresholds most trends are short: 49 of the 76 trends of the AAPL daily prices of 2023 at 0.003 last 1 or 2 bars, so the speed there is dominated by the whole-number bar count. The book’s Tables 6.6 to 6.8 report that regime information lowered final wealth in 8 of 9 cells, and no trading edge is demonstrated. The statistics are not a Markov model but observations for one.
The cost is two passes, the machine’s and one over its age, O(1) per bar, and the method allocates only the result: one allocation per call whatever the length and whether the thresholds are valid, and none for an empty receiver.
Recipes built on the DirectionalChange methods are listed under “Compositions” in the “Regime Detection” category.
Verification: at each emission t, T equals DirectionalChangeAge[t-1] + 1 - DirectionalChangeAge[t] bit for bit, across missing bars too. On finite positive data, with q the event bar before t and p the one before q (the first valid bar for the first trend), ia is q + s.IndexOfHighestS(t-q+1)[t] and ib is p + s.IndexOfLowestS(q-p+1)[q] for a -1 event, swapped for a +1 event, and T is ia - ib; this needs the rule that a tie moves the extreme to the latest bar. All three outputs also agree bit for bit with two independent references, one built on the machine’s reference and one written from Chen and Tsang’s Eqs 2.1 to 2.4, 4.1 and 4.2 and Appendix A, and with the trend length of 6 that their Fig 2.1 shows, from Time 3 to Time 9.
DirectionalChangeTrendSpeed
func (s Series) DirectionalChangeTrendSpeed(theta float64, thetaDown ...float64) Series
DirectionalChangeTrendSpeed returns the absolute relative move per bar of the last finished directional-change trend, Chen and Tsang’s time-adjusted return R, stamped at the bar that confirms its end.
The machine is that of DirectionalChange: the directional change of Chen and Tsang (2021), Eq 2.1 and Appendix A, with a strict tie rule. Here up is theta, and down is thetaDown[0] when thetaDown has at least one element, else theta: only thetaDown[0] is read, and further elements are ignored. A trend runs from one confirmed extreme to the next. At each confirmation bar t from the second on, the trend that has just finished runs from the previous confirmed extreme b, at bar ib, to the extreme a, at bar ia, that the confirmation at t confirms, with ib < ia < t, and DirectionalChangeAge is t - ia at t. Its move is |a - b|/b, one subtraction, an absolute value and one division, and its threshold thetaDir is that of its own direction: up for a rising trend, which ends at a peak and is stamped at a -1 confirmation, and down for a falling one, stamped at a +1 confirmation. Chen and Tsang use one threshold; normalising each trend by the threshold of its own direction is this library’s extension. The speed is move/T with T = ia - ib, the trend’s length in bars: Chen and Tsang’s time-adjusted return R of Eq 2.4 and Eq 4.2, which they form as TMV/T times theta and as TMV times theta over T. The theta-free order used here gives the same speed for the same trend at every threshold that confirms it, where the book’s orders change its last bits with theta; DirectionalChangeTMV(theta).Div(DirectionalChangeTrendBars(theta)).Mul(theta) is within 2 bit steps of it where the TMV is finite. The speed depends on the tie rule through T. Chen and Tsang’s ln R is the logarithm of the speed sampled at the emissions, as below.
At every emission the speed is above 0. It is unsigned, so a falling trend has a positive speed too, and it is not NaN. The finished trend runs opposite to the current DirectionalChange state: a rising trend is stamped when a -1 confirmation sets the state to -1. The speed does not depend on theta and stays finite where only the TMV overflows, as at theta 1e-310 on [100, 101, 99, 101], where it is 0.01 at bar 2 and 0.019801980198019802 at bar 3; it is +Inf when the ratio of the two extreme prices exceeds about 1.8e308, as on [1, 1e-300, 1e10, 1] at 0.5, where it is +Inf at bar 3.
The thresholds are valid if and only if 0 < up < +Inf and 0 < down < 1; NaN fails every comparison. An invalid thetaDown does not fall back to theta: DirectionalChangeTrendSpeed(0.1, 1) is invalid although DirectionalChangeTrendSpeed(0.1) is valid. Every invalid pair gives len(s) zeros, and an empty or nil receiver gives an empty result.
Units. theta and thetaDown are fractions: 0.05 means a 5% move. This differs on purpose from the older price-move thresholds in nseries, which take percentages: UpDown, UpDownString and UpDownSum (tolerance), and Pivots and PivotIndices (thresholdPercent), where 5 means 5%. The DirectionalChange family follows the directional-change literature (Chen & Tsang, Eq 2.1), where the threshold and the extension are fractions. DirectionalChangeExtension is therefore a fraction; DeltaPercent gives the same move multiplied by 100. The two conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. To use a percentage p, pass p/100. Go folds constant expressions exactly, so the constants 0.7/100 and 350.01 equal 0.007 and 0.35. The caveat is for p a float64 variable, where p/100 is computed at run time: for a whole-number percentage it equals the decimal literal (p = 5 gives 0.05), but for a fractional one it can differ from the literal in the last bit (p = 0.7 gives p/100 == 0.006999999999999999, not 0.007), and p0.01 can differ even for whole numbers (p = 35 gives p0.01 == 0.35000000000000003). Write the fraction literal (0.007) when a rule is stated in decimals. Because the tests are strict and exact, a one-bit difference in theta can move a confirmation that lands exactly on the threshold. For the same reason, a percentage test such as (p-LL)/LL100 > 7 is not the same test as (p-LL)/LL > 0.07: on [13.00, 13.91] the percentage test fires and the fraction test does not. For thresholds in points, see DirectionalChangePoints. The TMV is dimensionless, a multiple of the trend’s threshold; the speed is a fraction per bar, and the trend length T is in bars.
A threshold is crossed only when it is exceeded: a move exactly equal to its threshold does not confirm, so on [100, 110] at 0.1 nothing is confirmed, because (110 - 100)/100 is exactly the float64 0.1. To reproduce a source that counts equality as a crossing, pass math.Nextafter(theta, 0) and, for an asymmetric pair, math.Nextafter(thetaDown[0], 0): both tests use >, so both thresholds move towards 0, and a ratio exceeds math.Nextafter(x, 0) exactly when it is at least x, for every float64 ratio, because no float64 lies between a value and its neighbour. The one edge is a threshold of 5e-324, where math.Nextafter gives 0, which is invalid: pass 5e-324 unchanged, since no relative move between two distinct positive float64 prices is at most 5e-324, so both rules agree there. With the nudged thresholds the three methods give the inclusive machine’s events, trend lengths and speeds bit for bit, but the TMV is then divided by the nudged threshold, so it can exceed the literal inclusive value by one or two bit steps: on [21, 20, 21, 22, 23, 21] at 0.05 the nudged call gives 3 at bar 5, where the literal value is 2.9999999999999996, and on the AAPL daily prices of 2023 at 0.003 the two differ on 164 of the 200 bars. The literal value is DirectionalChangeExtension(math.Nextafter(theta, 0)).Abs().Div(theta) at the extreme bar ia.
The first valid index is the second confirmation bar, and the minimum length is 3: a trend needs two confirmed extremes, and its end is known only at the next confirmation. The three outputs are 0 before the second confirmation. The warm-up reads 0, not NaN: no emission is 0, because the TMV is above 1, T is at least 1 and the speed is above 0, so DirectionalChangeTrendBars(theta).GT(0), with the same thetaDown, detects exactly the bars from the first emission on. The first emitted trend is left-censored: it starts at the extreme reached since the first valid bar, so its values depend on where the series starts. On the AAPL daily prices of 2023 at 0.003, starting 1 to 59 bars later changed the first emission in 33 of the 59 starts and no later emission; that is a measurement on one series, not a guarantee.
A bar is missing when its price is not finite or is at most 0: a missing bar updates nothing and fires nothing, the state is held and the age keeps counting. This is the hold class. The three outputs hold their values on a missing bar and are not NaN there, because they read the confirmed extremes and not the current price, and leading missing bars give 0. T counts the missing bars inside a trend, so deleting the missing bars from s leaves the TMV unchanged on the remaining bars and can shorten T, and with it raise the speed: on a 50,000-bar cent-step random walk with one missing bar in every 97, at 0.003, deleting the 516 missing bars left the TMV unchanged on all 49,484 remaining bars and changed T on 4,507 of them.
Each output is a step series: it changes only at confirmation bars and holds its value until the next one. The held series is bar-weighted: an Average, StdDev or PercentRank over it weights each trend by the number of bars until the next confirmation, not once. To take per-trend statistics, sample at the emissions with FuncWhere, whose condition DirectionalChangeEvent(theta).Abs().Mul(DirectionalChangeTrendBars(theta).GT(0)) is 1 exactly on the emission bars. The logarithm of the held speed is -Inf in the warm-up.
The machine is a latch: it remembers its last confirmation, so the outputs are not start-invariant, and a run started later can differ from the full run until it re-synchronises, after a path-dependent number of bars.
The method is causal and deterministic: each output at bar t reads only s[0..t], every leading segment of s gives the same first values bit for bit, and nothing is revised. Each trend is stamped one confirmation after it ends, at the first bar at which its end is known, so the outputs lag the trend’s end by at least one bar. Chen and Tsang’s Eq 2.4 stamps R at the trend’s extreme, which reads one directional-change event ahead.
The settings of the sources are documentation, not causal parameters: Chen and Tsang (2021) use 0.004 on second-by-second FX (Chapter 3), ten thresholds from 0.001 to 0.01 (Chapter 4) and 0.003 on daily index prices (Chapters 5 and 6), all with the inclusive Eq 2.1, which here is the call with math.Nextafter(theta, 0). Their T is physical time, on second-by-second data in Chapter 3; here T counts bars, and it equals elapsed time only on evenly spaced bars without gaps.
The outputs describe the previous swing one directional-change event late, and on daily bars at small thresholds most trends are short: 49 of the 76 trends of the AAPL daily prices of 2023 at 0.003 last 1 or 2 bars, so the speed there is dominated by the whole-number bar count. The book’s Tables 6.6 to 6.8 report that regime information lowered final wealth in 8 of 9 cells, and no trading edge is demonstrated. The statistics are not a Markov model but observations for one.
The cost is two passes, the machine’s and one over its age, O(1) per bar, and the method allocates only the result: one allocation per call whatever the length and whether the thresholds are valid, and none for an empty receiver.
Recipes built on the DirectionalChange methods are listed under “Compositions” in the “Regime Detection” category.
Verification: at each emission t, with k the age at t, ia = t - k and T the trend’s length, the speed equals math.Abs(DirectionalChangeExtension(theta, thetaDown…)[ia])/T and math.Abs(s.Momentum(T)[ia])/s[ib]/T bit for bit. All three outputs also agree bit for bit with two independent references, one built on the machine’s reference and one written from Chen and Tsang’s Eqs 2.1 to 2.4, 4.1 and 4.2 and Appendix A, and with the trend length of 6 that their Fig 2.1 shows, from Time 3 to Time 9.
RegimeDFA
func (s Series) RegimeDFA(n int, args ...float64) Series
RegimeDFA maps DFA (Detrended Fluctuation Analysis) alpha into trading regimes using conventional thresholds. Good default thresholds for setting DFA-based regime classification in trading are: * Trending regime: alpha > 0.55 * Mean-reverting regime: alpha < 0.45 * Random walk/neutral: alpha ≈ 0.5
These thresholds create a buffer around the “random walk” mid-value of 0.5, reducing false positives from noise or estimation error. Using 0.55 and 0.45 as cutoffs is a widely-used, empirically validated starting point, but you may fine-tune these based on the specific instrument or the characteristics of your time series and trading strategy.
Returns a series with values: +1 for trending (alpha > trendThresh), 0 for random/neutral, -1 for mean-reverting (alpha < meanRevThresh).
trendThresh and meanRevThresh are values of the DFA scaling exponent alpha (dimensionless, where 0.5 is a random walk), not percentages, and default to 0.55 and 0.45. The comparisons are strict: alpha > trendThresh gives +1, alpha < meanRevThresh gives -1, and anything else gives 0. Only zero or two optional arguments are accepted. n < 20 (fewer than the two DFA scales a fit needs), one optional argument, a NaN threshold or meanRevThresh above trendThresh is invalid and gives all zeros; equal thresholds (no neutral band) and infinite thresholds are valid. The warm-up reads 0, not NaN: bars 0 to n-2 are 0, the neutral reading, and the first valid index is n-1. Releases before this change read -1 (mean-reverting) on those bars, and on every bar for n < 20, because DFAAlpha’s warm-up 0 is below the default 0.45. For n from 20 to 23 alpha is a two-point fit (scales 4 and 5).
Compositions
Directional change
DirectionalChange confirms an upward run when the price has risen from its running low by more than a fraction, and a downward run when it has fallen from its running high by more than a fraction; DirectionalChangeExtension, DirectionalChangeAge and DirectionalChangeEvent give the move from the last confirmed extreme, the bars since that extreme and the confirmations themselves. The recipes below take prices c and thresholds held in float64 variables. The anchors of the directional-change recipes in this category are tagged E (an exact identity), G (a property every valid output has), T (a tolerance or margin) or W (a witness that agrees as documented, not exactly).
Units. The thresholds theta and thetaDown are fractions: 0.05 means a 5% move. This differs on purpose from the percentage tolerance of UpDown, UpDownString and UpDownSum and the thresholdPercent of Pivots and PivotIndices, where 5 means 5%. The difference was flagged for review, and GLE-254 (3 October 2026) kept both conventions: the unit follows the method family. Recipe (d) converts a percentage.
The undetermined state. Before the first confirmation the state is 0, and the extension, the age and the event are 0 too; DirectionalChange(theta).EQ(0) detects those bars exactly. The 0 is not a warm-up and not a run: a recipe that feeds the state or the extension to a latch, a rank, an age or a state builder masks it first, as recipes (f) and (g) do. The state is not NaN on any bar.
Ties. A threshold is crossed only when it is exceeded. To reproduce a source that counts equality as a crossing, pass each threshold through math.Nextafter(x, 0); at the smallest threshold, 5e-324, pass it unchanged.
| Source | Rule | Call |
|---|---|---|
| Chen and Tsang (2021), Eq 2.1 | inclusive | c.DirectionalChange(math.Nextafter(theta, 0)) |
| Vakkur (1997), spreadsheet | strict | c.DirectionalChange(0.10) |
| Vakkur (1997), prose (“or greater”) | inclusive | c.DirectionalChange(math.Nextafter(0.10, 0)) |
| Merrill (1988), “5% or more” from the low | inclusive | recipe (b) |
| Dai, Zhang and Zhu | rally “24% or more”, decline “more than 19%” | recipe (c) |
| Raftopoulos (2003) | inclusive, 0.10 to 0.18 | c.DirectionalChange(math.Nextafter(f, 0)) |
These settings are documentation, not causal parameters: each source chose its threshold on its own data, and no trading edge is demonstrated.
(a) Inclusive thresholds
st := c.DirectionalChange(math.Nextafter(theta, 0))- First valid index: 0; the minimum length is 1.
- Exact: a relative move exceeds
math.Nextafter(x, 0)exactly when it is at least x, because no float64 lies between a value and its neighbour. On [100, 110, 99] at 0.10 both moves are exactly 10% in float64: the strict method confirms neither, the inclusive call both. - Anchors: the four outputs equal an inclusive transcription of the machine (
>=in both tests) bit for bit on every bar (E). On a 20,000-bar quarter-step random walk at 0.005, 0.01 and 0.03 they reproduce the digest 31d2229ded56e838 of an independent reference implementation. - Pinned by
TestRecipeDirectionalChangeViews; runnable exampleExampleSeries_DirectionalChange_inclusive.
(b) Merrill’s filter
Merrill measures a decline from the low point, (H - p)/p, so his down fraction is f/(1+f), computed at run time from the float64 variable f:
g := f / (1 + f)
st := c.DirectionalChange(math.Nextafter(f, 0), math.Nextafter(g, 0))
strict := c.DirectionalChange(f, g)- First valid index: 0; the minimum length is 1.
- The variable matters: Go folds the constant
1 - 1/1.05exactly, to0.05/1.05, but at run time1 - 1/(1+f)is 0.04761904761904767, not f/(1+f), and misses the decline on [100, 105, 100] even aftermath.Nextafter. - Anchors:
stequals Merrill’s literal rule with inclusive comparisons andstrictthe literal rule with strict ones, measured from the low, on every bar of the AAPL closes of 2023 and of a quarter-step and a cent random walk at f = 0.01, 0.05 and 0.10 (E). - Rounding ties: each rule rounds its own quotient, so they can differ where one quotient rounds onto its threshold. On [64.47, 61.4] at f = 0.05, Merrill’s (H - p)/p rounds to 0.05 and his strict test misses the decline that
strictconfirms; on [14.07, 13.4],stconfirms a decline that is just below 5% for those float64 prices. - Pinned by
TestRecipeDirectionalChangeViews; runnable exampleExampleSeries_DirectionalChange_merrill.
(c) Dai, Zhang and Zhu’s mixed rule
st := c.DirectionalChange(math.Nextafter(0.24, 0), 0.19)- First valid index: 0; the minimum length is 1.
- Only the up threshold is nudged: a rally of exactly 24% ([100, 124]) confirms, a decline of exactly 19% ([200, 162]) does not, and [200, 161.99] does. Their segment tables are full-sample.
- Anchors: the four outputs equal a transcription with
>=in the up test and>in the down test bit for bit (E). - Pinned by
TestRecipeDirectionalChangeViews; runnable exampleExampleSeries_DirectionalChange_dai.
(d) A percentage threshold
theta := pct / 100- Whole numbers: for a whole-number
pct,pct / 100is the decimal literal (7 gives 0.07); for a fractional one it can differ in the last bit (0.7 gives 0.006999999999999999, not 0.007), andpct * 0.01can differ even for whole numbers (35 gives 0.35000000000000003). Go folds the constants0.7/100and35*0.01exactly. Write the fraction literal when a rule is stated in decimals. - Not a percentage test:
(p-LL)/LL*100 > 7is not(p-LL)/LL > 0.07; on [13.00, 13.91] the first fires andDirectionalChange(0.07)does not. - Anchors:
float64(k) / 100equals the parsed literalk/100for every whole number k from 1 to 10,000 (E). - Pinned by
TestRecipeDirectionalChangeViews; runnable exampleExampleSeries_DirectionalChange_percent.
(e) Gap mask
The method holds its state across a missing price (not finite, or at most 0), so a windowed chain fed the state cannot see the gap. Adding NaN on the missing bars makes it visible:
st := c.DirectionalChange(theta).Add(c.If(func(p float64) bool { return p > 0 && p < math.Inf(1) }, 0.0, math.NaN()))- First valid index: 0; the minimum length is 1.
- Footprint: NaN exactly on the missing bars, the state elsewhere; the age still counts the missing bars.
- Anchors: on tie walks with missing bars of every kind,
stis NaN exactly where the price is missing and equalsDirectionalChangebit for bit elsewhere (E). - Pinned by
TestRecipeDirectionalChangeViews; runnable exampleExampleSeries_DirectionalChange_gapMask.
(f) Run age
StateAge of the masked state counts each confirmed run from its confirmation bar, 1 on that bar; DirectionalChangeAge counts from the confirmed extreme, the delay earlier:
st := c.DirectionalChange(theta)
runAge := st.If(func(v float64) bool { return v == 0 }, math.NaN(), st).StateAge()- First valid index: the first confirmation bar;
runAgeis NaN before it. Unmasked,st.StateAge()ages the undetermined bars as a run. - Anchors: wherever the state is not 0,
runAge[t]is t minus the bar of the run’s confirmation plus 1, and on finite positive dataage[t] == age[t - runAge[t] + 1] + runAge[t] - 1withagetheDirectionalChangeAge(E). - Pinned by
TestRecipeDirectionalChangeViews; runnable exampleExampleSeries_DirectionalChange_runAge.
(g) Extension with the undetermined bars as NaN
st := c.DirectionalChange(theta)
ext := c.DirectionalChangeExtension(theta)
det := st.If(func(v float64) bool { return v == 0 }, math.NaN(), ext)- First valid index: the first confirmation bar;
detis NaN before it. - Anchors:
detis NaN exactly where the state is 0 or the price is missing, and equals the extension bit for bit elsewhere (E). - Pinned by
TestRecipeDirectionalChangeViews; runnable exampleExampleSeries_DirectionalChangeExtension_detector.
(h) Total price movement
Chen and Tsang’s TMV (Eq 4.1) is the move from the last confirmed extreme in units of the threshold:
tmv := c.DirectionalChangeExtension(theta).Abs().Div(theta)- First valid index: 0; the minimum length is 1. It is 0 before the first confirmation and NaN on a missing price.
- Anchors: wherever the state is not 0,
tmvequals Eq 4.1 written literally,(|Ps - Pe|/Ps)/thetawith Ps the confirmed extreme, bit for bit (E). On their Fig 5.2 at book t = 10 it is 1.6842105263157894, with T 6. - Pinned by
TestRecipeDirectionalChangeViews; runnable exampleExampleSeries_DirectionalChangeExtension_tmv.
Rate of directional change (Poster)
Poster’s rate of directional change (RODC) measures whipsaw: the number of zigzag segments in the last W bars as a percentage of W. A segment ends when the close reverses from its extreme by the threshold, which DirectionalChange confirms and DirectionalChangeEvent marks.
Units. The threshold theta is a fraction: 0.05 means a 5% move. RODC is a percentage of the window. The fraction differs on purpose from the percentage tolerance of UpDown and the thresholdPercent of Pivots, where 5 means 5%. The two conventions were reviewed and kept in GLE-254 (3 October 2026): the unit follows the method family. To convert a percentage p, pass p/100. Go folds constant expressions exactly, so the constants 0.7/100 and 350.01 equal 0.007 and 0.35. The caveat is for p a float64 variable, where p/100 is computed at run time: for a whole-number percentage it equals the decimal literal (p = 5 gives 0.05), but for a fractional one it can differ from the literal in the last bit (p = 0.7 gives p/100 == 0.006999999999999999, not 0.007), and p0.01 can differ even for whole numbers (p = 35 gives p*0.01 == 0.35000000000000003).
thI := math.Nextafter(theta, math.Inf(-1))
st := c.DirectionalChange(thI)
ev := c.DirectionalChangeEvent(thI).Abs()
rodc := ev.Sum(W).Add(1.0).Mul(100.0).Div(float64(W)).Mul(st.Abs()).SetN(W, 0)- Output:
rodcis 100(k+1)/W, where k counts the confirmations in the last W bars and the segment in progress at the window’s start counts as one. It is a percentage, not a state: rank it withQuantileStateor threshold it before a state consumer. - Ties: Poster’s printed code ends a segment on a reversal of at least the threshold, though his prose describes a strict drop; the recipe follows the code. DirectionalChange’s tests are strict, and a relative move exceeds
math.Nextafter(theta, math.Inf(-1))exactly when it is at least theta, for every float64 move. The one edge is theta = 5e-324, where the nudge gives 0, an invalid threshold, so every output is 0: pass 5e-324 unnudged, since no relative move between two distinct positive float64 prices is at most 5e-324. - First valid index: W, where the window holds W+1 closes, as Poster’s does; the minimum length is W+1.
SetN(W, 0)writes 0 before it. Before the first confirmation the state is 0 androdcis 0 too:st.EQ(0)detects those bars exactly. - Masks: none. The state and the events are never NaN: DirectionalChange holds a missing close (NaN, infinite, or not above 0) through the gap, so a gap neither confirms nor ends a segment, and
rodcis never NaN. - Exact: 100(k+1) is a whole number, so one division by W gives the correctly rounded percentage. Multiplying by a rounded 100/W rounds twice and can differ: at W = 6 and k = 4, 500/6 is 83.33333333333333 and 5 times 100/6 is 83.33333333333334. With integers, 100/W truncates (100/30 is 3). The factor
st.Abs()is 0 or 1, so the product is exact. A window of W moves holds at most W confirmations, so RODC is at most 100(W+1)/W and can exceed 100: alternating moves of 3% at theta = 0.02 and W = 10 give 110. - Anchors: E:
rodcequals 100(k+1)/W from an integer count of the confirmations, bit for bit, and is 0 where the state is 0. W: Poster’s MQL4 loop, ported as printed (each window restarts in up mode from the close before it, counts segments from 1 and tests the reversal in pips), against the recipe at theta = 0.0015/1.1 on a 1,500-close walk near 1.1 on a grid of 0.0001: its segment count per window is within three of the recipe’s on every bar and within one on at least 90% of them. - Deviations kept: Poster restarts each window in up mode, where the recipe carries the state across windows in one run of DirectionalChange; and he tests a fixed number of pips, an absolute move, where the recipe tests a fraction of the extreme, so a pip threshold matches a theta only near one price level. A form of this recipe on
DirectionalChangePoints, which takes its threshold in price units, is planned. His PerSmth smoothing (3 by default) is a simple average of the last PerSmth values, which a caller applies asrodc.Average(PerSmth); his first smoothed values are seeded, so they differ. - Sources: Poster (Stocks & Commodities V42:3, Eq 1 and the MQL4 sidebar) uses RODC to filter whipsaw on forex, with thresholds in pips; his trend persistence rate is “Trend Persistence Rate (Poster)” in the “Momentum” category. The state as a two-code alphabet is “Directional-change run state” under “Markov Models”.
- Pinned by
TestRecipeRODC; runnable exampleExampleSeries_DirectionalChange_rodc.
Bull Bear Index (Siroky)
Siroky’s Bull Bear Index counts the new highs (a high strictly above the previous bar’s high) and the new lows (a low strictly below the previous bar’s low) over the last n comparisons, scores their difference with a pooled two-proportion t-score and reports the Student-t distribution function with n-1 degrees of freedom: above 0.5 when new highs outnumber new lows. BullBearIndex is the index and BullBearRatio the author’s later count ratio, CH/(CH+CL), with no transform. Both read 0.5 on a window with equal counts, and both pair h and l at their most recent bars.
Windows. The article uses n = 10 for its worked example, n = 25 for its charts and n = 256 for one long chart; the ratio’s article uses 25 days.
bbi := Series(nil).BullBearIndex(h, l, n)
trimmed := bbi.Window(-n)
latch := bbi.SetN(n, math.NaN()).Hysteresis(0.75, 0.25)- Worked example: on the 11 bars of the article’s Fig 2 (two new highs and seven new lows over ten comparisons) the index is 0.0256 at n = 10 (
ExampleSeries_BullBearIndex) and the ratio 2/9 (ExampleSeries_BullBearRatio). The article’s printed probability for this example, 0.02, matches neither n-1 degrees of freedom nor the index; the method follows the stated n-1. - Warm-up: the first n bars read 0, below the 0.25 bear line, so trim with
Window(-n)or mask withSetN(n, math.NaN())before a threshold or a latch; untrimmed,Hysteresis(0.75, 0.25)reads -1 from bar 0. Both trims assume equal lengths: when h is longer than l by off bars, the first off+n bars read 0, so mask withSetN(off+n, math.NaN())instead. - Closed forms: at n = 2 the index is 1/2 + atan(x)/pi, and at n = 3 it is 1/2 + x/(2 sqrt(2 + x^2)); one new high and two new lows at n = 3 give exactly 0.25, two and one exactly 0.75.
- Caveats: the index is not a calibrated probability. New highs and new lows come from the same bars, the score grows with sqrt(n), so long windows saturate, and the author published no backtest.
- Pinned by
TestRecipeBullBear(the worked example, the warm-up and its trims, the latch and the exact quarters at n = 3); runnable examplesExampleSeries_BullBearIndexandExampleSeries_BullBearRatio.
Gain probability index (Siroky)
Siroky’s gain probability index is the share of rises among the bars that moved over the last n bars, in percent: 100 times the number of up bars divided by the number of up and down bars (his Eq 1), with unchanged bars ignored. The recipe flags the up and down changes of the close with GT and LT on Delta, counts them over n bars with Sum and divides once.
d := c.Delta()
up := d.GT(0.0).MaskNonFinite(d)
dn := d.LT(0.0).MaskNonFinite(d)
U, D := up.Sum(n), dn.Sum(n)
gpi := U.Ratio(U.Add(D)).Mul(100.0).MaskNonFinite(U, D).SetN(n, 0)- Output: a percentage from 0 to 100. At bar t the window is the n changes from c[t-n] to c[t], n+1 closes, and
UandDcount its rises and falls; 50 means as many rises as falls, and 100 that no bar fell. - Readings of 0: four cases give 0. The warm-up, bars 0 to n-1, is written by
SetN(n, 0). A window in which every bar that moved fell reads a true 0. A window in which no bar moved reads 0, not 50, becauseRatiomaps 0/0 to 0; from bar n,U.Add(D).EQ(0.0)is 1 exactly on such a window. An invalid n gives 0 on every bar: below 1Sumreturns zeros, and from len(c) onSetNcovers the whole series. - First valid index: n, with zeros before; the minimum length is n+1. At bar n-1 the unmasked ratio would be a correct index of n-1 changes, since
Delta’s bar 0 is neither a rise nor a fall, butSetN(n, 0)zeros it so that every value covers n changes. - Masks: a NaN or infinite close at bar p makes
gpiNaN on bars max(p, n) to p+n, n+1 bars, and the output recovers bit for bit after them.Deltacarries the close into the changes at p and p+1,MaskNonFinite(d)keeps them NaN in the flags, andMaskNonFinite(U, D)restores the NaN thatRatiomaps to 0. A close of 0 or below is an ordinary value here. - Anchors: E: on every window with no unchanged bar
gpiequalsup.Average(n).Mul(100.0)bit for bit, since both divide the same whole-number count by n once and then scale by 100; on the 200 AAPL closes of 2023 that holds on all 180 such windows at n = 10 and all 94 at n = 64. Counting an unchanged bar as half a rise,c.UpDownSum(n).Mul(50.0 / float64(n)).Add(50.0), agrees only on a window with no unchanged bar or with as many rises as falls; on those closes it differs on all 10 windows with an unchanged bar at n = 10 and all 42 at n = 64. - The Bull Bear Index: with the closes as both highs and lows, a new high is a rise and a new low a fall, so
BullBearIndexandBullBearRatioread the same counts. For n of at least 2,Series(nil).BullBearRatio(c, c, n).Mul(100.0)equalsgpibit for bit except on a window in which no bar moved, where the ratio reads 0.5 andgpi0.Series(nil).BullBearIndex(c, c, n)is the Student-t transform of the same counts: it lies above 0.5 exactly wheregpilies above 50, and it saturates, so that in the Examplegpivalues of 80.0, 88.9 and 87.5 all read 0.99. - Evidence: Siroky’s Fig 1 counts 7 rises and 3 falls over 10 bars, an index of 70, with no prices printed; his readings for AAPL and RAX at n = 64 have no printed inputs either, so no published value can be reproduced beyond that count. The index is causal: each value reads only the closes up to its bar.
- Sources: Siroky, “Gain Probability Index”, Technical Analysis of Stocks & Commodities V35:7 (June 2017), pp.14-19: Eq 1 and Fig 1 (p.16).
- Pinned by
TestRecipeGainProbabilityIndex; runnable exampleExampleSeries_BullBearIndex_gpi.
First valid index of the gain probability stages
| Stage | First valid index f | Before f |
|---|---|---|
Delta() | 1 | zeros |
GT(x), LT(x), MaskNonFinite(refs) | 0 | nothing |
Sum(n) | n - 1 | the sum of the bars so far |
Add(x), Ratio(s2), Mul(x) | 0 | nothing |
SetN(n, 0) | n | zeros |
Chen and Tsang’s CT1 contrarian rule (research composition)
Research composition. Chen and Tsang’s CT1 trades against the run in progress: in an upward run it opens a short position once the run’s total price movement (TMV) reaches 2, in a downward run a long position once TMV reaches -2, and it closes the position at the next directional-change confirmation. The book states the rules in prose, with no code and no worked trade. It says that CT1 uses JC2’s rules, but CT1’s printed close at the next confirmation is JC1’s, and JC2’s rule list has none, though the book’s Table 6.1 gives it one; the recipe follows CT1’s own list. JC1 and JC2 add gating by a regime tracker with a re-arming rule that the book does not define, so that gating is left to the caller. The book’s Tables 6.6 to 6.8 report that regime information lowered final wealth in 8 of 9 cells, and no trading edge is demonstrated.
Units. The threshold alpha is a fraction: 0.05 means a 5% move. This differs on purpose from the percentage tolerance of UpDown, UpDownString and UpDownSum and the thresholdPercent of Pivots and PivotIndices, where 5 means 5%. The difference was flagged for review, and GLE-254 (3 October 2026) kept both conventions: the unit follows the method family. TMV is the extension in units of alpha, so 2 is a move of twice the threshold from the run’s confirmed extreme.
aIncl := math.Nextafter(alpha, 0)
st := c.DirectionalChange(aIncl)
tmv := c.DirectionalChangeExtension(aIncl).Div(alpha)
short := st.If(func(v float64) bool { return v == 1 }, tmv, math.Inf(-1)).Hysteresis(math.Nextafter(2, math.Inf(-1)), -math.MaxFloat64).GT(0)
long := st.If(func(v float64) bool { return v == -1 }, tmv.Mul(-1.0), math.Inf(-1)).Hysteresis(math.Nextafter(2, math.Inf(-1)), -math.MaxFloat64).GT(0)- Output:
shortandlongare 1 while the position is held and 0 otherwise. Each latch reads TMV inside its run, negated for the long leg, and -Inf elsewhere:Hysteresis(math.Nextafter(2, math.Inf(-1)), -math.MaxFloat64)turns on at an input of at least 2 and holds between, and since only -Inf lies below -MaxFloat64 it turns off only at the confirmation that ends the run, where the input becomes -Inf. The two legs are never 1 on the same bar. - Ties: the book’s directional change (its Eq 2.1) confirms a move of at least the threshold, and its Rules 1 and 2 open at TMV at least 2 and at most -2. Both calls take
math.Nextafter(alpha, 0), so that the state and the extension come from the same inclusive machine (a move exceeds the nudged threshold exactly when it is at least alpha), and the divisor stays alpha, as in its Eq 4.1: dividing by the nudged threshold gives 2.0000000000000004 for an extension of exactly 0.1 at alpha 0.05. On [100, 105, 110, 108, 104, 99] at 0.05 the state is 0, 1, 1, 1, -1, -1 (0, 0, 1, 1, -1, -1 on the strict machine), TMV is 0, 1, 2, 1.6, -1.09, -2 to the digits shown,short0, 0, 1, 1, 0, 0 andlong0, 0, 0, 0, 0, 1; the strict latchHysteresis(2, -math.MaxFloat64)leaves both legs 0 there. - First valid index: 0; the minimum length is 1. Before the first confirmation the state is 0, the latch input -Inf and both legs 0.
- Masks: a missing close (NaN, infinite, or not above 0) gives a NaN extension and TMV, and the latch holds the position through it, as the state does.
- Anchors: E:
tmv.Abs()equalsc.DirectionalChangeExtension(aIncl).Abs().Div(alpha)bit for bit, the unsigned TMV of recipe (h) of “Directional change” in this category taken on the inclusive machine; and both legs equal a per-bar loop of the rules with inclusive tests (at least alpha, at least 2), bit for bit. - Published vectors: on the closes read from Chen and Tsang’s Fig 2.1, 97, 96, 98, 95, 97, 100, 102, 104, 103, 105, 103, 99, at alpha 0.05 the state is 0 on bars 0 to 4, 1 on bars 5 to 10 and -1 at bar 11; TMV on bars 5 to 11 is 1.0526315789473684, 1.4736842105263155, 1.894736842105263, 1.6842105263157894, 2.1052631578947367, 1.6842105263157894 and -1.1428571428571428, bar 9 being the figure’s TMV_EXT, 10/(95*0.05) at the threshold 0.05 that this page reads into the figure, which prints none; the short leg is 1 on bars 9 and 10 and the long leg 0 throughout. The strict machine and the strict latch give the same vectors there: no move that the machine tests equals the threshold, and no TMV equals 2 or -2. On the constructed closes 100, 95, 108, 125, 150, 180, 160, 140, NaN, 135, 120, 95, 100 at alpha 0.10 the short leg is 1 on bars 3 to 5 and the long leg on bars 7 to 12, through the NaN at bar 8.
- Parameters: the book’s trading thresholds are 0.03, 0.006 and 0.009 (the text under its Eq 6.1), with TMV 2, after Glattfelder et al., who found that the foreign-exchange market changes direction on average at TMV 2. All are fixed in advance; choosing among the published thresholds on the test years would be in-sample.
- Sources: Chen and Tsang, Detecting Regime Change in Computational Finance (2021): Table 6.1 and the CT1 rules of Sec 6.2.4 (PDF pp.130 and 132-133), Eq 2.1 and Fig 2.1 (PDF p.44), Eq 4.1, and Eq 6.1 (PDF p.135). Two independent readings of PDF pp.132-133 confirmed the inclusive tests of Rules 1 and 2 before this recipe was written (30 September 2026).
- Pinned by
TestRecipeChenTsangCT1; runnable exampleExampleSeries_DirectionalChangeExtension_ct1.
First valid index of the CT1 stages
| Stage | First valid index f | Before f |
|---|---|---|
DirectionalChange(theta), DirectionalChangeExtension(theta) | 0 | nothing |
Div(x), Mul(x), If(cond, yes, no) | 0 | nothing |
Hysteresis(on, off) | 0 | nothing |
GT(x) | 0 | nothing |
Directional change with a threshold series
DirectionalChangePointsScaled, DirectionalChangePointsExtensionScaled and DirectionalChangePointsAgeScaled run the directional change in the receiver’s units with a threshold that is itself a series: bar t tests its moves against its own threshold h[t] (and hDown[0][t] for the down test, when given). h is right-aligned with the closes c at the most recent bar, and the bars before the overlap read 0. A bar whose value is not finite, or whose threshold is NaN, infinite or negative, is missing: it holds the state for that bar only. A threshold of 0 is valid and lets any move confirm. With a constant series the methods are DirectionalChangePoints and its views. The recipes below take closes c, highs hi and lows lo; their outputs are codes, counts and differences of inputs, all exact.
(a) Swings on an average-true-range threshold
Raschke builds swing charts with a volatility filter after Wilder: a new wave when price moves k times the 10-bar simple average of TrueRange from the last swing extreme, with k from 2 to 3. On closes, with the threshold committed a bar early and its warm-up masked:
dist := c.ATR(hi, lo, c, n).Mul(k).Shift(1).SetN(n+1, math.NaN())
state := c.DirectionalChangePointsScaled(dist)
events := state.Delta().Clamp(-1, 1)- First valid index: 0 for all three; the minimum length is 1. Bars 0 to
nare missing, so the machine starts at barn+1with state 0.ATRpassesTrueRangethrough on bars 0 ton-2, and its first average, at barn-1, includes bar 0’s rangehi[0] - lo[0], which has no previous close; afterShift(1)these sit on bars 1 ton, and bar 0 holds the shift’s 0, a valid threshold. Without theSetNthe machine starts at bar 0 and reads those values as thresholds. - Units:
distis in the closes’ units, as the method requires. Raschke tests the rise on highs and the fall on closes; this recipe tests both on closes. - Anchors: at an event bar
twith agekfromc.DirectionalChangePointsAgeScaled(dist), the confirmed extreme is bart-kand the extension is beyonddist[t](E, throughMomentum). On the 200 AAPL bars of 2023 in the package’s test data, withn = 10andk = 2, the first confirmation is at bar 18, with 5 up and 6 down confirmations; without theSetNit is at bar 9, with 6 of each. Atk = 3there are 4 up and 3 down, the first at bar 29. - Pinned by
TestRecipeDirectionalChangePointsScaled; runnable exampleExampleSeries_DirectionalChangePointsScaled_atr.
(b) A threshold committed before its bar
Each bar is compared with its own threshold, so a threshold built from the bar itself, such as its range, grows with the move it tests. To commit each threshold a bar early, with h the threshold series (the anchors use the bar’s range, hi.Sub(lo)):
pre := h.Shift(1).SetN(1, math.NaN())
state := c.DirectionalChangePointsScaled(pre)- First valid index: 0; the minimum length is 1. Bar 0 is masked, since
Shift(1)pads it with 0, a valid threshold, so the machine starts at bar 1. - Anchors:
preat bartish[t-1](E,Shift). On the 200 AAPL bars of 2023 withh := hi.Sub(lo), the bar’s own range gives 13 up and 13 down confirmations and the pre-committed range 16 of each, both first at bar 3; the two states differ on 28 bars. - Pinned by
TestRecipeDirectionalChangePointsScaled; runnable exampleExampleSeries_DirectionalChangePointsScaled_precommitted.
(c) Inclusive reversals
A source that reverses on a move of at least the threshold is the strict method with every positive finite threshold nudged down by one float64:
inclusive := h.Map(func(x float64) float64 {
if x > 0 && x < math.Inf(1) {
return math.Nextafter(x, math.Inf(-1))
}
return x
})
state := c.DirectionalChangePointsScaled(inclusive)- First valid index: 0; the minimum length is 1.
- Exactness: a move exceeds
math.Nextafter(x, math.Inf(-1))exactly when it is at leastx, for every float64 move. The guard keeps a bad bar bad (math.Nextafter(+Inf, math.Inf(-1))is MaxFloat64, a valid threshold) and leaves a threshold of 0 strict: unguarded, the nudge would turn 0 into -5e-324, an invalid threshold, and so make those bars missing. MaphDown[0]the same way. - Anchors: where no threshold is 0, the inclusive state equals the
>=reading of the step list on every bar (E). On the 20,000-bar quarter-step walk withh[t] = (t mod 5)/4and+Infwheret mod 50 = 49, there are 3,555 strict and 5,005 inclusive confirmations, and the states differ on 4,588 bars; the guarded map leaves 400 missing bars, where the unguarded nudge would leave 4,000. - Pinned by
TestRecipeDirectionalChangePointsScaled; runnable exampleExampleSeries_DirectionalChangePointsScaled_inclusive.
Directional change in points
DirectionalChangePoints, DirectionalChangePointsExtension and DirectionalChangePointsAge run the directional-change machine with thresholds in the receiver’s own units: points or pips on prices, and the indicator’s own units on an oscillator or a spread. Each move is one subtraction from the running extreme, and a threshold is crossed only when it is exceeded. Zero and negative values are valid; only a value that is not finite is missing, and a missing bar holds the state. The recipes below take closes c or an oscillator osc and a threshold h; their outputs are codes, counts and differences of inputs, all exact.
(a) Inclusive reversals
Poster’s 2024 listing reverses on a move of at least the threshold (>= and <=), and so does Raftopoulos’s points mode. Nudge the threshold down by one float64:
strict := c.DirectionalChangePoints(h)
inclusive := c.DirectionalChangePoints(math.Nextafter(h, math.Inf(-1)))- First valid index: 0 for both; the minimum length is 1. Both start in the undetermined state 0.
- Exactness: a move exceeds
math.Nextafter(h, math.Inf(-1))exactly when it is at leasth, for every float64 move. Nudge an asymmetrichDownthe same way. Ath = 5e-324the nudge gives 0, which is valid; there is no recipe ath = 0, where it gives -5e-324, which is invalid. - Anchors: the inclusive state equals the
>=reading of the method’s step list on every bar (E). On a 20,000-bar quarter-step random walk ath = 1the two states differ on 3,048 bars, with 1,086 strict and 1,524 inclusive confirmations. - Pinned by
TestRecipeDirectionalChangePoints; runnable exampleExampleSeries_DirectionalChangePoints_inclusive.
(b) Events and views on an oscillator
state := osc.DirectionalChangePoints(h)
events := state.Delta().Clamp(-1, 1)
ext := osc.DirectionalChangePointsExtension(h)
age := osc.DirectionalChangePointsAge(h)- First valid index: 0 for all four; the minimum length is 1.
eventsis +1 or -1 exactly on the confirmation bars and 0 on every other bar, missing bars included. - Views: at an event bar
twith agek, the confirmed extreme is bart-k, a swing high for -1 and a swing low for +1, andextis the test’s own move, abovehat +1 and below-hat -1. - Warm-up zeros: zero is a valid value here, unlike in
DirectionalChange, so mask an upstream warm-up withSetN(F, math.NaN())first. On the 200 AAPL closes of 2023 in the package’s test data,c.Sub(c.Average(10))is 0 on bars 0 to 8; ath = 2the unmasked oscillator confirms a rise from that 0 at bar 9, whilec.Sub(c.Average(10)).SetN(9, math.NaN())first confirms at bar 11. Both give 19 up and 19 down confirmations. - Anchors:
extequalsosc.Momentum(k)at every bar with a non-zero state and a finite value (E). - Pinned by
TestRecipeDirectionalChangePoints; runnable exampleExampleSeries_DirectionalChangePoints_events.
Directional-change trend statistics
DirectionalChangeTMV, DirectionalChangeTrendBars and DirectionalChangeTrendSpeed describe each finished trend of the directional-change machine: its move from extreme to extreme in units of the threshold of its own direction (Chen and Tsang’s total move, TMV), its length in bars, and its move per bar (their time-adjusted return R). Each is stamped at the bar that confirms the trend’s end, the confirmation that reveals its extreme, and held until the next; all three are 0 before the second confirmation. The recipes below take prices c and a fraction theta. Recipe (h) of Directional change gives the tracking TMV of the run in progress, and the page on Chen and Tsang’s CT1 contrarian rule uses its signed form; the recipes here connect that tracking value to the finished statistics.
(a) Tracking and finished values
ext := c.DirectionalChangeExtension(theta)
tracking := ext.Abs().Div(theta)
signed := ext.Div(theta)
age := c.DirectionalChangeAge(theta)
tmv := c.DirectionalChangeTMV(theta)
bars := c.DirectionalChangeTrendBars(theta)- First valid index: 0 for
ext,tracking,signedandage, which are 0 before the first confirmation (the first three are NaN on a missing price); the second confirmation bar fortmvandbars, which are 0 before it. The minimum length is 3. - Exactness: at a bar
tthat stamps a finished trend, withia = t - age[t]the bar of the extreme it confirms,tracking[ia]equalstmv[t]bit for bit: the tracking value at the extreme is the finished value stamped later. Withref := c.ShiftVariable(age), as in the “Threshold swings” recipes,tmv[t]is also|ref[t] - ref[t-1]|/ref[t-1]/thetaat each stamped bar, andbars[t]isage[t-1] + 1 - age[t]. On Chen and Tsang’s Fig 5.2 at 0.05 the tracking value at index 8 and the TMV stamped at index 10 are both 2.1052631578947367, and the trend lasted 5 bars;signed, the form the CT1 page uses, is -1.1428571428571428 at index 10, in the new falling run. - Anchors: the TMV is
|ext[ia]|/thetaDirandbarsthe age identity above (K, the same kernel); for an asymmetric pairthetaDirisupfor a rising trend anddownfor a falling one, so divideext.Abs()by that threshold. - Pinned by
TestRecipeDirectionalChangeTrends; runnable exampleExampleSeries_DirectionalChangeTMV_tracking.
(b) Per-trend statistics at event bars
speed := c.DirectionalChangeTrendSpeed(theta)
r := tmv.Div(bars).Mul(theta)
emit := c.DirectionalChangeEvent(theta).Abs().Mul(bars.GT(0))
lnR := speed.FuncWhere(emit, func(x Series) Series { return x.Log() })- First valid index: the second confirmation bar for
speed,randemit;lnRis NaN before it. - Exactness:
emitis 1 exactly on the bars that stamp a trend, the confirmations from the second on, and 0 elsewhere. The held statistics are bar-weighted, so an average over them weights each trend by the bars until the next confirmation;FuncWherepasses the callback one value per trend instead, and holds each result until the next stamp. Here it gives ln R, the observation of Chen and Tsang’s regime model, which the logarithm of the held speed would make -Inf in the warm-up. A per-trend average or deviation goes in the callback the same way.ris R in Chen and Tsang’s Eq 2.4 order, within 2 bit steps ofspeedwheretmvis finite: on the 50,000-bar cent-step random walk of the package’s test data at 0.001 the two differ on 2,061 of 15,967 trends. Print ln R to six decimals:math.Logcan differ in its last bit between architectures. - Anchors:
speedis|ext[ia]|/bars[t](K) and|c.Momentum(T)[ia]|/c[ib]/TwithT = bars[t]andib = ia - T(E). - Pinned by
TestRecipeDirectionalChangeTrends; runnable exampleExampleSeries_DirectionalChangeTMV_tracking.
(c) Inclusive thresholds
Chen and Tsang’s Eq 2.1 confirms a move of at least the threshold. Nudge the threshold down by one float64, and an asymmetric thetaDown the same way:
incl := math.Nextafter(theta, 0)
recipe := c.DirectionalChangeTMV(incl)
bars := c.DirectionalChangeTrendBars(incl)
speed := c.DirectionalChangeTrendSpeed(incl)
literal := c.DirectionalChangeExtension(incl).Abs().Div(theta)- First valid index: the inclusive machine’s second confirmation bar; the minimum length is 3.
- Exactness:
barsandspeedare the inclusive machine’s trend lengths and speeds bit for bit.recipeis divided by the nudged threshold, so it can exceed the literal value by one or two bit steps: on [21, 20, 21, 22, 23, 21] at 0.05 it is 3 at bar 5, where the literal value is 2.9999999999999996, and on the AAPL daily prices of 2023 in the package’s test data at 0.003 the two differ on 164 of the 200 bars. The literal value isliteral[ia]at the extreme baria. On [100, 110, 99, 110] at 0.1 the first two moves are exactly 10%: the strict methods stamp nothing, and the nudged ones stamp two trends of 1 bar each. At the smallest threshold, 5e-324, pass it unchanged, as forDirectionalChange:math.Nextaftergives 0, which is invalid. - Anchors:
bars,speedandliteral[ia]equal a>=reading of the machine bit for bit (E). - Pinned by
TestRecipeDirectionalChangeTrends; runnable exampleExampleSeries_DirectionalChangeTMV_inclusive.
Michael Zahorchak’s method (The Art of Low Risk Investing, Van Nostrand Reinhold, 1977, out of print; the tables below are Greg Morris’s, The Complete Guide to Market Breadth Indicators, 2015, Tables 4-1 and 4-2; Table 4-1 is also printed in his StockCharts articles “Zahorchak Measure II”, 2015, with a different tenth row, and “Zahorchak Revisited”, 2017, and Table 4-2 in the 2015 article) reads the market’s posture from an index and its breadth and each stock’s posture from its own averages: in Morris’s summary “the primary trend tells you when to buy stocks and when to avoid them”, and “Once stocks have been bought, their trend action tells you when to sell”. The recipes run on weekly bars (the caller’s bars; the market posture’s section gives daily lengths) and lengths are in bars. Each code is NaN before its first valid index and wherever an input it reads is not finite. A value equal to the one it is compared with reads “not above”, and an average equal to its value a bar earlier reads “down”. The advances and declines follow the Breadth inputs page (weekly counts, not sums of daily counts, paired by position with the closes). A code flips on a one-ulp difference near a tie, so the cross-language goldens run on prices in sixty-fourths and integer counts: their window sums and differences are exact, two distinct simple averages of lengths n1 and n2 are at least 1/(64 n1 n2) apart, far beyond rounding, and the test path for Merrill’s rating keeps its close and averages apart. Related: Dukas’s six phases (moving-averages/t6-ma-stack-systems.md), the same ordering code on a close and two averages, and the Breadth category’s advance-decline recipes.
Zahorchak’s market posture (Table A)
Table A crosses four columns: “5 week” and “15 week”, each “40” or “-40” ("+40" in Morris’s prose) for the 5- or 15-week simple average above or below the 40-week one; “40 week”, the 40-week average “Up” or “Down”; and “AD Line 15 week”, the 15-week average of the advance-decline line “Up” or “Down”. Morris writes “+40 or -40 mean that the price is above (+) or below (-) the 40 week average”, but the 5-week and 15-week columns would then be the same, so the averages are meant. Twelve rows print eight labels, coded as seven postures: 4 “Bull market - stay invested”, 3 “Buy aggressively or stay invested”, 2 “Second sign of bull - BUY”, 1 “Uncertain (possibly first sign of bull - BUY)”, 0 “Uncertain (stay invested - no buying)”, -2 “Uncertain (probably bear rally)” and -3 “Bear market” (rows 1 and 2 add “avoid new purchases”); one row reads “Up/-40”, the 5-week average below the 40-week but rising. s2ZahorchakMarket writes the five tests as the bits of a key and reads the code from a 32-entry table.
as := c.Average(s)
ms := c.Momentum(s)
net := a.Sub(d).Sum(m)
p5 := c.Average(f).GT(as)
p15 := c.Average(m).GT(as)
u5 := c.Momentum(f).GT(0)
key := u5.Mul(16).Add(p5.Mul(8)).Add(p15.Mul(4)).Add(ms.GT(0).Mul(2)).Add(net.GT(0)).SetN(s, math.NaN()).
MaskNonFinite(as, ms, net)
tableA := [32]float64{
-3, 1, -3, -3, 0, 0, 0, 0, 1, 2, -3, -3, 0, 3, 0, 4,
-2, 1, -3, -3, 0, 0, 0, 0, 1, 2, -3, -3, 0, 3, 0, 4,
}
code := key.Map(func(k float64) float64 {
if math.IsNaN(k) {
return k
}
return tableA[int(k)]
})- Inputs: weekly index closes
c(Zahorchak used the Dow Industrials, Morris the NYSE Composite), weekly advancesaand declinesd, all of one length;f,mands(5, 15 and 40). The daily form is 25, 75 and 200 on daily closes and counts: Morris gives 75 and 200, and 25 for the 5 weeks is our inference. - First valid index: s (40; 200 daily). Both outputs are NaN before it, and wherever a close in the slow window or s bars back, or an advance or a decline in the middle window, is not finite: on the weekly test path a NaN close at bar 900 masks bars 900 to 940, a NaN advance count at bar 960 masks 960 to 974, an infinite close at bar 1000 masks 1000 to 1040, and the code recovers after each.
- Anchors: a simple average rises exactly when its input rises over its length, so “40 week Up” is
c.Momentum(s).GT(0), and the middle average of the cumulative linea.Sub(d).CumSum()rises exactly when the last m net advances sum above 0,a.Sub(d).Sum(m).GT(0), whatever the line’s origin; both equal the direct comparisons of the averages with themselves a bar earlier on every finite bar of the test fixtures, and the code is start-invariant bit for bit. The table is Morris’s rows cell by cell: “Up/-40” refines the first row only, so the 16 bit matters at key 0 alone; the four unprinted cells (both short averages above the 40-week with both slopes down, and the 5-week below with the 15-week above in three slope cases) read 0, as one of them is printed in the 2015 article, whose tenth row, (-40, 40, Down, Up), differs from the book’s and gives the same table under that rule. On the weekly test path the codes from bar 40 are -3 on 248 bars, -2 on 111, 0 on 233, 1 on 239, 2 on 10, 3 on 16 and 4 on 106. - Traps: unmasked, the warm-up reads codes, because the averages pass the close through and the momentum reads 0, and a NaN close reads as a code, because a comparison with NaN is false; hence the mask. Go’s
int(NaN)is not portable (on amd64 it is the most negative int64, an index out of range, and on arm64 it is 0, which reads the first entry silently), so the lookup returns NaN for NaN before it indexes. The table is stateless: the market table does not say sell, and a code of 0 means hold what is held. - Variant: the four conditions Zahorchak names, mapped by our reading of the table, bull for codes 3 and 4, a sideways bull for 0, an uncertain bear for 1 and 2 and a bear for -2 and -3:
code.GTE(3).Sub(code.LTE(-2)).Add(code.Mul(0))reads +1, 0 or -1 for the bull, the uncertain states and the bear, and carries the code’s NaN. - Evidence: Morris shows charts and no backtest of the table. Evidence, not a reference.
- Pinned by
TestRecipeS2ZahorchakMarket; runnable exampleExampleSeries_Average_zahorchakMarket.
Zahorchak’s stock posture (Table B)
Table B reads a stock’s own 5-, 15- and 40-week simple averages, with no breadth column (“there is no advance decline information on an individual stock”). Every posture is printed with the 40-week average “Up” and with it “Down” (the last row as “Up/Down”), so only the ordering of the three averages matters: Strong (“Hold, regardless of general market”) for 5 > 15 > 40 (its row prints both short averages above the 40-week, read as 5 > 15 by exclusion from the “-15” row), Weakening (“Hold if Bull - Sell if Bear”) for 15 > 5 > 40 and 15 > 40 > 5, Emerging (“Buy in early Bull - Avoid in Bear”) for 5 > 40 > 15, and Weak (“Avoid, regardless of general market”) for 40 > 5 > 15 and 40 > 15 > 5. s2ZahorchakStock writes the ordering as a code.
m5 := c.Average(f)
m15 := c.Average(m)
m40 := c.Average(s)
code := m5.GT(m15).Mul(4).Add(m5.GT(m40).Mul(2)).Add(m15.GT(m40)).SetN(s-1, math.NaN()).MaskNonFinite(m40)- Inputs: a stock’s closes
c;f,mands(5, 15 and 40). The codes are 7 Strong, 3 and 1 Weakening, 6 Emerging, 4 and 0 Weak. - First valid index: s - 1 (39). NaN before it and wherever the slow average is not finite: a NaN close at bar p masks p to p + s - 1.
- Anchors: codes 2 and 5 cannot occur (code 2 needs m5 <= m15 <= m40 < m5, code 5 m40 < m15 < m5 <= m40), ties included; a tie puts the later of the tied averages in the list (5, 15, 40) above the earlier, the reading of every bar of the tie fixture. On the weekly test path’s instrument the codes from bar 39 are 7 on 257 bars, 6 on 35, 4 on 98, 3 on 45, 1 on 44 and 0 on 542. The code is start-invariant, since each average reads only its window: bit for bit on the test path.
- Traps: the 40-week slope column does not change the answer, so no slope is computed. A flat history reads 0, Weak, because three equal averages are none above another. Unmasked, the warm-up compares averages with the closes the longer ones pass through, and bars 0 to f - 2, where every average is the close, read 0.
- Variant: the four classes as an ordinal, Weak 0, Weakening 1, Emerging 2 and Strong 3:
code.EQ(1).Add(code.EQ(3)).Add(code.EQ(6).Mul(2)).Add(code.EQ(7).Mul(3)).Add(code.Mul(0)), whose last term carries the code’s NaN. - Evidence: Morris shows charts and no backtest. Evidence, not a reference.
- Pinned by
TestRecipeS2ZahorchakStock; runnable exampleExampleSeries_Average_zahorchakStock.
The two-level gate
The tables give the market’s posture and each stock’s, and Table B’s postures name the market: “Hold if Bull - Sell if Bear”, “Buy in early Bull - Avoid in Bear”. s2ZahorchakGate crosses the two codes: 2 where a buy is allowed, 1 hold (keep if held, no new buy), -1 sell or avoid. The market code is grouped as bear (-3, -2), uncertain (0), early bull (1 to 3, the codes where Table A says buy: “BUY” at 1 and 2, “Buy aggressively” at 3) and bull (4). A cell is printed, follows the buy rule (a new buy only where Table A says buy) or is our reading:
| Stock | Bear | Uncertain | Early bull | Bull |
|---|---|---|---|---|
| Strong (7) | 1 (printed) | 1 (printed) | 2 (buy rule) | 1 (printed) |
| Weakening (3, 1) | -1 (printed) | 1 (our reading) | 1 (printed) | 1 (printed) |
| Emerging (6) | -1 (printed) | 1 (our reading) | 2 (printed) | 1 (buy rule) |
| Weak (4, 0) | -1 (printed) | -1 (printed) | -1 (printed) | -1 (printed) |
g := market.GTE(0).Add(market.GTE(1)).Add(market.GTE(4))
idx := g.Mul(8).Add(stock).MaskNonFinite(market)
nan := math.NaN()
table := [32]float64{
-1, -1, nan, -1, -1, nan, -1, 1,
-1, 1, nan, 1, -1, nan, 1, 1,
-1, 1, nan, 1, -1, nan, 2, 2,
-1, 1, nan, 1, -1, nan, 1, 1,
}
gate := idx.Map(func(k float64) float64 {
if math.IsNaN(k) {
return k
}
return table[int(k)]
})- Inputs: the market code of
s2ZahorchakMarketand the stock code ofs2ZahorchakStock, of one length. - First valid index: the later of the two codes’ (40 weekly); NaN before it and wherever either code is NaN. The impossible stock codes 2 and 5 read NaN.
- Anchors: a buy is allowed only in an early bull and only for Strong and Emerging stocks, the cells marked 2; Weak is -1 in every column. The small test group reaches all 24 cells.
- Traps: a bull market (4) allows no new buy, since Table A says buy only at 1 to 3; the buy rule also sets Strong in an early bull, where Table B prints only “Hold”, and Emerging in a bull, where it prints “Buy in early Bull”. Weakening and Emerging in an uncertain market are our reading of cells the tables leave open. The gate holds no position: whether a stock is held, and Zahorchak’s shopping list of 25 to 100 cyclical stocks, are the caller’s.
- Evidence: Morris summarises the process (“Keyword here is their”: a stock’s own trend says when to sell it) and reports no test. Evidence, not a reference.
- Pinned by
TestRecipeS2ZahorchakGate.
Merrill’s rating of the moving-average relativity
Arthur Merrill compared a stock’s weekly close with his 5- and 19-week exponential averages, a three-way comparison “developed by analyst Michael Zahorchak” (“More trend detection”, Stocks & Commodities V6:6, 1988), and later (“Stock Selection”, Stocks & Commodities V10:6, 1992, pp. 239-242) wrote of Zahorchak, “With his help, I fitted his guidance rules into a rating scale”: ++ for C > 5 > 19, + for 5 > C > 19 and C > 19 > 5, - for 5 > 19 > C and 19 > C > 5, and – for 19 > 5 > C. s2MerrillRating writes the ordering as a code, as Table B does, and reads the rating from a table.
e5 := c.XAverage(fast)
e19 := c.XAverage(slow)
code := c.GT(e5).Mul(4).Add(c.GT(e19).Mul(2)).Add(e5.GT(e19)).SetN(slow-1, math.NaN()).MaskNonFinite(e19)
nan := math.NaN()
merrill := [8]float64{-2, -1, nan, 1, -1, nan, 1, 2}
rating := code.Map(func(k float64) float64 {
if math.IsNaN(k) {
return k
}
return merrill[int(k)]
})- Inputs: weekly closes
c;fastandslow(5 and 19;XAverage’s 2/(n+1) gives smoothing constants 1/3 and 1/10, and Merrill’s own definition is in a column of his not read here). The ratings are 2, 1, -1 and -2 for ++, +, - and –. - First valid index: slow - 1 (18). NaN before it and from the first non-finite close on, since an exponential average does not recover from one (on the test path, from bar 800 to the end).
- Anchors: on strict orderings the rating is (S + sign S)/2 for S the sum of the signs of c - e5, c - e19 and e5 - e19, on every valid bar of the test path; there the ratings from bar 18 are 2 on 334 bars, 1 on 103, -1 on 88 and -2 on 257. Codes 2 and 5 cannot occur. Merrill groups the orderings differently from Table B: C > 19 > 5 is + where Table B’s same ordering is Emerging, and 5 > 19 > C is - where Table B’s is Weakening.
- Traps: with a tie, S can be even and the identity gives a half; the table sends a tie to the lower rating, so a flat history reads -2. The averages start from a simple-average seed and remember it, so the rating depends on where the history starts: on the test path, starting 400 bars later changes 2 ratings, the later of them 40 bars after the new start, where the postures above are start-invariant.
- Variant: Merrill’s 1988 three-way reading, bullish for C > 5 > 19 and bearish for C < 5 < 19:
code.EQ(7).Sub(code.EQ(0)).Add(code.Mul(0)). - Evidence: Merrill reports no test of the scale on its own. His “Moving Average Crossovers” (Stocks & Commodities V10:8, 1992), on the weekly Dow and its 4-, 13-, 26- and 52-week exponential averages, found the best two relations right 61.5% and 62.3% of the time over the next 13 weeks in 1980-91 and the rest below 60%, with 1968-79 near chance (“The odds for success aren’t high; they rarely exceed six to four”), and concluded “I’ll watch these moving average relationships but I won’t give them too much weight”. Evidence, not a reference.
- Pinned by
TestRecipeS2MerrillRating; runnable exampleExampleSeries_XAverage_merrillRating.
The Zahorchak Measure (not provided)
Morris’s Zahorchak Measure (StockCharts !BINYZMD daily and !BINYZMDW weekly, from -15 to +15, and its variant from -10 to +10) scores the 5-, 15- and 40-week averages of the NYSE Composite and of the advance-decline line, but its point rules are not published. Morris, answering a reader (“Questions from Readers”, StockCharts, October 2015): “The book did not include an indicator. The Zahorchak Measure is my attempt to recreate via an indicator his method.” His charts show values of both parities and a one-week step of -9, which a sum of fifteen comparisons scoring +1 or -1 cannot give, so the rules cannot be read off the description. No recipe is given; the market posture above is the published method it recreates.
Three trend-quality gates from stock-selection articles, each with in-sample evidence on lists of index members, open to survivorship bias. Values are NaN before their first valid index, where a window would read an average’s pass-through or a warm-up; flags and scores read 0 there. Prices are positive and finite, volumes non-negative and finite, and lengths are in bars (weekly bars for the star rating); series are paired by position, so the caller puts the index closes on the stock’s calendar, aligned by timestamp, before they reach nseries.
Stiffness (Katsanos)
Markos Katsanos (“The Stiffness Indicator”, Stocks & Commodities V36:12, November 2018, pp. 9-13) counts “the number of times price closed above the MA during the indicator period”, with “a volatility threshold that excludes minimal penetrations of less than 0.2 standard deviations”: “MA2 = MA(C,100)-0.2StDev(C,100); P = Sum(C>MA2,60); Stiffness = P100/60”. His AmiBroker code smooths the share with EMA(STIF,3), which AmiBroker seeds with a simple average of the first valid values. t6Stiffness returns the printed share in his order and that smoothing, trimmed before XAverage so that its seed skips the warm-up.
raw := c.GT(c.Bollinger(a, -k)).Sum(p).Mul(100).Div(p)
stif := raw.SetN(a+p-2, math.NaN())
stiffness := raw.Mul(0.0).Add(raw.Window(-(a + p - 2)).XAverage(m)).SetN(a+p+m-3, math.NaN())- Inputs: closes, a, p and m (100, 60 and 3) and k (0.2);
Bollingeruses the population deviation, as AmiBroker’s StDev does. - First valid index: a + p - 2 for
stif(158) and a + p + m - 3 forstiffness(160), NaN before. On bars 0 to a - 2 the band is the close itself (Averagepasses it through and the deviation is 0), so the flag reads 0 there. - Anchors:
stifis the count of closes above the band times 100 over p, bit for bit;stiffnessequals AmiBroker’s EMA seeded on the first m shares, bit for bit at m = 3, whose constant 0.5 makes every product exact; a constant share of 90 smooths to 90 and does not cross over 90; and for his June 2018 coefficient,c.LT(ma).Sum(63).LTE(7)equalsc.GT(ma).Sum(63).GTE(56)when no close equals the average: 56 of 63 is 88.888…, so the dossier’s share level 88.9 misses it. - Traps: the dossier’s
Average(60).Mul(100)rounds twice and differs in the last bits; its full-seriesXAverage(3)seeds on the warm-up and reads 0.42 off at bar 160 and 4e-7 at bar 180 on the synthetic path; his printed index rule is strict where his code tests “>=”, and the platform ports depart (TradeStation’s scales by the average’s length, AIQ’s exits below 90 and uses 2 deviations, TradersStudio’s exits below 90, takes a sample deviation over the 60-bar period and prints both 2 and 0.2 as its deviation count, MetaStock’s exits after 21 bars). - Variant: his system,
buy := stiffness.CrossesAboveS(90.0).Mul(mkt)andsell := stiffness.CrossesBelowS(50.0), withe := spy.XAverage(100).SetN(99, math.NaN())andmkt := e.GTE(e.Shift(2)), andc.Position(buy.Shift(1), sell.Shift(1), 85): fills at the next open and his “Bars since entry >= 84”. - Variant: his June 2018 stiffness coefficient,
c.LT(c.Average(100)).Sum(63).LTE(7).SetN(161, math.NaN()), which counts the bars below the average, not the crossings. - Evidence: his Figure 4 (S&P 500 stocks over ten years to 6 July 2018): 1,030 trades, 63.4% profitable and a profit factor of 2.6, against buy and hold of SPY, with parameters he optimised. Evidence, not a reference.
- Pinned by
TestRecipeT6Stiffness; runnable exampleExampleSeries_Bollinger_stiffness.
Technical stock rating (Katsanos)
Markos Katsanos (“A Technical Method For Rating Stocks”, Stocks & Commodities V36:7, June 2018, pp. 9-14) scores five conditions: the volume flow indicator above zero, the close above its 100-day average, that average above its value four days earlier, his stiffness coefficient and the index’s 100-day EMA “either flat or pointing up”. He found the system “performed best when all conditions were assigned a weight of 1 except for the last condition, which earned a weight of 2”, and used “a rating threshold of greater or equal to 5”. t6StockRating follows the operators of his AmiBroker code (<=7 and >=), with the shipped VolumeFlowIndicator as his VFI.
vfi := c.VolumeFlowIndicator(h, l, c, v, 130, 0.2, 2.5)
ma := c.Average(100)
c1 := vfi.GT(0.0)
c2 := c.GT(ma)
c3 := ma.GT(ma.Shift(4))
c4 := c.LT(ma).Sum(63).LTE(7)
e := spy.XAverage(100).SetN(99, math.NaN())
c5 := e.GTE(e.Shift(2))
score := c1.Add(c2).Add(c3).Add(c4).Add(c5.Mul(2)).SetN(261, math.NaN())
buy := score.GTE(5)- Inputs: highs, lows, closes and volumes of the stock and the index closes
spyon the stock’s calendar; the lengths and levels are his. - First valid index: 261 for
score, the volume flow indicator’s 2n + 1 at n = 130, NaN before;buyreads 0 there. His code forces the indicator to 0 through bar 268 (BarIndex()>268), so the package’s indicator can read above 0 on bars 261 to 268 where his reads 0, and the two scores differ there. - Anchors: a score of 5 or more is the index gate and at least three of the four stock terms, on every bar (all 32 combinations); the index gate, masked to bar 99, reads 0 to bar 100 and equals his
EMA(SPY,100)>=Ref(EMA(SPY,100),-2)after, where an unmasked one fires in the warm-up. - Traps: his text says “less than seven times” and prints the index rule strict, where his code tests
<=7and>=, and it counts the bars below the average, not crossings; the ports depart (Wealth-Lab buys only on a score above 5, NeuroShell weights the stiffness term 2 and the index 1); a note in the Excel port gives a 30-day hold where his code holds 21 bars. - Variant: his code’s start,
vfi.SetN(269, 0)beforeGT(0.0). - Variant: his 21-bar hold with fills at the next open,
c.Position(buy.Shift(1), nil, 22)if AmiBroker’s N-bar stop exits at the open after the 21st bar,c.Position(buy.Shift(1), nil, 21)if on it; the article does not say which. - Evidence: his Figure 2 (S&P 500 stocks, 2 January 2008 to 2 January 2018, no costs): holding a month after a rating of 5 or more gave 29,093 trades, a profit factor of 1.64 and a maximum drawdown of 11.7%, against 1.35 and 53.4% without the rating. Evidence, not a reference.
- Pinned by
TestRecipeT6StockRating.
Technical star rating (D’Errico)
Domenico D’Errico (“Build Your Own Technical Rating”, Stocks & Commodities V35:8, July 2017, pp. 42-46) combines a “One-year linear regression slope”, “12-week higher highs” and “12-week higher lows”, “assigning two stars to slope, one star to highs, and two stars to lows, for a maximum of five stars”, and trades “Buy if the stock rating is above 2.5 stars, sell if it’s below 2.5” on weekly bars. t6StarRating reads the higher highs and lows quarter over quarter (his Figure 1’s “Previous Quarter” and “Current Quarter”) and the slope over 40 weeks, his tested setting.
hh := h.Highest(b)
ll := l.Lowest(b)
raw := c.Slope(sl).GT(0.0).Mul(2).Add(hh.GT(hh.Shift(b))).Add(ll.GT(ll.Shift(b)).Mul(2)).
SetN(max(sl-1, b+b-1), math.NaN())
long := raw.GT(2.5)- Inputs: weekly highs, lows and closes (the caller builds the weeks); sl and b (40 and 12).
- First valid index: max(sl - 1, 2b - 1) for
raw(39 at the defaults), NaN before;longreads 0 there. Unmasked,ll.Shift(b)pads 0, so the higher-lows flag is 1 on bars 0 to b - 1. - Anchors: with the weights a permutation of 1, 2 and 2 (his Figure 6’s 2-1-2, 1-2-2 and 2-2-1) a rating above 2.5 is at least two of the three flags, on every bar: one flag scores at most 2 and any two at least 3; the flags equal loops of their definitions.
- Traps: since the three weightings give one raw rule, his Figure 6’s three trade counts (707, 854 and 743) show that his published rating is smoothed, which he does not say; his Figure 7 (settings 1-2-2, Simulation 2’s weighting) shows 850 or so trades at a trigger of 5, which suggests an inclusive buy; Figure 6 prints a drawdown of -197291 where its own ratio needs about 19,729.
- Variant: a smoothed rating,
raw.Average(10).Hysteresis(2.5, 2.5), valid from bar max(sl - 1, 2b - 1) + 9: the 10-bar simple average is an assumption from a digitisation of his Figure 4 (about 11 weeks) and his Figure 9’s 4.9 for CAT, and the latch holds a tie at 2.5. - Variant: the current bar against the previous quarter,
h.GT(hh.Shift(b))andl.GT(ll.Shift(b)). - Evidence: his Figure 5 (S&P 100 stocks, January 2005 to December 2016, weekly): 707 trades and 87,553 dollars with a maximum drawdown of 19,897, against buy and hold’s 88,696 and 76,315. Evidence, not a reference.
- Pinned by
TestRecipeT6StarRating.
Markov Models
State codes
The Markov methods read a state series. For the counting methods (MarkovTransition, MarkovNext, MarkovPersistence and MarkovCount) a valid state is a whole number from 0 to k-1, decided on the float before any conversion to an integer: NaN, the infinities, fractions such as 0.5 and values outside 0 to k-1 are invalid bars, and -0 is state 0. UpDown(1) gives 0 for flat, 1 for down and 2 for up, so its codes fit k = 3; UpDown(2) and UpDown(3) fit k = 11 and 43. UpDownSum and RegimeDFA use +1 for up and -1 for down (RegimeDFA’s +1 is its trending reading and -1 its mean-reverting one), so add 1 before counting their codes. Builders turn missing data into valid states (UpDown gives flat on a NaN close), so mask what should not count with SetN or If.
Caps
A method that counts transitions or holds a k by k table accepts k from 1 to 98. Methods with cubic work per bar accept k up to 16 (MarkovStationary).
Persistence
Three different quantities share the word. MarkovPersistence is the one-step stay probability of the current state over a rolling window, and 1 minus it is that state’s switch rate. The pooled, drift-adjusted persistence of Semenov’s sign test belongs to a later tranche of this category. The long-memory persistence that DFAAlpha, RegimeDFA and Hurst estimate describes how slowly a series’ fluctuations decay, not whether one state follows another. On a two-state series the share of stays in a window, (n_UU + n_DD)/n, equals (m_UP(U|U) + m_DP(D|D))/n, where m_U and m_D count the transitions leaving up and down: a pooled figure that weights the two diagonal cells by their row counts.
MarkovAhead
func (s Series) MarkovAhead(n, k, h, to int) Series
MarkovAhead returns the Markov-implied probability that a state series will be in state to h bars ahead, from the current state and the transition matrix of the trailing n transitions.
The receiver z is the state series, and the window of bar t holds the n transitions (z[u-1], z[u]) for u = t-n+1 to t, from which P(i, j) is the share of the transitions leaving state i that enter state j, 0 on an empty row; with i the state of z[t], the output is entry to of row i of the h-th power of P, read at bar t as a forecast for bar t+h. n counts transitions, so the window spans the n+1 bars t-n to t, and the rows and columns of P read as in MarkovTransition, row i the state left and column j the state entered. The value at bar t is a forecast for bar t+h, to compare with z[t+h] when that bar arrives, not a value to shift back.
A bar holds state j when its value is the whole number j from 0 to k-1, decided on the float before any conversion to an integer; -0 is state 0, and NaN, an infinity, a fraction, a negative value or a value of k or more is not a state. k runs from 1 to 98. UpDownSum(1) and RegimeDFA use +1 for up, so add 1 to their values first.
h is the forecast horizon in bars, from 1 to 1000, compared by value and independent of the length of z: h = 50 on a 40-bar series is valid and gives the first 40 bars of the longer run. For horizons beyond 1000 use MarkovStationary, the long-run share, which needs no horizon; it accepts k up to 16.
v starts as the unit vector of the current state and takes up to h steps: each step maps v to y, with y[j] the sum over i ascending of float64(v[i]*P[i, j]), every product rounded on its own before the addition, rows with v[i] = 0 and cells with P[i, j] = 0 skipped. The output is min(v[to], 1), since rounding can lift an entry just above 1. A step that leaves v unchanged bit for bit ends the loop, as every later step would repeat it.
When the window holds no transition from the current state, the output is 0 for every to and h. The row is not replaced by a stay, and MarkovCount(n, k, i) is 0 exactly there, so the selection sum over i of z.EQ(i).Mul(z.MarkovCount(n, k, i)) tells an empty current row, where the sum is 0, from a state to that the current state cannot reach in h steps, where it is positive. On a non-empty row the outputs over to sum to within (h+1)(k+1)*2^-53 of 1. At k = 1 the output is 1 on every valid window. A window whose reachable states alternate, as 0 1 0 1, flips between 0 and 1 with the parity of h and does not converge.
The first valid index is n and the minimum length is n+1. Bars 0 to n-1 are +0 whatever z holds there, NaN and infinities included, as the warm-up takes precedence over an invalid state. The warm-up reads 0, not NaN, which an unmasked rule reads as a state unreachable h bars ahead, so mask the first n bars when that matters.
The method is window-local: an invalid state at bar p (NaN, an infinity, a fraction, a negative value or k or more) gives NaN on [max(p, n), p+n] and recovers at bar p+n+1 with the bits of the run without it. An invalid current state z[t] is such a bar. Every output is +0, NaN or a value in (0, 1], never -0, and the output on a prefix of z is the prefix of the output.
The output is causal when the states are: compare it with z[t+h] and do not shift it back. States defined with hindsight are not, as for MarkovNext, and a state that reads bars after t leaks them into the forecast.
No source shows a trading edge. Arrington (1993) counts the direction transitions of one whole sample and iterates the matrix to its equilibrium vector, which he reads as tomorrow’s probability too; it is the long-run share of up, down and flat days, while tomorrow’s probability is the h = 1 value, which, as his own caution says, depends on the current state. Morley (2022) applies a stated matrix twice to a start vector for the two-step forecast. Direction chains collapse to the long-run share by h = 2 or 3: on the 2023 AAPL closes at n = 20 the median gap of the up direction from MarkovDirStationary over the 179 bars from n+1 on is below 0.01 at h = 2, 0.0087 measured, and 0.0017 at h = 3. Sticky regime states keep a gap for longer, and there the h-step value also departs from the directly counted lag-h frequency, as it does on a short window of a first-order chain, so the gap alone does not show that such regimes are not first-order Markov.
The cost is at most O(h*k^2) per bar: a step visits only the rows of the states the vector occupies, and the loop stops at the first step that changes no bit, so a window whose current state only stays stops at the first step and a mixing one once the vector settles to the last bit, while a periodic window, which never settles, takes all h steps. A call allocates at most four times, for the result, the two counter tables of the window and one float buffer that holds P and the two vectors; small tables may live on the stack.
Invalid parameters give len(z) zeros, decided before any allocation: n below 1 or above len(z)-1, k below 1 or above 98, to outside 0 to k-1, or h below 1 or above 1000; a nil or empty receiver gives an empty Series and a one-bar receiver one zero.
This method is listed under “Compositions” in the “Markov Models” category. Its natural pair is the directly counted lag-h transition frequency: a gap between the two at h above 1 that the noise of the window does not explain says that the chain is not first-order Markov.
Verification: the Python reference and the Julia reference give the bits of the fixtures and the method agrees with them bit for bit. At h = 1 the output equals MarkovNext(n, k, to) at every bar from n on, NaN bars included, and the selection sum over i of z.EQ(i).Mul(C(i, to)), where C(i, j) stands for z.EQ(j).Mul(z.EQ(i).Shift(1)).Sum(n).Ratio(z.EQ(i).Shift(1).Sum(n)); at h = 2 it equals the composition, the sum over i of z.EQ(i) times the sum over m of C(i, m).Mul(C(m, to)), clamped to [0, 1]; at h = 1000 it is within the Dobrushin bound of the long-run share of the window, which MarkovStationary gives exactly.
MarkovChiSquare
func (s Series) MarkovChiSquare(n, k int, lag ...int) Series
MarkovChiSquare returns the rolling Pearson chi-square statistic of the transition table of a state series of integer codes 0 to k-1, over the last n pairs of states lag bars apart.
For a state series z, the window of bar t holds the n pairs (z[u-lag], z[u]) for u = t-n+1 to t. Each pair counts in the row of its earlier state and the column of its later state of a k by k table. With O a cell’s count and R and C its row and column totals, the output is the sum of (On - RC)^2/(nRC) over occupied rows and columns, the terms added in row-major order from +0, with On - RC formed exactly in int64.
For codes i and j, with R = z.EQ(i).Shift(lag).Sum(n), C = z.EQ(j).Sum(n), O = z.EQ(j).Mul(z.EQ(i).Shift(lag)).Sum(n) and q = O.Mul(n).Sub(R.Mul(C)), the output equals the row-major sum of q.Mul(q).Div(R.Mul(n).Mul(C)) over the occupied rows and columns, bit for bit, at every bar from n+lag-1 on whose pairs are all valid.
A bar holds state j when its value is a whole number j from 0 to k-1, decided on the float before any conversion to an integer: NaN, the infinities, fractions, negative values and values of k or more are invalid states, and -0 is state 0. k runs from 1 to 98. The codes of UpDown(1), 0 for flat, 1 for down and 2 for up, are states at k = 3; UpDownSum and RegimeDFA use +1 for up, and a negative code is an invalid state, so shift such codes into 0 to k-1 first. Mask what should not count: z.SetN(1, math.NaN()) marks the first bar of UpDown(1), which has no earlier price.
The first valid index is n+lag-1 and the minimum length is n+lag. The warm-up reads 0, not NaN, so an unmasked rule reads it as independence. Bars 0 to n+lag-2 are +0, and n = len(z)-lag gives one output, at the last bar. An n above len(z)-lag gives only warm-up zeros.
lag is the distance back to the earlier state: each pair is (z[u-lag], z[u]), the sign of Shift(lag), so lag 1 pairs consecutive bars. lag is optional: omitted, it is 1; given, it must be exactly one element from 1 to len(z)-1, and two or more elements give zeros.
The method is window-local: an invalid state at bar p gives NaN on [p, p+n-1] and on [p+lag, p+lag+n-1], from bar n+lag-1 on and clipped to the last bar, because bar p is the later end of pair p and the earlier end of pair p+lag. When lag is at most n the spans join into [p, p+n+lag-1], which is [p, p+n] at lag 1; when lag is above n they are disjoint and the bars between recover. Several invalid bars give the union of their spans. The warm-up zeros take precedence over NaN. Bar t reads only bars up to t, so the output on a prefix of z is the prefix of the output, and dropping the first d bars leaves every bar from d+n+lag-1 on unchanged.
The codes are given, so there is no tie rule; SignPhi, a two-series phi that excludes tied changes, is the price-level contrast.
The output is +0 when only one row or one column is occupied: at n = 1, at k = 1, on a constant window and on a window whose pairs all fall in one cell. Otherwise it is finite and at least +0, and empty rows and columns are skipped, so it depends only on the occupied part of the table.
With a occupied rows and b occupied columns the statistic has (a-1)(b-1) degrees of freedom; the package has no p-value for it. Some state series have structural zeros, transitions that cannot occur or must occur by construction, and some carry the overlap of their own windows: UpDown codes over two or more bars, streak and run-length states, alternating events, the side of a moving average and quantiles of a smoothed series give large values for any input, a random walk included, which are not evidence of dependence; McKallip concedes that his expected counts do not work for embedded sequences, whose diagonal is zero. The usual guideline is n >= 5k^2, with k the number of occupied states, documented and not enforced. Rolling windows overlap, so successive bars are not independent tests.
No source shows a trading edge from these statistics. Corrected to Pearson’s contingency test, the published whole-sample tables mostly show no first-order dependence: soymeal gives 0.612 and Sherry’s autos 0.0976, each with one degree of freedom, and Sherry’s two daily tables 5.72 and 10.36 with four; McKallip’s large values come from chart patterns labelled with hindsight.
Cost is O(k*k) per bar for the statistic, over the cells of the table, while the window’s integer counters move in constant time; a call allocates the result, the counter tables and a column table. An invalid n, k or lag gives len(z) zeros, and a nil or empty receiver gives an empty Series. n is invalid above 3,000,000,000, a cap that keeps the integer products within int64.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference and a Julia reference recount every window and agree with this method bit for bit, as does the row-major sum of q.Mul(q).Div(R.Mul(n).Mul(C)) over the occupied rows and columns.
MarkovCount
func (s Series) MarkovCount(n, k, from int) Series
MarkovCount returns the number of valid transitions leaving state from among the last n transitions of a state series whose valid values are the integer codes 0 to k-1.
The receiver z is the state series, and the window of bar t holds the n transitions (z[u-1], z[u]) for u = t-n+1 to t. So n counts transitions, not bars, and the window spans the n+1 bars t-n to t. Each transition counts in the row of its earlier state, from, and the column of its later state, to. The output at bar t is m, the number of transitions in the window whose row is from: the support of the row, which MarkovTransition divides by for every to.
A bar holds state j when its value is a whole number j from 0 to k-1, decided on the float before any conversion to an integer: NaN, the infinities, fractions, negative values and values of k or more are invalid states, and -0 is state 0. k runs from 1 to 98, so the codes of UpDown(1), UpDown(2) and UpDown(3) fit, at k = 3, 11 and 43, and those of UpDown(4) do not. UpDown(1) gives 0 for flat, 1 for down and 2 for up, but UpDownSum and RegimeDFA use +1 for up (trending, for RegimeDFA), so add 1 to their values first; a value that is then negative or fractional is still invalid. The parameter from must lie in [0, k).
The first valid index is n and the minimum length is n+1. The warm-up reads 0, not NaN, so an unmasked rule reads it as a state that never transitions or stays. Bars 0 to n-1 are +0 whatever z holds there.
The method is window-local: an invalid state at bar p gives NaN on [max(p, n), p+n], clipped to the last bar, since bar p is the later end of transition p and the earlier end of transition p+1, and the output recovers at bar p+n+1; several invalid bars give the union of their spans. The warm-up zeros take precedence over NaN, so an invalid bar inside the first window leaves the bars before n at 0, and the output on a prefix of z is the prefix of the output. Mask what should not count: z.SetN(1, math.NaN()) marks the first bar of UpDown(1), which has no earlier bar to compare with, and If can set NaN on the bars of a data gap, so that no window counts a transition across the gap.
The count is the detector of the empty row: it is 0 exactly when the window holds no transition from state from, where MarkovTransition and MarkovNext output 0 without having observed anything, so it tells an empty row from an observed 0. Empty rows are frequent at small n or at large k. For MarkovNext, and for the stay probability of the current state, read the count at the current state i, as the sum over i of z.EQ(i).Mul(z.MarkovCount(n, k, i)). The count is a whole number from 0 to n stored as float64, NaN on the footprint, +0 before bar n; it takes no alpha. Summed over every from, the counts give n, and at k = 1 the count is n.
McKallip (1986) and Arrington (1993) put from in the rows, as here. Sherry puts the later state in the rows, Trongone (2011) puts the from-states in the columns, and Morley (2022) states the transpose, as MarkovTransition explains.
Bar t reads z[t-n] to z[t] only, so the output is causal for point-in-time states. States defined with hindsight are not: McKallip’s chart patterns are labelled after they complete, Sherry cuts terciles over the whole sample, and Alexander, Scherer and Thompson re-cluster the whole history each month.
The sources estimate one table over the whole sample, and none shows a trading edge from a rolling transition probability. Gustafson’s share of up days after an up day is 513/1016 = 0.505, and Pearson chi-square re-tests of two of Sherry’s tables give 0.612 and 0.0976. At n = 50 a two-state row holds about 25 transitions, so a probability has a standard error near 0.1.
The method costs O(1) per bar after clearing its tables in O(k*k); it allocates the result and two counter tables. An invalid parameter (n outside 1 to len(z)-1, k outside 1 to 98 or from outside [0, k)) gives len(z) zeros, and a nil or empty receiver gives an empty Series. The current state’s stay probability has its own method; see the Markov Models introduction.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference (integer counters and exact fractions) and a Julia reference (exact rationals) agree with it bit for bit, and so do the compositions z.EQ(from).Shift(1).Sum(n) and the sum over j of z.EQ(j).Mul(z.EQ(from).Shift(1)).Sum(n), at every bar from n on whose window holds only valid states.
MarkovCramerV
func (s Series) MarkovCramerV(n, k int, lag ...int) Series
MarkovCramerV returns the rolling Cramer’s V of the transition table of a state series of integer codes 0 to k-1, over the last n pairs of states lag bars apart.
For a state series z, the window of bar t holds the n pairs (z[u-lag], z[u]) for u = t-n+1 to t. Each pair counts in the row of its earlier state and the column of its later state of a k by k table. With chi2 its Pearson chi-square statistic, the output is sqrt(chi2/(n*(m-1))), m the smaller number of occupied rows and columns, clamped to 1 by math.Min, with n*(m-1) formed exactly in int64.
With chi2 the row-major sum of q.Mul(q).Div(R.Mul(n).Mul(C)) over the occupied rows and columns, as for MarkovChiSquare, and m = a.Sub(a.Sub(b).Max(0)), with a and b the sums of R[i].GT(0) and C[j].GT(0) over the codes, the output equals chi2.Div(m.Sub(1).Mul(n)).Sqrt().Min(1), bit for bit, at every bar from n+lag-1 on whose pairs are all valid.
A bar holds state j when its value is a whole number j from 0 to k-1, decided on the float before any conversion to an integer: NaN, the infinities, fractions, negative values and values of k or more are invalid states, and -0 is state 0. k runs from 1 to 98. The codes of UpDown(1), 0 for flat, 1 for down and 2 for up, are states at k = 3; UpDownSum and RegimeDFA use +1 for up, and a negative code is an invalid state, so shift such codes into 0 to k-1 first. Mask what should not count: z.SetN(1, math.NaN()) marks the first bar of UpDown(1), which has no earlier price.
The first valid index is n+lag-1 and the minimum length is n+lag. The warm-up reads 0, not NaN, so an unmasked rule reads it as independence. Bars 0 to n+lag-2 are +0, and n = len(z)-lag gives one output, at the last bar. An n above len(z)-lag gives only warm-up zeros.
lag is the distance back to the earlier state: each pair is (z[u-lag], z[u]), the sign of Shift(lag), so lag 1 pairs consecutive bars. lag is optional: omitted, it is 1; given, it must be exactly one element from 1 to len(z)-1, and two or more elements give zeros.
The method is window-local: an invalid state at bar p gives NaN on [p, p+n-1] and on [p+lag, p+lag+n-1], from bar n+lag-1 on and clipped to the last bar, because bar p is the later end of pair p and the earlier end of pair p+lag. When lag is at most n the spans join into [p, p+n+lag-1], which is [p, p+n] at lag 1; when lag is above n they are disjoint and the bars between recover. Several invalid bars give the union of their spans. The warm-up zeros take precedence over NaN. Bar t reads only bars up to t, so the output on a prefix of z is the prefix of the output, and dropping the first d bars leaves every bar from d+n+lag-1 on unchanged.
The codes are given, so there is no tie rule; SignPhi, a two-series phi that excludes tied changes, is the price-level contrast.
The output is +0 when m is at most 1: at n = 1, at k = 1, on a constant window and on a window whose pairs all fall in one row or one column. Otherwise math.Min clamps it to 1, so it lies in [0, 1]. The six-state cycle 0, 1, 2, 3, 4, 5, 0 at n = 6 and k = 6 gives chi2 30.000000000000014 and a raw quotient whose square root is 1.0000000000000002, which the clamp turns into exactly 1, while the cycle 0, 1, 2, 0, 1, 2, 0 at n = 6 and k = 4 shows that complete association can read 0.9999999999999999.
V saturates on small windows: with three independent, equally likely states it is exactly 1 in 4/9 of the windows at n = 2 and in 2/9 at n = 3, where the occupied table is a partial permutation. m counts the occupied states, not the k declared, so V jumps when a state enters or leaves the window. Some state series have structural zeros, transitions that cannot occur or must occur by construction, and some carry the overlap of their own windows: UpDown codes over two or more bars, streak and run-length states, alternating events, the side of a moving average and quantiles of a smoothed series give large values for any input, a random walk included, which are not evidence of dependence; McKallip concedes that his expected counts do not work for embedded sequences, whose diagonal is zero. The usual guideline is n >= 5*k^2, with k the number of occupied states, documented and not enforced. Rolling windows overlap, so successive bars are not independent tests.
No source shows a trading edge from these statistics. Corrected to Pearson’s contingency test, the published whole-sample tables mostly show no first-order dependence: soymeal gives 0.612 and Sherry’s autos 0.0976, each with one degree of freedom, and Sherry’s two daily tables 5.72 and 10.36 with four; McKallip’s large values come from chart patterns labelled with hindsight.
Cost is O(k*k) per bar for the statistic, over the cells of the table, while the window’s integer counters move in constant time; a call allocates the result, the counter tables and a column table. An invalid n, k or lag gives len(z) zeros, and a nil or empty receiver gives an empty Series. n is invalid above 3,000,000,000, a cap that keeps the integer products within int64.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference and a Julia reference recount every window and agree with this method bit for bit, as does chi2.Div(m.Sub(1).Mul(n)).Sqrt().Min(1) on the composed chi-square.
MarkovDirAhead
func (s Series) MarkovDirAhead(n, h, to int, tolerance ...float64) Series
MarkovDirAhead returns the Markov-implied probability that the price direction h bars ahead is to (0 flat, 1 down, 2 up), from the current direction and the trailing n direction transitions.
It is MarkovAhead with k = 3 on the direction codes of UpDown(1), 0 flat, 1 down and 2 up, where the tolerance is a percentage, as in UpDown. The receiver c holds prices, and the output at bar t is a forecast for the direction of bar t+h, the change from bar t+h-1 to bar t+h, not a value to shift back.
The codes are those of UpDown(1): the change from bar u-1 to bar u is up when it exceeds the band |previous|*tolerance/100, down when it falls below minus that band, and flat inside it, where the tolerance is a percentage, as in UpDown: 0.05 means 0.05%, not 5%. The band is closed, so a change equal to the threshold is flat, and a tolerance of -0 behaves as 0, as does an omitted one. On the 2023 AAPL closes the default tolerance 0 gives one flat change in 199.
With d[u] the direction of change u, from bar u-1 to bar u, the window of bar t holds the n transitions (d[u-1], d[u]) for u = t-n+1 to t, so it reads the n+2 prices of bars t-n-1 to t, and the output is entry to of row d[t] of the h-th power of the matrix of those transitions. h runs from 1 to 1000, compared by value and independent of the length of c. For horizons beyond 1000 use MarkovDirStationary, the long-run share of the direction chain.
The first valid index is n+1 and the minimum length is n+2. Bars 0 to n are +0 whatever the prices, NaN and infinities included: bar n, which MarkovAhead would compute, reads 0 because its window holds the missing direction of bar 0. The warm-up reads 0, not NaN, which an unmasked rule reads as a direction unreachable h bars ahead, so mask the first n+1 bars when that matters.
The method is window-local: a NaN or infinite price at bar p gives NaN on [max(p, n+1), p+n+1] and recovers at bar p+n+2 with the bits of the run without it, while a finite pair of prices whose difference overflows is a direction, not a missing value. Every output is +0, NaN or a value in (0, 1], never -0, and the output on a prefix of c is the prefix of the output.
The output is causal: compare it with the direction of bar t+h and do not shift it back. The codes read only bars t-1 and t, so no state is defined with hindsight.
No source shows a trading edge. Arrington (1993) counts the transitions between up, down and flat days of one whole sample and iterates the matrix to its equilibrium vector, which he reads as tomorrow’s probability too; it is the long-run share of each direction, while tomorrow’s probability is the h = 1 value. Morley (2022) applies a stated matrix twice to a start vector for the two-step forecast. Direction chains collapse to the long-run share by h = 2 or 3: on the 2023 AAPL closes at n = 20 the median gap of the up direction from MarkovDirStationary over the 179 bars from n+1 on is below 0.01 at h = 2 (0.0087 measured) and 0.0017 at h = 3, so beyond the first bar or two the horizon matters little.
The cost is at most O(h) per bar, with k fixed at 3. The early exit of MarkovAhead, which stops at the first step that changes no bit, ends most direction windows long before h: on the 2023 AAPL closes at n = 20 and h = 1000 the median window stops at step 22, while a periodic window takes all h steps. A call allocates at most five times, for the direction codes, the result, the two counter tables of the window and one float buffer; small tables may live on the stack.
Invalid parameters give len(c) zeros, decided before any allocation: n below 1 or above len(c)-1, to outside 0 to 2, h below 1 or above 1000, or a tolerance that is negative, NaN or infinite; only the first tolerance value is read, and a nil or empty receiver gives an empty Series.
This method is listed under “Compositions” in the “Markov Models” category. Its natural pair is the directly counted lag-h direction frequency: a gap between the two at h above 1 that the noise of the window does not explain says that the direction chain is not first-order Markov.
Verification: the Python reference and the Julia reference give the bits of the fixtures and the method agrees with them bit for bit. On the masked codes, the directions of UpDown(1, tol) with NaN wherever either price of the change is not finite, it equals MarkovAhead(n, 3, h, to) at every bar from n+1 on, and through that call the h = 1 and h = 2 selection identities of MarkovAhead hold at the bars whose window holds only valid codes.
MarkovDirChiSquare
func (s Series) MarkovDirChiSquare(n int, tolerance ...float64) Series
MarkovDirChiSquare returns the rolling Pearson chi-square statistic of the flat, down and up price-direction transition table over the last n pairs of consecutive changes.
Change u of a price series c runs from c[u-1] to c[u], for u >= 1, and d[u] is the direction of change u. The window of bar t holds the n pairs of consecutive directions (d[u-1], d[u]) for u = t-n+1 to t, so it spans the n+2 prices c[t-n-1] to c[t]. Each pair counts in the row of its earlier direction and the column of its later direction of a 3 by 3 table. With O a cell’s count and R and C its row and column totals, the output is the sum of (On - RC)^2/(nRC) over occupied rows and columns, the terms added in row-major order from +0, with On - RC formed exactly in int64.
On z := c.UpDown(1, tolerance), with R = z.EQ(i).Shift(1).Sum(n), C = z.EQ(j).Sum(n), O = z.EQ(j).Mul(z.EQ(i).Shift(1)).Sum(n) and q = O.Mul(n).Sub(R.Mul(C)) for codes i and j, the output equals the row-major sum of q.Mul(q).Div(R.Mul(n).Mul(C)) over the occupied rows and columns, bit for bit, at every bar from n+1 on whose prices c[t-n-1] to c[t] are finite. There it also equals c.UpDown(1, tolerance).SetN(1, math.NaN()).MarkovChiSquare(n, 3), the state form on the codes with bar 0 masked, bit for bit.
The codes are those of UpDown(1): change u, from c[u-1] to c[u], is 0 for flat, 1 for down and 2 for up, and the rows and columns run in that order. A change with a NaN or infinite price at either end has no direction.
A change is up when it exceeds the threshold and down when it falls below its negation, exactly as UpDown classifies it in float64: the tolerance is a percentage, as in UpDown; the DirectionalChange family takes fractions (see DirectionalChange). It is compared strictly against |previous|*tolerance/100, multiplied before it is divided, so 0.05 means 0.05%, not 5%, and a change equal to the threshold is flat, the strict crossing rule of the family. tolerance is optional: only its first element is read, and the rest are ignored whatever they hold; omitting it is the same as passing 0, and -0 behaves as 0.
Bar 0 has no earlier price, so the first window of n whole pairs ends at bar n+1. The first valid index is n+1 and the minimum length is n+2. The warm-up reads 0, not NaN, so an unmasked rule reads it as independence. Bars 0 to n are +0, and n = len(c)-1 gives only warm-up zeros.
The method is window-local: a NaN, +Inf or -Inf price at bar p leaves changes p and p+1 without a direction, so the output is NaN on [max(p, n+1), p+n+1], clipped to the last bar, and recovers at bar p+n+2; several bad prices give the union of their spans. The warm-up zeros take precedence over NaN. Bar t reads only bars up to t, so the output on a prefix of c is the prefix of the output, and dropping the first d bars leaves every bar from d+n+1 on unchanged. A -0 price is finite, and -0 against +0 is a flat change.
A flat change is its own state, so a flat band separates quiet bars instead of merging them with the downs as MarkovDirPhi does; SignPhi excludes ties.
The output is +0 when only one row or one column is occupied: at n = 1, on a constant window, on a window whose pairs all fall in one cell and on a window of exact ties at any tolerance. Otherwise it is finite and at least +0, and empty rows and columns are skipped. On a window without a flat change it equals the statistic of the up and down table, up.SetN(1, math.NaN()).MarkovChiSquare(n, 2) with up := c.Delta().GT(0), bit for bit.
The statistic has up to four degrees of freedom, (a-1)(b-1) for a occupied rows and b occupied columns; the package has no p-value for it, which needs the regularised incomplete gamma function. The usual guideline is n >= 5k^2, with k the number of occupied directions, documented and not enforced. Rolling windows overlap, so successive bars are not independent tests.
No source shows a trading edge from these statistics. Corrected to Pearson’s contingency test, the published whole-sample tables mostly show no first-order dependence: soymeal gives 0.612 and Sherry’s autos 0.0976, each with one degree of freedom, and Sherry’s two daily tables 5.72 and 10.36 with four; McKallip’s large values come from chart patterns labelled with hindsight.
Cost is O(1) per bar: the window keeps integer counters and the table has three states. A call allocates the result, the direction series, the counter tables and a column table. An invalid n (outside 1 to len(c)-1, or above 3,000,000,000, a cap that keeps the integer products within int64) or tolerance (a negative, NaN or infinite first element) gives len(c) zeros, and a nil or empty receiver gives an empty Series.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference and a Julia reference recount every window and agree with this method bit for bit, as does the row-major sum of q.Mul(q).Div(R.Mul(n).Mul(C)) over the UpDown(1) codes.
MarkovDirCramerV
func (s Series) MarkovDirCramerV(n int, tolerance ...float64) Series
MarkovDirCramerV returns the rolling Cramer’s V of the flat, down and up price-direction transition table over the last n pairs of consecutive changes, from 0 for no association to 1 for complete association.
Change u of a price series c runs from c[u-1] to c[u], for u >= 1, and d[u] is the direction of change u. The window of bar t holds the n pairs of consecutive directions (d[u-1], d[u]) for u = t-n+1 to t, so it spans the n+2 prices c[t-n-1] to c[t]. Each pair counts in the row of its earlier direction and the column of its later direction of a 3 by 3 table. With chi2 its Pearson chi-square statistic, the output is sqrt(chi2/(n*(m-1))), m the smaller number of occupied rows and columns, clamped to 1 by math.Min, with n*(m-1) formed exactly in int64.
On z := c.UpDown(1, tolerance), with chi2 the row-major sum of q.Mul(q).Div(R.Mul(n).Mul(C)) over the occupied codes, as for the chi-square form, and m = a.Sub(a.Sub(b).Max(0)), with a and b the sums of R[i].GT(0) and C[j].GT(0) over the codes, the output equals chi2.Div(m.Sub(1).Mul(n)).Sqrt().Min(1), bit for bit, at every bar from n+1 on whose prices c[t-n-1] to c[t] are finite. There it also equals c.UpDown(1, tolerance).SetN(1, math.NaN()).MarkovCramerV(n, 3), the state form on the codes with bar 0 masked, bit for bit.
The codes are those of UpDown(1): change u, from c[u-1] to c[u], is 0 for flat, 1 for down and 2 for up, and the rows and columns run in that order. A change with a NaN or infinite price at either end has no direction.
A change is up when it exceeds the threshold and down when it falls below its negation, exactly as UpDown classifies it in float64: the tolerance is a percentage, as in UpDown; the DirectionalChange family takes fractions (see DirectionalChange). It is compared strictly against |previous|*tolerance/100, multiplied before it is divided, so 0.05 means 0.05%, not 5%, and a change equal to the threshold is flat, the strict crossing rule of the family. tolerance is optional: only its first element is read, and the rest are ignored whatever they hold; omitting it is the same as passing 0, and -0 behaves as 0.
Bar 0 has no earlier price, so the first window of n whole pairs ends at bar n+1. The first valid index is n+1 and the minimum length is n+2. The warm-up reads 0, not NaN, so an unmasked rule reads it as independence. Bars 0 to n are +0, and n = len(c)-1 gives only warm-up zeros.
The method is window-local: a NaN, +Inf or -Inf price at bar p leaves changes p and p+1 without a direction, so the output is NaN on [max(p, n+1), p+n+1], clipped to the last bar, and recovers at bar p+n+2; several bad prices give the union of their spans. The warm-up zeros take precedence over NaN. Bar t reads only bars up to t, so the output on a prefix of c is the prefix of the output, and dropping the first d bars leaves every bar from d+n+1 on unchanged. A -0 price is finite, and -0 against +0 is a flat change.
A flat change is its own state, so a flat band separates quiet bars instead of merging them with the downs as MarkovDirPhi does; SignPhi excludes ties.
The output is +0 when m is at most 1: at n = 1, on a constant window, on a window whose pairs all fall in one row or one column and on a window of exact ties at any tolerance. Otherwise math.Min clamps it to 1, so it lies in [0, 1]. Complete association can also read 0.9999999999999999, which the clamp leaves alone, when the chi-square sum rounds below n*(m-1), as the repeating changes flat, down and up do at n = 6. On a window without a flat change it agrees with |MarkovDirPhi(n)| within a few units in the last place, not bit for bit.
V saturates on small windows: with three independent, equally likely states it is exactly 1 in 4/9 of the windows at n = 2 and in 2/9 at n = 3, where the occupied table is a partial permutation. m counts the occupied directions, not three, so V jumps when a direction enters or leaves the window. The usual guideline is n >= 5*k^2, with k the number of occupied directions, documented and not enforced. Rolling windows overlap, so successive bars are not independent tests.
No source shows a trading edge from these statistics. Corrected to Pearson’s contingency test, the published whole-sample tables mostly show no first-order dependence: soymeal gives 0.612 and Sherry’s autos 0.0976, each with one degree of freedom, and Sherry’s two daily tables 5.72 and 10.36 with four; McKallip’s large values come from chart patterns labelled with hindsight.
Cost is O(1) per bar: the window keeps integer counters and the table has three states. A call allocates the result, the direction series, the counter tables and a column table. An invalid n (outside 1 to len(c)-1, or above 3,000,000,000, a cap that keeps the integer products within int64) or tolerance (a negative, NaN or infinite first element) gives len(c) zeros, and a nil or empty receiver gives an empty Series.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference and a Julia reference recount every window and agree with this method bit for bit, as does chi2.Div(m.Sub(1).Mul(n)).Sqrt().Min(1) on the UpDown(1) codes.
MarkovDirDuration
func (s Series) MarkovDirDuration(n, state int, tolerance ...float64) Series
MarkovDirDuration returns the expected total spell length in bars of the given price direction (0 flat, 1 down, 2 up) for the direction chain of the trailing n transitions, counting the current bar.
It is MarkovDuration with k = 3 on the direction codes of UpDown(1), 0 flat, 1 down and 2 up, where the tolerance is a percentage, as in UpDown. With m the number of pairs in the window whose earlier direction is the given one and x the number of those whose later direction differs, the output is m/max(x, 1): m itself, a censored value, when the direction did not change inside the window, and 0 when the row is empty. Since the spell counts the current bar, the remaining life is D - 1. It is the geometric model’s expected length, not the observed run that StateAge and ConsecUp count.
The codes are those of UpDown(1): a change is up, code 2, when it exceeds the threshold |previous|*tolerance/100, multiplied before it is divided, down, code 1, when it is below the negative of that threshold, and flat, code 0, otherwise, so a change equal to the threshold is flat. The tolerance is optional and only its first element is read: 0.05 means 0.05%, not 5%, and -0 behaves as 0. At tolerance 0 flat changes are rare on prices quoted to several decimals, one flat change in 199 on the 2023 AAPL closes.
With d[u] the direction of change u, from c[u-1] to c[u], the window of bar t holds the n pairs (d[u-1], d[u]) for u = t-n+1 to t, over the n+2 prices c[t-n-1] to c[t]; m is the row sum of the given direction and x that row sum less its diagonal cell. A NaN or infinite price leaves both changes that touch it without a direction.
The first valid index is n+1 and the minimum length is n+2. Bars 0 to n are +0 whatever the prices. The warm-up reads 0, not NaN.
The method is window-local: the output at bar t depends only on the prices c[t-n-1] to c[t] and on the parameters, and the output on a prefix of c is the prefix of the output. A NaN or infinite price at bar p reads NaN on [max(p, n+1), p+n+1], clipped to the last bar, and the output recovers at bar p+n+2; several such bars give the union of their footprints. Every output is +0, NaN or positive, never -0.
The sources treat the expected spell length as a whole-sample figure of a fitted chain (Graflund; Giner and Zakamulin; Baker and Arnold), and none of them shows a trading edge from it. The cost is O(1) per bar after the counters are cleared. Invalid parameters, n outside 1 to len(c)-1, a state outside 0 to 2 or a negative, NaN or infinite tolerance, give len(c) zeros, and a nil or empty receiver gives an empty Series. A call allocates the result, the direction series and the window’s two counter tables.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: every output is the correctly rounded ratio of two window counts and equals the composition ePrev.Sum(n).Ratio(ePrev.Mul(e.Sub(1.0).Mul(-1.0)).Sum(n).Max(1.0)) with e := c.UpDown(1, tolerance).EQ(state) and ePrev := e.Shift(1) bit for bit on every bar from n+1 on finite prices, and the Python reference and the Julia reference bit for bit on every bar.
MarkovDirNext
func (s Series) MarkovDirNext(n, to int, tolerance ...float64) Series
MarkovDirNext returns the rolling estimate of the probability that the next price change is in direction to, given the direction of the current change, over the last n pairs of consecutive changes.
The codes are those of UpDown(1): change u, from c[u-1] to c[u], is 0 for flat, 1 for down and 2 for up. UpDownSum and RegimeDFA use +1 for up, so a caller who passes 1 for up gets the down row. The parameter to must lie in [0, 3); the current direction is that of the last change, from c[t-1] to c[t]. A change is up when it exceeds the threshold and down when it falls below its negation, exactly as UpDown classifies it in float64: the tolerance is a percentage, as in UpDown; the DirectionalChange family takes fractions (see DirectionalChange). It is compared strictly against |previous|*tolerance/100, multiplied before it is divided, so 0.05 means 0.05%, not 5%, and a change equal to the threshold is flat, the strict crossing rule of the family. tolerance is optional: only its first element is read, and the rest are ignored whatever they hold; omitting it is the same as passing 0, and -0 behaves as 0.
With d[u] the direction of change u, the window of bar t holds the n pairs (d[u-1], d[u]) for u = t-n+1 to t, so it spans the n+2 prices c[t-n-1] to c[t]. Each pair counts in the row of its earlier direction, from, and the column of its later direction, to. With i the direction d[t], m the number of pairs in the window whose row is i, the support of the current row, and x the number of those whose column is to, the output at bar t is x/m when m > 0: an estimate of the probability that the next change, d[t+1], is to, from the pairs that end by bar t. It is MarkovDirTransition(n, i, to, tolerance) read at each bar’s own direction i.
On finite prices the method is a composition of existing methods: with z := c.UpDown(1, tolerance) and C(i, j) the composition z.EQ(j).Mul(z.EQ(i).Shift(1)).Sum(n).Ratio(z.EQ(i).Shift(1).Sum(n)), the output at every bar t from n+1 on whose prices c[t-n-1] to c[t] are finite equals the sum over i of z.EQ(i).Mul(C(i, to)) bit for bit; the method adds the warm-up zeros, the NaN footprint and O(1) cost.
The first valid index is n+1 and the minimum length is n+2; the useful range is n at most len(c)-2. The warm-up reads 0, not NaN, so an unmasked rule reads it as a direction that never follows. Bars 0 to n are +0 whatever the prices: bar 0 has no earlier price, so the first window of n whole pairs ends at bar n+1.
The method is window-local: a NaN or infinite price at bar p leaves changes p and p+1 without a direction, so the output is NaN on [max(p, n+1), p+n+1], clipped to the last bar, and recovers at bar p+n+2; several such prices give the union of their spans. UpDown alone gives each such change a code, flat across a NaN. The warm-up zeros take precedence over NaN, so the output on a prefix of c is the prefix of the output.
When the window holds no pair from the current direction, its row is empty and the output is 0 for every to, which looks like an observed 0. The first flat change of any window has an empty current row, and flats are sparse at tolerance 0: the 2023 AAPL closes have one flat change in 199, at bar 42, where the output is 0 for every to and every n. The support of a row is c.UpDown(1, tolerance).EQ(from).Shift(1).Sum(n) on finite prices; the recipe in the Markov Models category masks non-finite prices as the method does and reads it through MarkovCount, which is NaN at bar n where the method reads 0.
The integer counts of a row’s three cells sum to its support, and the three supports sum to n, but the three float64 values of the method at to = 2, 1 and 0, added in that order, can sum to 1 - 1 ulp: 4/6 + 1/6 + 1/6 = 0.9999999999999999. On an empty current row they sum to 0.
Arrington (1993) puts the earlier change, the prior day, in the rows, as here. Sherry (1987) puts the later change in the rows and breaks ties with a coin flip, which the deterministic flat state replaces. Gustafson (2002) counts with the counters of ConsecUp and ConsecDown; his whole-sample ratios, their denominators shifted one bar, are the up-to-up and down-to-down cells. Bar t reads c[t-n-1] to c[t] only, so the output is causal; the sources estimate one table over the whole sample.
No source shows a trading edge from these probabilities. Gustafson’s share of up days after an up day is 513/1016 = 0.505, against an up rate of 0.524. On a fair coin the 5% to 95% band of the rolling up-to-up probability is [0.17, 0.73] at n = 20, [0.30, 0.66] at n = 50 and [0.41, 0.57] at n = 250, so sampling noise dominates a rolling estimate.
An invalid parameter (n outside 1 to len(c)-1, to outside [0, 3), or a negative, NaN or infinite tolerance) gives len(c) zeros, and a nil or empty receiver gives an empty Series. The method costs O(1) per bar; it allocates the result, the direction series and the counter tables. The current direction’s stay probability has its own method beside it in the Markov Models category.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference (float64 directions in UpDown’s order, integer counters and exact fractions) and a Julia reference (the same directions and exact rationals) agree with it bit for bit, and so does the selection sum over i of z.EQ(i).Mul(C(i, to)), with z := c.UpDown(1, tolerance), at every bar from n+1 on whose window holds only finite prices.
MarkovDirPersistence
func (s Series) MarkovDirPersistence(n int, tolerance ...float64) Series
MarkovDirPersistence returns the rolling estimate of the current price direction’s one-step stay probability, the probability that the next change has the same direction as the current one, over the last n pairs of consecutive changes.
The codes are those of UpDown(1): change u, from c[u-1] to c[u], is 0 for flat, 1 for down and 2 for up. UpDownSum and RegimeDFA use +1 for up; here 2 is up and 1 is down. The method takes no from or to: the row and the column it reads are both the direction of the last change, from c[t-1] to c[t]. A change is up when it exceeds the threshold and down when it falls below its negation, exactly as UpDown classifies it in float64: the tolerance is a percentage, as in UpDown; the DirectionalChange family takes fractions (see DirectionalChange). It is compared strictly against |previous|*tolerance/100, multiplied before it is divided, so 0.05 means 0.05%, not 5%, and a change equal to the threshold is flat, the strict crossing rule of the family. tolerance is optional: only its first element is read, and the rest are ignored whatever they hold; omitting it is the same as passing 0, and -0 behaves as 0.
With d[u] the direction of change u, the window of bar t holds the n pairs (d[u-1], d[u]) for u = t-n+1 to t, so it spans the n+2 prices c[t-n-1] to c[t]. Each pair counts in the row of its earlier direction, from, and the column of its later direction, to. With i the direction d[t], m the number of pairs in the window whose row is i, the support of the current row, and x the number of those whose column is i as well, the output at bar t is x/m when m > 0: the share of the pairs from direction i that stayed in direction i. It is MarkovDirNext read at to = i. At n = 1 it is 1 when d[t-1] equals d[t] and 0 otherwise.
On finite prices the method is a composition of existing methods: with z := c.UpDown(1, tolerance) and C(i, j) the composition z.EQ(j).Mul(z.EQ(i).Shift(1)).Sum(n).Ratio(z.EQ(i).Shift(1).Sum(n)), the output at every bar t from n+1 on whose prices c[t-n-1] to c[t] are finite equals the sum over i of z.EQ(i).Mul(C(i, i)) bit for bit; the method adds the warm-up zeros, the NaN footprint and O(1) cost.
The first valid index is n+1 and the minimum length is n+2; the useful range is n at most len(c)-2. The warm-up reads 0, not NaN, so an unmasked rule reads it as a direction that never follows. Bars 0 to n are +0 whatever the prices: bar 0 has no earlier price, so the first window of n whole pairs ends at bar n+1.
The method is window-local: a NaN or infinite price at bar p leaves changes p and p+1 without a direction, so the output is NaN on [max(p, n+1), p+n+1], clipped to the last bar, and recovers at bar p+n+2; several such prices give the union of their spans. UpDown alone gives each such change a code, flat across a NaN. The warm-up zeros take precedence over NaN, so the output on a prefix of c is the prefix of the output.
When the window holds no pair from the current direction, its row is empty and the output is 0, as for a direction that always switched. The first flat change of any window has an empty current row, and flats are sparse at tolerance 0: the 2023 AAPL closes have one flat change in 199, at bar 42, where the output is 0 for every n, so on a flat bar the method reads P(F|F), usually 0. The support of a row is c.UpDown(1, tolerance).EQ(from).Shift(1).Sum(n) on finite prices; the recipe in the Markov Models category masks non-finite prices as the method does and reads it through MarkovCount, which is NaN at bar n where the method reads 0. The integer counts of a row’s three cells sum to its support, and the three supports sum to n.
It is not the pooled, drift-adjusted persistence of Semenov’s sign test, the SignPersistence methods of a later GLE-227 tranche (not yet built), nor the long-memory persistence that DFAAlpha, RegimeDFA and Hurst estimate: it is the one-step stay probability of the current price direction, P(U|U) on an up bar, P(D|D) on a down bar and P(F|F) on a flat bar, neither Semenov’s pooled (n_UU + n_DD)/n nor Siroky’s joint share of up-up days. On a window with no flats the pooled share equals (m_UP(U|U) + m_DP(D|D))/n, where n_UU and n_DD count the up-up and down-down pairs and m_U and m_D the pairs from up and from down. On up bars it is Gustafson’s continuation ratio.
Arrington (1993) puts the earlier change, the prior day, in the rows, as here. Sherry (1987) puts the later change in the rows and breaks ties with a coin flip, which the deterministic flat state replaces. Gustafson (2002) counts with the counters of ConsecUp and ConsecDown; his whole-sample ratios, their denominators shifted one bar, are the up-to-up and down-to-down cells. Bar t reads c[t-n-1] to c[t] only, so the output is causal; the sources estimate one table over the whole sample.
No source shows a trading edge from these probabilities. Gustafson’s share of up days after an up day is 513/1016 = 0.505, against an up rate of 0.524. On a fair coin the 5% to 95% band of the rolling up-to-up probability is [0.17, 0.73] at n = 20, [0.30, 0.66] at n = 50 and [0.41, 0.57] at n = 250, so sampling noise dominates a rolling estimate.
An invalid parameter (n outside 1 to len(c)-1, or a negative, NaN or infinite tolerance) gives len(c) zeros, and a nil or empty receiver gives an empty Series. The method costs O(1) per bar; it allocates the result, the direction series and the counter tables.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference (float64 directions in UpDown’s order, integer counters and exact fractions) and a Julia reference (the same directions and exact rationals) agree with it bit for bit, and so does the selection sum over i of z.EQ(i).Mul(C(i, i)), with z := c.UpDown(1, tolerance), at every bar from n+1 on whose window holds only finite prices.
MarkovDirPhi
func (s Series) MarkovDirPhi(n int) Series
MarkovDirPhi returns the rolling phi coefficient between the up or not-up direction of each price change and that of the change before it, over the last n pairs of consecutive changes, positive when a direction tends to repeat and negative when it tends to alternate.
Change u of a price series c runs from c[u-1] to c[u], for u >= 1, and b[u] is the up bit of change u. The window of bar t holds the n pairs of consecutive bits (b[u-1], b[u]) for u = t-n+1 to t, so it spans the n+2 prices c[t-n-1] to c[t]. Each pair counts in the row of its earlier bit and the column of its later bit of a 2 by 2 table: n11 counts up then up, n10 up then not-up, n01 not-up then up and n00 not-up then not-up. With N = n11n00 - n10n01, the row totals r1 = n11+n10 and r0 = n01+n00 and the column totals c1 = n11+n01 and c0 = n10+n00, the output is the Spearman two-factor form (Nn/4)/sqrt((nc1c0/4)(nr1r0/4)), each product formed exactly in int64 and each factor rounded once.
With up := c.Delta().GT(0), the output equals up.SpearmanRankCorrelation(n, up.Shift(1)) bit for bit at every bar from n+1 on whose prices are finite, while nc1c0 < 2^53: the ranks of 0/1 data are half-integers, so Spearman’s sums are exact. The counts move by one pair a bar, so the method has an O(1) cost.
The up bit is 1 when the change is up and 0 when it is down or flat: change u is up when c[u] is above c[u-1], the up code of UpDown(1) at tolerance 0. A change with a NaN or infinite price at either end has no bit.
The method takes no tolerance: any rise in price is up, however small, and a flat change counts with the downs.
Bar 0 has no earlier price, so the first window of n whole pairs ends at bar n+1. The first valid index is n+1 and the minimum length is n+2. The warm-up reads 0, not NaN, so an unmasked rule reads it as independence. Bars 0 to n are +0, and n = len(c)-1 gives only warm-up zeros.
The method is window-local: a NaN, +Inf or -Inf price at bar p leaves changes p and p+1 without a bit, so the output is NaN on [max(p, n+1), p+n+1], clipped to the last bar, and recovers at bar p+n+2; several bad prices give the union of their spans. The warm-up zeros take precedence over NaN. Bar t reads only bars up to t, so the output on a prefix of c is the prefix of the output, and dropping the first d bars leaves every bar from d+n+1 on unchanged. A -0 price is finite, and -0 against +0 is a flat change.
A flat change is not-up, the up-against-not-up split of TSSB’s price entropy, so clustered flats (tick-rounded quiet markets) give a positive phi without directional dependence; SignPhi, the two-series phi, excludes a pair with a flat change and evaluates Tarkany’s form (AD - BC)/sqrt((A+B)(C+D)(A+C)*(B+D)) left to right, where this method evaluates Spearman’s two-factor form; on windows of finite prices without a flat change s.SignPhi(s, n, 1, 1) agrees with MarkovDirPhi(n) within a few units in the last place, not bit for bit.
The output is +0 when a margin product r1r0 or c1c0 is 0: at n = 1, on a window whose changes are all up or all not-up, and on a constant window. It lies in [-1, 1], its zero is +0, and strict alternation of up and not-up gives exactly -1 at every n >= 2.
Under independence phi has a standard error of about 1/sqrt(n), 0.22 at n = 20 and 0.07 at n = 200, and n*phi^2 is a chi-square statistic with one degree of freedom, so erfc(|phi|*sqrt(n/2)) is its p-value, below 5% when |phi| exceeds about 1.96/sqrt(n); the recipe is under Compositions. Rolling windows overlap, so the p-values of successive bars are not independent tests.
No source shows a trading edge from these statistics. Corrected to Pearson’s contingency test, the published whole-sample tables mostly show no first-order dependence: soymeal gives 0.612 and Sherry’s autos 0.0976, each with one degree of freedom, and Sherry’s two daily tables 5.72 and 10.36 with four; McKallip’s large values come from chart patterns labelled with hindsight.
Cost is O(1) per bar from five integer counters, the four cells and a count of undefined pairs, and a call allocates only the result. An invalid n (outside 1 to len(c)-1, or above 2,000,000, a cap that keeps the integer products within int64) gives len(c) zeros, and a nil or empty receiver gives an empty Series.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference and a Julia reference recount every window and agree with this method bit for bit; up.SpearmanRankCorrelation(n, up.Shift(1)) matches it bit for bit on finite windows while nc1c0 < 2^53, and s.SignPhi(s, n, 1, 1) agrees within 8 units in the last place on windows of finite prices without a flat change.
MarkovDirStationary
func (s Series) MarkovDirStationary(n, state int, tolerance ...float64) Series
MarkovDirStationary returns the long-run share of the given price direction (0 flat, 1 down, 2 up) under the direction chain of the trailing n transitions.
It is MarkovStationary with k = 3 on the direction codes of UpDown(1), 0 flat, 1 down and 2 up, takes no alpha, and is exact on every bar; the tolerance is a percentage, as in UpDown. The share is the occupancy c.UpDown(1, tolerance).EQ(state).Average(n) when the window’s first and last directions agree or the current row is empty, the occupancy rule, and otherwise the stationary distribution of the window’s observed transition frequencies on the closed class that the current direction reaches, the closed-class rule, as a ratio of positive integers rounded to the nearest float64 once, ties to even, so every bar is exact. A direction outside the class reads +0 whether it is transient or absent from the window, as does, on an occupancy-rule bar with an empty current row, the first direction when it occurs at bar t-n alone.
The codes are those of UpDown(1): a change is up, code 2, when it exceeds the threshold |previous|*tolerance/100, multiplied before it is divided, down, code 1, when it is below the negative of that threshold, and flat, code 0, otherwise, so a change equal to the threshold is flat. The tolerance is optional and only its first element is read: 0.05 means 0.05%, not 5%, and -0 behaves as 0. At tolerance 0 flat changes are rare on prices quoted to several decimals, one flat change in 199 on the 2023 AAPL closes.
With d[u] the direction of change u, from c[u-1] to c[u], the window of bar t holds the n pairs (d[u-1], d[u]) for u = t-n+1 to t, over the n+2 prices c[t-n-1] to c[t]; the current direction is d[t] and the first d[t-n]. A NaN or infinite price leaves both changes that touch it without a direction.
The first valid index is n+1 and the minimum length is n+2. Bars 0 to n are +0 whatever the prices. The warm-up reads 0, not NaN.
The method is window-local: the output at bar t depends only on the prices c[t-n-1] to c[t] and on the parameters, and the output on a prefix of c is the prefix of the output. A NaN or infinite price at bar p reads NaN on [max(p, n+1), p+n+1], clipped to the last bar, and the output recovers at bar p+n+2; several such bars give the union of their footprints. Every output is +0, NaN or positive, never -0.
The sources treat the stationary share as a whole-sample figure of a fitted chain (Arrington 1993, Sherry 1987, McKallip 1986, Morley); none tests a forecast or shows a trading edge, and the repeated matrix multiplication that one of them describes does not converge on a periodic window, where the exact solve does. The cost is a few integer operations and divisions per bar. Invalid parameters, n outside 1 to len(c)-1, a state outside 0 to 2 or a negative, NaN or infinite tolerance, give len(c) zeros, and a nil or empty receiver gives an empty Series. A call allocates the result, the direction series and the window’s two counter tables, plus a big-integer workspace of three allocations built once when n exceeds 432790.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: every share is the correctly rounded ratio of two positive integers and equals the Python reference and the Julia reference bit for bit on every bar, as does the occupancy identity c.UpDown(1, tolerance).EQ(state).Average(n) on bars from n+1 whose window has equal endpoints or an empty current row.
MarkovDirTransition
func (s Series) MarkovDirTransition(n, from, to int, tolerance ...float64) Series
MarkovDirTransition returns the rolling estimate of the probability that a price change in direction from is followed by one in direction to, over the last n pairs of consecutive changes, with directions coded 0 for flat, 1 for down and 2 for up.
The codes are those of UpDown(1): change u, from c[u-1] to c[u], is 0 for flat, 1 for down and 2 for up. UpDownSum and RegimeDFA use +1 for up, so a caller who passes 1 for up gets the down row. Both from and to must lie in [0, 3). A change is up when it exceeds the threshold and down when it falls below its negation, exactly as UpDown classifies it in float64: the tolerance is a percentage, as in UpDown; the DirectionalChange family takes fractions (see DirectionalChange). It is compared strictly against |previous|*tolerance/100, multiplied before it is divided, so 0.05 means 0.05%, not 5%, and a change equal to the threshold is flat, the strict crossing rule of the family. tolerance is optional: only its first element is read, and the rest are ignored whatever they hold; omitting it is the same as passing 0, and -0 behaves as 0.
With d[u] the direction of change u, the window of bar t holds the n pairs (d[u-1], d[u]) for u = t-n+1 to t, so it spans the n+2 prices c[t-n-1] to c[t]. Each pair counts in the row of its earlier direction, from, and the column of its later direction, to. With m the number of pairs in the window whose row is from, the support of the row, and x the number of those whose column is to, the output at bar t is x/m when m > 0.
On finite prices the method is a composition of existing methods: with z := c.UpDown(1, tolerance), the output at every bar t from n+1 on whose prices c[t-n-1] to c[t] are finite equals z.EQ(to).Mul(z.EQ(from).Shift(1)).Sum(n).Ratio(z.EQ(from).Shift(1).Sum(n)) bit for bit; the method adds the warm-up zeros, the NaN footprint and O(1) cost.
The first valid index is n+1 and the minimum length is n+2; the useful range is n at most len(c)-2. The warm-up reads 0, not NaN, so an unmasked rule reads it as a direction that never follows. Bars 0 to n are +0 whatever the prices: bar 0 has no earlier price, so the first window of n whole pairs ends at bar n+1.
The method is window-local: a NaN or infinite price at bar p leaves changes p and p+1 without a direction, so the output is NaN on [max(p, n+1), p+n+1], clipped to the last bar, and recovers at bar p+n+2; several such prices give the union of their spans. UpDown alone gives each such change a code, flat across a NaN. The warm-up zeros take precedence over NaN, so the output on a prefix of c is the prefix of the output.
When the window holds no pair from direction from, the row is empty and the output is 0, which looks like an observed 0. The flat row is empty at the first flat change of any window, and flats are sparse at tolerance 0: the 2023 AAPL closes have one flat change in 199, at bar 42, where the output from flat is 0 for every to and every n. The support of a row is c.UpDown(1, tolerance).EQ(from).Shift(1).Sum(n) on finite prices; the recipe in the Markov Models category masks non-finite prices as the method does and reads it through MarkovCount, which is NaN at bar n where the method reads 0.
The integer counts of a row’s three cells sum to its support, and the three supports sum to n, but the three float64 probabilities of a row, added from the up cell to the flat cell, can sum to 1 - 1 ulp: 4/6 + 1/6 + 1/6 = 0.9999999999999999.
Arrington (1993) puts the earlier change, the prior day, in the rows, as here. Sherry (1987) puts the later change in the rows and breaks ties with a coin flip, which the deterministic flat state replaces. Gustafson (2002) counts with the counters of ConsecUp and ConsecDown; his whole-sample ratios, their denominators shifted one bar, are the up-to-up and down-to-down cells. Bar t reads c[t-n-1] to c[t] only, so the output is causal; the sources estimate one table over the whole sample.
No source shows a trading edge from these probabilities. Gustafson’s share of up days after an up day is 513/1016 = 0.505, against an up rate of 0.524. On a fair coin the 5% to 95% band of the rolling up-to-up probability is [0.17, 0.73] at n = 20, [0.30, 0.66] at n = 50 and [0.41, 0.57] at n = 250, so sampling noise dominates a rolling estimate.
An invalid parameter (n outside 1 to len(c)-1, from or to outside [0, 3), or a negative, NaN or infinite tolerance) gives len(c) zeros, and a nil or empty receiver gives an empty Series. The method costs O(1) per bar; it allocates the result, the direction series and the counter tables. The current direction’s stay probability has its own method beside it in the Markov Models category.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference (float64 directions in UpDown’s order, integer counters and exact fractions) and a Julia reference (the same directions and exact rationals) agree with it bit for bit, and so does the composition z.EQ(to).Mul(z.EQ(from).Shift(1)).Sum(n).Ratio(z.EQ(from).Shift(1).Sum(n)), with z := c.UpDown(1, tolerance), at every bar from n+1 on whose window holds only finite prices.
MarkovDuration
func (s Series) MarkovDuration(n, k, state int) Series
MarkovDuration returns the expected total spell length in bars of the given state, 1/(1-p_ii) for the chain of the trailing n transitions, counting the current bar.
With m the number of transitions in the window whose earlier state is the given one and x the number of those whose later state differs, the output is m/max(x, 1): m itself, a censored value, when the state did not change inside the window, and 0 when the row is empty. Each output is one correctly rounded division of two exact integers, and since the spell counts the current bar, the remaining life is D - 1. It is the geometric model’s expected length, not the observed run that StateAge and ConsecUp count. The output is 0 exactly where MarkovCount(n, k, state) is 0, on an empty row, which a state seen only at the current bar has too.
The receiver z is the state series. The window of bar t holds the n transitions (z[u-1], z[u]) for u = t-n+1 to t, over the bars t-n to t, with rows and columns as in MarkovTransition: m is the row sum of the given state and x that row sum less its diagonal cell.
A bar holds state j when its value is a whole number from 0 to k-1, decided on the float before any conversion to an integer; NaN, the infinities, fractions, negative values and values of k or more are invalid, and -0 is state 0. k runs from 1 to 98. The codes of UpDown(1) fit k = 3 once bar 0, which has no change, is masked by z.SetN(1, math.NaN()); UpDownSum and RegimeDFA use +1 for up, so add 1 to their values first. The state runs from 0 to k-1. At k = 1 every transition stays and the output is n.
The first valid index is n and the minimum length is n+1. Bars 0 to n-1 are +0 whatever z holds there. The warm-up reads 0, not NaN.
The method is window-local: the output at bar t depends only on bars t-n to t and on the parameters, and the output on a prefix of z is the prefix of the output. An invalid state at bar p reads NaN on [max(p, n), p+n], clipped to the last bar, and the output recovers at bar p+n+1; several invalid bars give the union of their footprints. Every output is +0, NaN or positive, never -0.
The sources treat the expected spell length as a whole-sample figure of a fitted chain (Graflund; Giner and Zakamulin; Baker and Arnold), and none of them shows a trading edge from it. The cost is O(1) per bar after the counters are cleared. Invalid parameters, n outside 1 to len(z)-1, k outside 1 to 98 or a state outside 0 to k-1, give len(z) zeros, and a nil or empty receiver gives an empty Series. A call allocates the result and the window’s two counter tables.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: every output is the correctly rounded ratio of two window counts and equals the composition ePrev.Sum(n).Ratio(ePrev.Mul(e.Sub(1.0).Mul(-1.0)).Sum(n).Max(1.0)) with e := z.EQ(state) and ePrev := e.Shift(1) bit for bit on every bar from n on whose window holds only valid states, and the Python reference and the Julia reference bit for bit on every bar.
MarkovEntropyRate
func (s Series) MarkovEntropyRate(n, k int) Series
MarkovEntropyRate returns the rolling plug-in entropy rate in bits of a state series, the entropy of the next state given the current one, weighted by how often each state occurs in the trailing n transitions.
The receiver z is the state series, whose valid values are the integer codes 0 to k-1, and the window of bar t holds the n transitions (z[u-1], z[u]) for u = t-n+1 to t, as MarkovTransition counts them. With c the number of transitions from state i to state j and r the number that leave state i, the output is the sum of c*log2(r/c) over the occupied cells, divided by n. Each term is rounded before it is added, the cells are read row by row, i ascending and then j ascending, and empty cells and empty rows add nothing: no row is filled.
The output is in bits, from 0 to log2(k) up to rounding, and is not negative zero. It is +0 when every occupied row has one successor, and at k = 1, and it is exactly 1 when every occupied row splits evenly between two successors. k validates the states and sizes the table; it does not scale the output. To normalise, divide by log2(k) and cap the result at 1, because rounding can leave a uniform table slightly above log2(k).
The first valid index is n and the minimum length is n+1. The warm-up reads 0, not NaN, and 0 is also the reading of perfect order, so drop the first n bars with Window(-n), or mask them with SetN(n, math.NaN()), before a percentile, a rank or a low-entropy rule reads the output.
The method is window-local: an invalid state at bar p (NaN, an infinity, a fraction, a negative value or a value of k or more) gives NaN on [max(p, n), p+n], and the output recovers at bar p+n+1. Mask a builder’s artificial first bar, as z.SetN(1, math.NaN()) does for UpDown(1). An invalid parameter (n outside 1 to len(z)-1, or k outside 1 to 98) gives len(z) zeros, and a nil or empty receiver gives an empty Series.
The estimate is biased low on short windows; a table of kk cells wants about 10k*k transitions. Fifteen independent, equally likely states read about 0.67 of log2(15) at n = 119, and ten of the fifteen read about 0.69, so the value does not rise steadily with the true entropy there. With two states the output is nearly a function of the phi coefficient of the same table and the base rate. The output is only as causal as z: build the states from trailing data, not from bins or labels cut over the whole sample. No source shows a trading edge from it.
Singha’s order-flow entropy weights the rows by the stationary distribution, fills empty rows with 1/k and divides by the logarithm of k; this method weights by the window’s own row counts and fills nothing. CrossSectionalEntropy is a different quantity, the entropy of the shares of several series at one bar.
Cost is O(k*k) per bar; a call allocates the result and two counter tables.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference and a Julia reference, with explicit loops in the same order, agree with each other digit for digit and with this method to 1e-12, and at k = 2 a composition of EQ, Shift, Sum, Mul, Ratio, Max, Log2, Add and Div on the up bit of a price series equals it bit for bit.
MarkovMutualInfo
func (s Series) MarkovMutualInfo(n, k int) Series
MarkovMutualInfo returns the rolling plug-in mutual information in bits between consecutive states of a state series over the trailing n transitions.
The receiver z is the state series, whose valid values are the integer codes 0 to k-1, and the window of bar t holds the n transitions (z[u-1], z[u]) for u = t-n+1 to t, as MarkovTransition counts them. With c the number of transitions from state i to state j, r the number that leave i and d the number that enter j, the output is the sum of clog2((nc)/(rd)) over the occupied cells, divided by n. The products nc and r*d are formed as integers, each term is rounded before it is added, and the cells are read row by row, i ascending and then j ascending.
The output is in bits, from 0 to log2(k) up to rounding, and it is not negative: math.Max turns a negative rounding residue into +0. It is +0 when the table equals the product of its margins, at k = 1 and on a constant window. Multiplied by 2nln(2) it is the likelihood-ratio statistic of independence of the table, and added to MarkovEntropyRate(n, k) it is the entropy of the states the transitions enter, up to rounding.
The first valid index is n and the minimum length is n+1. The warm-up reads 0, not NaN, and 0 is also the reading of independence, so drop the first n bars with Window(-n), or mask them with SetN(n, math.NaN()), before a rule or a rank reads the output.
The method is window-local: an invalid state at bar p (NaN, an infinity, a fraction, a negative value or a value of k or more) gives NaN on [max(p, n), p+n], and the output recovers at bar p+n+1. Mask a builder’s artificial first bar, as z.SetN(1, math.NaN()) does for UpDown(1). An invalid parameter (n outside 1 to len(z)-1, n above 3,000,000,000, a cap that keeps the integer products within int64, or k outside 1 to 98) gives len(z) zeros, and a nil or empty receiver gives an empty Series.
The estimate is biased high on short windows; a table of kk cells wants about 10k*k transitions. Independent, equally likely states average about 1.2 bits at k = 15 and n = 119, and about 0.04 bits at k = 2 and n = 20. With two states the output is nearly a function of the phi coefficient of the same table and the base rate. The output is only as causal as z: build the states from trailing data. No source shows a trading edge from it.
Cost is O(k*k) per bar; a call allocates the result, two counter tables and a table of column totals.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference and a Julia reference, with explicit loops in the same order, agree with each other digit for digit and with this method to 1e-12, and at k = 2 a composition of EQ, Shift, Sum, Mul, Ratio, Max, Log2, Add and Div on the up bit of a price series equals it bit for bit.
MarkovNext
func (s Series) MarkovNext(n, k, to int, alpha ...float64) Series
MarkovNext returns the rolling estimate of the probability that the next state is to, given the current state, over the last n transitions of a state series whose valid values are the integer codes 0 to k-1.
The receiver z is the state series, and the window of bar t holds the n transitions (z[u-1], z[u]) for u = t-n+1 to t. So n counts transitions, not bars, and the window spans the n+1 bars t-n to t. Each transition counts in the row of its earlier state, from, and the column of its later state, to. With i the state of z[t], m the number of transitions in the window whose row is i and c the number of those whose column is to, the output at bar t is c/m when m > 0: an estimate of the probability that z[t+1] is to, from the transitions that end by bar t. It is MarkovTransition(n, k, i, to) read at each bar’s own state i, with the same alpha.
A bar holds state j when its value is a whole number j from 0 to k-1, decided on the float before any conversion to an integer: NaN, the infinities, fractions, negative values and values of k or more are invalid states, and -0 is state 0. k runs from 1 to 98, so the codes of UpDown(1), UpDown(2) and UpDown(3) fit, at k = 3, 11 and 43, and those of UpDown(4) do not. UpDown(1) gives 0 for flat, 1 for down and 2 for up, but UpDownSum and RegimeDFA use +1 for up (trending, for RegimeDFA), so add 1 to their values first; a value that is then negative or fractional is still invalid. The parameter to must lie in [0, k); the current state i is read from z[t] itself.
The first valid index is n and the minimum length is n+1. The warm-up reads 0, not NaN, so an unmasked rule reads it as a state that never transitions or stays. Bars 0 to n-1 are +0 whatever z holds there.
The method is window-local: an invalid state at bar p gives NaN on [max(p, n), p+n], clipped to the last bar, since bar p is the later end of transition p and the earlier end of transition p+1, and the output recovers at bar p+n+1; several invalid bars give the union of their spans. An invalid current state z[t] is such a bar, as the later end of transition t. The warm-up zeros take precedence over NaN, so an invalid bar inside the first window leaves the bars before n at 0, and the output on a prefix of z is the prefix of the output. Mask what should not count: z.SetN(1, math.NaN()) marks the first bar of UpDown(1), which has no earlier bar to compare with, and If can set NaN on the bars of a data gap, so that no window counts a transition across the gap.
When the window holds no transition from the current state i, its row is empty and the output is 0 for every to, which looks like an observed 0; empty rows are frequent at small n or large k. MarkovCount(n, k, i) is 0 exactly there, so the sum over i of z.EQ(i).Mul(z.MarkovCount(n, k, i)), the support of the current row, tells an empty row from an observed 0.
alpha is optional: only its first element is read, and the rest are ignored whatever they hold. Omitting it is the same as passing 0, bit for bit. A positive alpha adds alpha pseudo-counts to every cell of the row: the output is then the posterior mean of the row under a symmetric Dirichlet prior, (c + alpha)/(m + kalpha), with kalpha rounded to float64 before the addition by an explicit conversion, which the compiler may not fuse into the sum. An empty row then gives alpha/(kalpha), close to 1/k but not always exactly 1/k. The counts themselves are not changed. alpha must be at least 0 and finite, and so must kalpha; -0 behaves as 0. An invalid parameter (n outside 1 to len(z)-1, k outside 1 to 98, to outside [0, k), or an invalid alpha) gives len(z) zeros, and a nil or empty receiver gives an empty Series.
McKallip (1986) and Arrington (1993) put from in the rows, as here. Sherry puts the later state in the rows, Trongone (2011) puts the from-states in the columns, and Morley (2022) states the transpose, as MarkovTransition explains.
Bar t reads z[t-n] to z[t] only, so the output is causal for point-in-time states. States defined with hindsight are not: McKallip’s chart patterns are labelled after they complete, Sherry cuts terciles over the whole sample, and Alexander, Scherer and Thompson re-cluster the whole history each month.
The sources estimate one table over the whole sample, and none shows a trading edge from a rolling transition probability. Gustafson’s share of up days after an up day is 513/1016 = 0.505, and Pearson chi-square re-tests of two of Sherry’s tables give 0.612 and 0.0976.
The method costs O(1) per bar after clearing its tables in O(k*k); it allocates the result and two counter tables. The current state’s stay probability has its own method; see the Markov Models introduction.
This method is listed under “Compositions” in the “Markov Models” category. The run-continuation recipe under “Consecutive” reads its exact reversal from it.
Verification: a Python reference (integer counters and exact fractions) and a Julia reference (exact rationals) agree with it bit for bit, and so does the selection sum over i of z.EQ(i).Mul(C(i, to)), where C(i, j) is z.EQ(j).Mul(z.EQ(i).Shift(1)).Sum(n).Ratio(z.EQ(i).Shift(1).Sum(n)), at every bar from n on whose window holds only valid states.
MarkovPersistence
func (s Series) MarkovPersistence(n, k int, alpha ...float64) Series
MarkovPersistence returns the rolling estimate of the probability that the current state persists to the next bar, its one-step stay probability over the last n transitions of a state series whose valid values are the integer codes 0 to k-1.
The receiver z is the state series, and the window of bar t holds the n transitions (z[u-1], z[u]) for u = t-n+1 to t. So n counts transitions, not bars, and the window spans the n+1 bars t-n to t. Each transition counts in the row of its earlier state, from, and the column of its later state, to. With i the state of z[t], m the number of transitions in the window whose row is i and c the number of those whose column is i as well, the output at bar t is c/m when m > 0: the share of the transitions from state i that stayed in state i. It is MarkovNext read at to = i, with the same alpha. At n = 1 it is 1 when z[t-1] equals z[t] and 0 otherwise, when alpha is omitted.
A bar holds state j when its value is a whole number j from 0 to k-1, decided on the float before any conversion to an integer: NaN, the infinities, fractions, negative values and values of k or more are invalid states, and -0 is state 0. k runs from 1 to 98, so the codes of UpDown(1), UpDown(2) and UpDown(3) fit, at k = 3, 11 and 43, and those of UpDown(4) do not. UpDown(1) gives 0 for flat, 1 for down and 2 for up, but UpDownSum and RegimeDFA use +1 for up (trending, for RegimeDFA), so add 1 to their values first; a value that is then negative or fractional is still invalid. The method takes no from or to: the row and the column it reads are both the state of z[t].
The first valid index is n and the minimum length is n+1. The warm-up reads 0, not NaN, so an unmasked rule reads it as a state that never transitions or stays. Bars 0 to n-1 are +0 whatever z holds there.
The method is window-local: an invalid state at bar p gives NaN on [max(p, n), p+n], clipped to the last bar, since bar p is the later end of transition p and the earlier end of transition p+1, and the output recovers at bar p+n+1; several invalid bars give the union of their spans. An invalid current state z[t] is such a bar, as the later end of transition t. The warm-up zeros take precedence over NaN, so an invalid bar inside the first window leaves the bars before n at 0, and the output on a prefix of z is the prefix of the output. Mask what should not count: z.SetN(1, math.NaN()) marks the first bar of UpDown(1), which has no earlier bar to compare with, and If can set NaN on the bars of a data gap, so that no window counts a transition across the gap.
When the window holds no transition from the current state i, its row is empty and the output is 0, as for a state that always switched; empty rows are frequent at small n or large k. MarkovCount(n, k, i) is 0 exactly there, so the sum over i of z.EQ(i).Mul(z.MarkovCount(n, k, i)), the support of the current row, tells an empty row from a state that switched.
alpha is optional: only its first element is read, and the rest are ignored whatever they hold. Omitting it is the same as passing 0, bit for bit. A positive alpha adds alpha pseudo-counts to every cell of the row: the output is then the posterior mean of the row under a symmetric Dirichlet prior, (c + alpha)/(m + kalpha), with kalpha rounded to float64 before the addition by an explicit conversion, which the compiler may not fuse into the sum. An empty row then gives alpha/(kalpha), close to 1/k but not always exactly 1/k. The counts themselves are not changed. alpha must be at least 0 and finite, and so must kalpha; -0 behaves as 0. An invalid parameter (n outside 1 to len(z)-1, k outside 1 to 98, or an invalid alpha) gives len(z) zeros, and a nil or empty receiver gives an empty Series.
McKallip (1986) and Arrington (1993) put from in the rows, as here. Sherry puts the later state in the rows, Trongone (2011) puts the from-states in the columns, and Morley (2022) states the transpose, as MarkovTransition explains. Transposing the table leaves its diagonal in place, so a transposed matrix shows the same stay probabilities. A table normalised over the later state does not: its diagonal cell divides by the transitions into the state, not out of it.
Bar t reads z[t-n] to z[t] only, so the output is causal for point-in-time states. States defined with hindsight are not: McKallip’s chart patterns are labelled after they complete, Sherry cuts terciles over the whole sample, and Alexander, Scherer and Thompson re-cluster the whole history each month.
The sources estimate one table over the whole sample, and none shows a trading edge from a rolling transition probability. Gustafson’s share of up days after an up day is 513/1016 = 0.505, and Pearson chi-square re-tests of two of Sherry’s tables give 0.612 and 0.0976.
It is not the pooled, drift-adjusted persistence of Semenov’s sign test, the SignPersistence methods of a later GLE-227 tranche (not yet built), nor the long-memory persistence that DFAAlpha, RegimeDFA and Hurst estimate: it is the one-step stay probability of the current state, and 1 - MarkovPersistence is that state’s switch rate. On a two-state series with states U and D, the pooled share of stays in the window is (n_UU + n_DD)/n = (m_UP(U|U) + m_DP(D|D))/n, where n_UU and n_DD count the stays in U and in D, m_U and m_D the transitions from U and from D, and P(U|U) and P(D|D) are the two stay probabilities of the window. On the up state of a direction series it is Gustafson’s continuation ratio, and on a persistent regime state it gauges how stable the regime is.
The method costs O(1) per bar after clearing its tables in O(k*k); it allocates the result and two counter tables.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference (integer counters and exact fractions) and a Julia reference (exact rationals) agree with it bit for bit, and so does the selection sum over i of z.EQ(i).Mul(C(i, i)), where C(i, j) is z.EQ(j).Mul(z.EQ(i).Shift(1)).Sum(n).Ratio(z.EQ(i).Shift(1).Sum(n)), at every bar from n on whose window holds only valid states.
MarkovStationary
func (s Series) MarkovStationary(n, k, state int, alpha ...float64) Series
MarkovStationary returns the long-run share of the given state under the transition matrix of the trailing n transitions, or under its alpha-smoothed form when alpha is positive.
The share is the stationary distribution of the window’s maximum-likelihood transition matrix on the closed class that the current state reaches, computed exactly in integers and rounded once, and it equals the occupancy z.EQ(state).Average(n) when the window’s first and last states agree or the current row is empty. That occupancy rule is a rule, never a fallback: a window that starts and ends in the same state is a closed walk whose counts are balanced, so the occupancy is the stationary share of the window’s own matrix and equals z.EQ(j).Average(n) bit for bit; a window whose current state has no transition leaving it has no row for that state, and the occupancy is its long-run share by definition. Every other window takes the closed-class rule: the states that the current state reaches through observed transitions form the one closed class of the window’s chain, every state outside it reads +0, and the shares inside it solve pi = pi P for the matrix P of observed transition frequencies as ratios of positive integers, each rounded to the nearest float64 once, ties to even. A state outside the class reads 0 whether it is transient, with a positive MarkovCount(n, k, state), or absent from the window, with a count of 0; on an occupancy-rule bar with an empty current row the first state also reads 0 with a count of 1 when it occurs at bar t-n alone.
The receiver z is the state series. The window of bar t holds the n transitions (z[u-1], z[u]) for u = t-n+1 to t, over the bars t-n to t, with rows and columns as in MarkovTransition; the current state is z[t] and the first state z[t-n].
A bar holds state j when its value is a whole number from 0 to k-1, decided on the float before any conversion to an integer; NaN, the infinities, fractions, negative values and values of k or more are invalid, and -0 is state 0. k runs from 1 to 16, the cap of the methods with cubic work per bar; k from 17 to 98 gives aligned zeros, which a later widening of the cap would turn into values. The codes of UpDown(1) fit k = 3 once bar 0, which has no change, is masked by z.SetN(1, math.NaN()); UpDownSum and RegimeDFA use +1 for up, so add 1 to their values first. The state runs from 0 to k-1. At k = 1 the share is 1 on every valid bar.
With a positive alpha the share is that of the full k by k matrix whose cells are MarkovTransition(n, k, i, j, alpha), every state solved and an empty row read as uniform, by the Grassmann-Taksar-Heyman reduction in float64: a tolerance-class value within 1e-14 relative of the exact stationary share of the matrix the reduction solves, the one with those off-diagonal cells. A share pins at 0 only when a cell underflows, alpha below about m times 2.5e-324 for a row count m, and reads 1 only when every other share totals about 2^-54 or less. While every cell is at least 2^-1000, about 9.33e-302, every share is positive and finite; below that a cell can round to 0 or a quotient can overflow, and then the bar reads NaN. Below that floor a share can also be subnormal, under about 2.2e-308, and the 1e-14 relative bound does not hold there: one such share reads 4 units of 5e-324 where the exact share rounds to 3. Omitting it, 0 and -0 give the rule above; only the first element of alpha is read, and a negative, NaN or infinite value, or one whose product with k overflows, gives len(z) zeros.
The first valid index is n and the minimum length is n+1. Bars 0 to n-1 are +0 whatever z holds there. The warm-up reads 0, not NaN.
The method is window-local: the output at bar t depends only on bars t-n to t and on the parameters, and the output on a prefix of z is the prefix of the output. An invalid state at bar p reads NaN on [max(p, n), p+n], clipped to the last bar, and the output recovers at bar p+n+1; several invalid bars give the union of their footprints. Every output is +0, NaN or positive, never -0.
The sources treat the stationary share as a whole-sample figure of a fitted chain (Arrington 1993, Sherry 1987, McKallip 1986, Morley); none tests a forecast or shows a trading edge, and the repeated matrix multiplication that one of them describes does not converge on a periodic window, where the exact solve does. On the 2023 AAPL closes against their 20-bar average at n = 20, the share is up to 0.90 from the occupancy and pinned at 0 or 1 while the occupancy is interior on 51 of 161 bars; on the up/not-up states the largest gap is 0.022. The cost is O(k^2 + |C|^3) per bar at alpha 0 and O(k^3) with a positive alpha. Invalid parameters give len(z) zeros, and a nil or empty receiver gives an empty Series. A call allocates the result and the window’s two counter tables, plus, at alpha 0, a big-integer workspace of three allocations built once when k exceeds 3 or n exceeds 432790, and with a positive alpha one float buffer for the matrix, the reduction and the shares.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: every alpha 0 share is the correctly rounded ratio of two positive integers and equals the Python reference and the Julia reference bit for bit on every bar, as does the occupancy identity z.EQ(state).Average(n) on bars whose window has equal endpoints or an empty current row; a positive-alpha share equals the references’ float64 twin bit for bit and, on every reference row with an exact share, lies within 1e-14 relative of the exact share of the matrix the twin solves.
MarkovSwitchMean
func (s Series) MarkovSwitchMean(p11, p22, mu1, sigma1, mu2, sigma2 float64, p0 ...float64) Series
MarkovSwitchMean returns the model’s expected value of the next observation at each bar, the average of mu1 and mu2 weighted by the one-step regime prediction.
The receiver and the missing-observation rule are MarkovSwitchProb’s: an observation series, where a NaN or infinite bar takes the prediction only. The output is in the receiver’s units. Parameter meanings, validation, the optional prior and upstream warm-up masking are also MarkovSwitchProb’s.
It is the model’s non-linear conditional mean of the next observation, the convex combination float64(pred*mu1) + float64(float64(1-pred)*mu2) of MarkovSwitchPredict’s output pred, exactly mu2 at pred = 0 and mu1 at pred = 1. Its range is within one unit in the last place of [min(mu1, mu2), max(mu1, mu2)]. When mu1 > mu2 it rises with the prediction up to rounding: a one-unit step in the prediction can lower it by two units in the last place when both means have the same sign, and it is exactly non-decreasing when mu2 <= 0 <= mu1. When mu1 < mu2 it falls up to rounding. It stays finite for all validated means, including opposite signs at the largest finite magnitude, where the uncentred form mu2 + pred*(mu1-mu2) can overflow.
The first valid index is 0 and the minimum length is 1; the last bar is a forecast for the bar after the series. The underlying filter is recursive, not start-invariant. With no observations, MarkovSwitchProb’s 1e-6 settling points relative to each set’s own prior are bar 84 for Jansen’s toy set at p0 = 0.8 and bar 1,184 for Dai, Zhang and Zhu’s daily set at the default prior. Informative observations usually shorten this; weak ones can lengthen it, by about 5 % for Jansen’s set and by about a half for Dai, Zhang and Zhu’s. Invalid parameters give aligned zeros: an expected observation of 0 rather than mu2, not regime 2 with certainty. A nil or empty receiver gives an empty, non-nil Series. An output is -0 only when both rounded products are -0, as can occur with means of -0 or tiny negative means whose products underflow. Each non-empty call uses O(n) time and one allocation, returns fresh storage and leaves the receiver unchanged.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: the Python and Julia references are the mean columns of MarkovSwitchProb’s references, using exact Bayes in decimal at 60 digits and the forward algorithm on explicit Gaussian likelihoods with a normalised two-state vector in 256-bit BigFloat respectively. The reference cases agree within the 1e-12 golden tolerance from bar 0, with relative allowance 1e-11*|want|. For valid parameters the output equals pred.Mul(mu1).Add(pred.Mul(-1.0).Add(1.0).Mul(mu2)) bit for bit, with pred MarkovSwitchPredict’s output. In that prediction, a = 1-p22 and L = (p11+p22)-1 are run-time values. Both products round before the addition, matching the Series composition.
MarkovSwitchPredict
func (s Series) MarkovSwitchPredict(p11, p22, mu1, sigma1, mu2, sigma2 float64, p0 ...float64) Series
MarkovSwitchPredict returns the probability that the two-state Gaussian Markov-switching model is in regime 1 at the next bar, given the observations up to the current bar.
The receiver and the missing-observation rule are MarkovSwitchProb’s: an observation series, where a NaN or infinite bar takes the prediction only. The parameter meanings, validation, optional prior and upstream warm-up masking are also MarkovSwitchProb’s.
At bar t it is the probability of regime 1 for bar t+1, a + xi*L clamped to [0, 1], with xi MarkovSwitchProb’s output at bar t, a = 1-p22 and L = (p11+p22)-1, the product rounded before the addition. On a missing bar t >= 1, MarkovSwitchProb’s output equals this method’s output at t-1; at a missing bar 0 it equals the prior. The prediction still advances the chain once for bar t+1. The state between bars is this one number: for every k >= 1, MarkovSwitchProb on the bars from k on, with the same parameters and p0 set to this method’s output at bar k-1, repeats MarkovSwitchProb’s output from bar k on, bit for bit.
The first valid index is 0 and the minimum length is 1; the last bar is a forecast for the bar after the series. The underlying filter is recursive, not start-invariant. With no observations, MarkovSwitchProb’s 1e-6 settling points relative to each set’s own prior are bar 84 for Jansen’s toy set at p0 = 0.8 and bar 1,184 for Dai, Zhang and Zhu’s daily set at the default prior. Informative observations usually shorten this; weak ones can lengthen it, by about 5 % for Jansen’s set and by about a half for Dai, Zhang and Zhu’s. Invalid parameters give aligned zeros, which read as regime 2 with certainty. A nil or empty receiver gives an empty, non-nil Series. All valid outputs are finite and in [0, 1]. No output is -0. Each non-empty call uses O(n) time and one allocation, returns fresh storage and leaves the receiver unchanged.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: the Python and Julia references are the prediction columns of MarkovSwitchProb’s references, using exact Bayes in decimal at 60 digits and the forward algorithm on explicit Gaussian likelihoods with a normalised two-state vector in 256-bit BigFloat respectively. The reference cases agree within the 1e-12 golden tolerance from bar 0, with relative allowance 1e-11*|want|. For valid parameters the output equals Prob.Mul(L).Add(a).Clamp(0, 1) bit for bit, with Prob the MarkovSwitchProb output and a = 1-p22 and L = (p11+p22)-1 computed as run-time values. The product rounds before the addition.
MarkovSwitchPredictLikelihood
func (s Series) MarkovSwitchPredictLikelihood(p11, p22 float64, p0 ...float64) Series
MarkovSwitchPredictLikelihood returns the one-step-ahead regime-1 probability of MarkovSwitchProbLikelihood’s filter: the filtered probability carried through the transition step.
The receiver and the missing-observation rule are MarkovSwitchProbLikelihood’s: a likelihood-ratio series f2/f1, where a ratio of 0 or more is an observation and a NaN or negative ratio is a missing bar that takes the prediction only. The parameter meanings, validation, optional prior, the decisive zero ratio and upstream masking are also MarkovSwitchProbLikelihood’s.
At bar t it is the probability of regime 1 for bar t+1, a + xi*L clamped to [0, 1], with xi MarkovSwitchProbLikelihood’s output at bar t, a = 1-p22 and L = (p11+p22)-1, the product rounded before the addition. The transition applies at every bar, bar 0 and missing bars included. With L >= 0 the output lies between a and a + L: from 0.010000000000000009 to 0.95 at the monthly preset p11 = 0.95 and p22 = 0.99. Its value at bar t-1 is the probability of regime 1 at bar t given the bars before it, the forecast a decision at the close of bar t-1 acts on.
The first valid index is 0 and the minimum length is 1; the last bar is a forecast for the bar after the series. The underlying filter is recursive, not start-invariant: with no observations its 1e-6 settling point is bar 221 at the monthly preset, and informative observations usually shorten it. Invalid parameters give aligned zeros, which read as regime 2 with certainty. A nil or empty receiver gives an empty, non-nil Series. All valid outputs are finite and in [0, 1]. No output is -0. Each non-empty call uses O(n) time and one allocation, returns fresh storage and leaves the receiver unchanged.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: the Python and Julia references are the prediction columns of MarkovSwitchProbLikelihood’s references, the first in binary64 with a correctly rounded exponential against exact Bayes in decimal at 60 digits, the second from the densities’ definitions with 256-bit BigFloat checks. Given their ratio column the output agrees with both bit for bit. For valid parameters the output equals Prob.Mul(L).Add(a).Clamp(0, 1) bit for bit, with Prob the MarkovSwitchProbLikelihood output and a = 1-p22 and L = (p11+p22)-1 computed as run-time values; written as constant expressions they fold exactly and differ. On the Gaussian ratio it equals MarkovSwitchPredict on the observations bit for bit.
MarkovSwitchProb
func (s Series) MarkovSwitchProb(p11, p22, mu1, sigma1, mu2, sigma2 float64, p0 ...float64) Series
MarkovSwitchProb returns the filtered probability that a two-state Gaussian Markov-switching model with caller-fixed parameters is in regime 1 at each bar, given the observations up to that bar.
The receiver is an observation series, for example log returns c.Log().Delta().SetN(1, math.NaN()); a NaN or infinite observation is missing, and that bar takes the prediction only. Other observation series, such as log realised variance, are valid when the emission parameters use the receiver’s units. Regime 1 is the first emission pair (mu1, sigma1), and regime 2 is the second; its view is Prob.Mul(-1.0).Add(1.0).
In regime k, the observation is normal with mean mu_k and standard deviation sigma_k. The unobserved regime follows a two-state Markov chain with parameters fixed by the caller; nothing is estimated. With a = 1-p22 and L = (p11+p22)-1, the one-step prediction from the current regime-1 probability xi is a + xi*L. For z1 = (x-mu1)/sigma1 and z2 = (x-mu2)/sigma2, the likelihood ratio is r = exp(d)sigma1/sigma2, where d = (z1-z2)(z1+z2)*0.5, and the posterior is pred/(pred + (1-pred)*r). No individual Gaussian likelihood is formed, so a crash-size observation cannot underflow both densities; each observed bar costs one exponential and a missing bar costs none. This is Hamilton’s filter in likelihood-ratio form. Sources are Zakamulin and Giner 2022, Table 1, p.8; Giner and Zakamulin 2023, Table 1, p.28; Dai, Zhang and Zhu 2009, Table 1, p.15; Jansen’s regime notebook; and Chan’s Machine Trading, p.104.
p11 and p22 are stay probabilities; a mean regime duration E[d] in bars gives p = 1 - 1/E[d]. Map continuous-time switching intensities through the exact two-state transition matrix exponential, not through lambda*dt. The means mu1 and mu2 and standard deviations sigma1 and sigma2 are per bar in the receiver’s units. p0 is the probability of regime 1 before bar 0’s observation; no transition is applied before bar 0; the default is the stationary share a/((1-p11)+a). Supply at most one p0 element.
The first valid index is 0 and the minimum length is 1; bar 0 is filtered from p0, or is p0 when bar 0 is missing. There is no warm-up. On a missing bar, the posterior keeps the prediction, then the chain advances once for the next bar. Later outputs remain defined but can differ from an uninterrupted run. Mask any upstream warm-up with NaN before the call: an unmasked value is read as an observation, including Delta’s artificial zero at bar 0. Smooth before masking, using c.Log().XAverage(span).Delta().SetN(span, math.NaN()); bars 0 to span-1 are missing and observations begin at bar span. Smoothing already masked returns with XAverage instead leaves bars 1 to span-2 unsmoothed and makes every bar from span-1 on NaN.
Invalid parameters give aligned zeros, which read as regime 2 with certainty. Each stay probability must be in [0, 1), both means must be finite, both standard deviations must be finite and positive, and the optional p0 must be in [0, 1]. More than one p0 element, or a NaN in any parameter, is invalid; -0 is valid as a stay probability or prior. p = 1 is rejected because a state locks once its probability rounds to 1. With p11 = p22 = 0, the chain alternates deterministically: the prediction is 1-xi, and evidence locks the filter only once it rounds to 0 or 1, within 2^-53. A nil or empty receiver gives an empty, non-nil Series. Validation precedes allocation. Each non-empty call makes one allocation and returns fresh storage without changing the receiver; filtering takes O(n) time.
The filter is recursive, not start-invariant, and keeps no state between calls. With no observations, the initial effect decays as |L|^t. The first bar from which every p0 in [0, 1] changes the filtered probability by less than 1e-6 against the set’s own prior is bar 84 for Jansen’s toy set at p0 = 0.8, 117 for Zakamulin and Giner, 123 and 112 for Giner and Zakamulin’s S&P and DJIA sets, and 1,184 for Dai, Zhang and Zhu. The latter sets use their default priors. Informative observations usually shorten this; weak ones can lengthen it, by about 5 % for Jansen’s and the monthly sets and by about a half for Dai, Zhang and Zhu’s (steady observations a little on regime 2’s side of the means’ midpoint). The state’s 1-xi has about 1.1e-16 absolute precision, so errors against exact Bayes grow like 1e-17/(1-p) near a stay probability p of 1: about 1.6e-15, 4.7e-14, 4.9e-12, 6.0e-10 and 9.4e-8 at gaps 1-p of 1e-2, 1e-4, 1e-6, 1e-8 and 1e-10 respectively. Agreement with exact Bayes to 1e-12 is claimed only where 1-max(p11, p22) >= 1e-3; stay probabilities within a few ulps of 1 behave as absorbing. An exp overflow gives exactly 0, as does an overflow of r = exp(d)sigma1/sigma2 with exp(d) finite; the true value is then below pred/(1-pred)e^-709max(1, sigma2/sigma1). Likewise an underflow gives exactly 1, of exp(d) or of r, within (1-pred)/prede^-744max(1, sigma1/sigma2) of the true value. A NaN quotient instead keeps the prediction: pred = 0 with r = 0, pred = 1 with r = +Inf, or r = NaN. The chain recovers from 0 through a and from 1 through a + L. Both z overflowing makes r NaN and keeps the prediction. With a finite positive sigma ratio, z1 overflowing alone gives 0 and z2 alone gives 1, subject to those boundary cases; the product forming d can also overflow with both z finite. With equal sigmas and |x| beyond about 2^52|mu1 - mu2|, the two z can round equal. Then r = 1 leaves the prediction unchanged up to rounding, or an overflowing z1+z2 makes r NaN and keeps it exactly. When both means exceed about 2^53*|x| in magnitude, x - mu_k rounds to -mu_k, so the bar gives the output of x = 0. With mu2 = -mu1 and equal sigmas, z1+z2 is then 0 and r = 1, so the output is the prediction even where exact Bayes is decisive: mu1 = 1e300, mu2 = -1e300, unit sigmas, p0 = 0.5 and x = 0.01 give 0.5, not 1. Extreme sigma ratios can also make r NaN, so those bars keep the prediction; sigmas at the largest finite float can give r = 1. An output is -0 only at bar 0, when p0 is -0 and that bar keeps the prediction because it is missing or r is 0 or NaN there. Such ratios can arise from an underflow of exp(d) or of r, both z overflowing, the equal-sigma band or an extreme sigma ratio. All valid outputs are finite probabilities in [0, 1].
With equal variances, on Apple’s 2023 daily log returns and Dai, Zhang and Zhu’s daily set, the logit of the output correlates 0.9975 with an exponential moving average of the returns (weight 0.955 per bar), the kind of average XAverage computes. With unequal variances (Zakamulin and Giner’s monthly set scaled to days) the best such correlation is 0.855, at a weight of 0.986, and the filter acts as a volatility-regime detector. Kalman is a continuous-state filter with a fixed gain, not a regime filter, and RegimeDFA is a deterministic regime label. No source gives out-of-sample evidence for a filter with fixed parameters. Chan’s related hidden Markov model on SPY made a compound annual growth rate of 8.7 % on its training half, December 2004 to September 2009, and 1 % on its test half, September 2009 to June 2014 (Machine Trading, p.104). The published parameter sets are documentation only: Zakamulin and Giner’s and Giner and Zakamulin’s are monthly statistics of bull and bear phases dated with hindsight, on capital-gain and on total returns, and Dai, Zhang and Zhu’s are annual statistics of the Dow’s bull and bear markets of 1962 to 2008, dated the same way and mapped onto daily bars only approximately. All of them are in-sample.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference uses exact Bayes in decimal at 60 digits on the binary64 parameters, with each output rounded once. A Julia reference uses the forward algorithm on explicit Gaussian likelihoods with a normalised two-state vector in 256-bit BigFloat. The reference cases agree within the 1e-12 golden tolerance from bar 0, with relative allowance 1e-11*|want|; Jansen’s printed four-decimal path agrees within 5e-5. For valid parameters, the following compositions agree bit for bit. Under equal emissions, P equals P.Shift(1).Mul(L).Add(a).Clamp(0, 1).SetN(1, p0). When p11 = 1-p22, P equals x.Mul(0.0).Add(a).Div(R.Mul(1-a).Add(a)) on finite observations after bar 0 with a finite denominator, and at bar 0 too when the prior is a. On every bar with a finite observation and a finite non-zero denominator, P equals Q.Div(Q.Add(Q.Mul(-1.0).Add(1.0).Mul(R))).Clamp(0, 1), where Q = P.Shift(1).Mul(L).Add(a).Clamp(0, 1).SetN(1, p0), z1 = x.Sub(mu1).Div(sigma1), z2 = x.Sub(mu2).Div(sigma2) and R = z1.Sub(z2).Mul(z1.Add(z2)).Mul(0.5).Exp().Mul(rs), with rs = sigma1/sigma2. Here x is the receiver, P the filtered series, p0 the chosen prior, and a and L are run-time values. The products feeding additions round first, matching separate Series operations.
MarkovSwitchProbContinuation
func (s Series) MarkovSwitchProbContinuation(p11, p22, q1, q2 float64, p0 ...float64) Series
MarkovSwitchProbContinuation returns the filtered probability of regime 1 of a two-state Markov-switching model whose observation is whether each price change kept the sign of the previous change.
The receiver is a price series. A bar’s direction is up, down or flat as its change c[t]-c[t-1] is above, below or equal to 0, a -0 change being flat; bar 0 has no change, and a bar whose change is NaN or infinite, from a NaN or infinite price or two finite prices whose difference overflows, has no direction. At bar t the observation is 1 when bars t and t-1 are both up or both down, 0 when one is up and the other down, and missing otherwise, so a flat bar, or one without a direction, makes its own bar and the next missing. Bars 0 and 1 are always missing. A missing bar takes the prediction only, and the chain still advances once for the next bar, so the filter steps in bar time, not in event time. The signs are compared, not the product of the two changes, which underflows to 0 for two changes near 1e-200 and would make a valid pair missing. A flat bar is missing evidence, not a continuation or a reversal: comparing signs as numbers would read two flat bars as a continuation and an up bar after a flat one as a reversal.
The unobserved regime follows a two-state Markov chain whose stay probabilities p11 and p22 are constant parameters, and q1 and q2 are the probabilities of a continuation in regimes 1 and 2; nothing is estimated. With a = 1-p22 and L = (p11+p22)-1, the prediction from the current regime-1 probability xi is a + xi*L, clamped to [0, 1], and the posterior after an observation is pred/(pred + (1-pred)*r), each product rounded before the addition, with the likelihood ratio r1 = q2/q1 after a continuation and r0 = (1-q2)/(1-q1) after a reversal. The ratios follow IEEE division. A q1 of 0 makes r1 +Inf, and a q1 of 1 makes r0 +Inf, which sets the output to 0 unless the prediction is 1; with q2 equal to q1 there, the ratio is NaN instead, and the observation keeps the prediction. Otherwise a q2 of 0 makes r1 0, and a q2 of 1 makes r0 0, which sets the output to 1 unless the prediction is 0. A q1 of -0 is read as 0 before the division, so the two give the same output. p0 is the probability of regime 1 before bar 0’s observation; no transition is applied before bar 0; the default is the stationary share a/((1-p11)+a). Supply at most one p0 element. The default is 0.7500000000000001 at Barberis, Shleifer and Vishny’s values below, and because bars 0 and 1 are missing, their belief of 0.5 before the first observation needs p0 = 1.0/3: bar 1’s output is then 0.5 and bar k+1’s is their period k.
The first valid index is 0 and the minimum length is 1; bars 0 and 1 are always missing, so bar 0’s output is the prior, p0 or its default, and bar 1’s the prediction from it. There is no warm-up. Mask an upstream warm-up of F bars, after a right-alignment segment of off bars, with SetN(off+F, math.NaN()) before the call: a warm-up of zeros is a run of flat bars, which reads as missing here and as not-up evidence in MarkovSwitchProbUpDown, and the step from the last zero to the first value is an artificial change.
Invalid parameters give aligned zeros, which read as regime 2 with certainty. Each stay probability must be in [0, 1), q1 and q2 in [0, 1], and the optional p0 in [0, 1]; more than one p0 element, or a NaN in any parameter, is invalid, and -0 is valid. A nil or empty receiver gives an empty, non-nil Series. Validation precedes allocation. Each non-empty call makes one allocation and returns fresh storage without changing the receiver; filtering takes O(n) time. All valid outputs are finite probabilities in [0, 1]. An output is -0 only at bar 0, and there exactly when p0 is -0.
The filter is recursive, not start-invariant, and keeps no state between calls. With no observations the effect of p0 decays as |L|^t: the first bar from which every p0 in [0, 1] changes the output by less than 1e-6 against the stationary prior is bar 8 at p11 = 0.6 and p22 = 0.25, Chan’s values, and bar 27 at p11 = 0.9 and p22 = 0.7, Barberis, Shleifer and Vishny’s. Observations usually shorten this, but some sequences delay it, to bar 30 on one at the latter values.
Presets are float64 literals in the caller’s code, not defaults. Barberis, Shleifer and Vishny’s values are p11 = 0.9 and p22 = 0.7, from switch probabilities of 0.1 and 0.3, with a continuation probability of q1 = 1/3 in regime 1, their mean-reverting model, and q2 = 0.75 in regime 2, their trending model. The journal article and the working paper before it swap the letters for the two continuation probabilities, so read them by role. The values are illustrative, for annual earnings shocks with a period of roughly a year, not estimates, so they carry no look-ahead; the paper models an investor’s beliefs and gives no trading evidence, and applying the model to price changes is this library’s recast. No source shows an edge out of sample for these values.
SignPhi is a different quantity: a windowed concordance of two series’ up and down changes, not a filtered probability of a hidden regime.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference forms the observations and the filter in binary64, and exact Bayes in rational arithmetic on the binary64 parameters and ratios, rounded once; a Julia reference forms the same quantities from the specification, with exact rational Bayes as its oracle. The output agrees with both bit for bit. On prices that start at 100 and step by 1 with the signs of Barberis, Shleifer and Vishny’s Table 1, with p0 = 1.0/3, bars 1 to 21 reproduce their 21 printed beliefs to two decimals, none nearer than 4.6e-4 to a rounding boundary, and the 21 pinned values bit for bit, and the prices 0, 1e-200, 2e-200 and 3e-200 separate the sign rule from the product rule. For valid parameters, with q1 not -0, the output equals MarkovSwitchProbLikelihood bit for bit on the ratio that is q2/q1 where o is 1, (1-q2)/(1-q1) where o is 0 and NaN elsewhere, with o 1 where k is 1, 0 where k is -1 and NaN elsewhere, for k = sg.Mul(sg.Shift(1)), sg = d.GT(0).Sub(d.LT(0)).MaskNonFinite(d) and d = c.Delta(); with q1 = 1, q2 = 0 and stay probabilities in [0.001, 0.999], the output from bar 2 is 1 where the two changes have the same sign and 0 where they differ, on every bar where both are finite and not 0.
MarkovSwitchProbLikelihood
func (s Series) MarkovSwitchProbLikelihood(p11, p22 float64, p0 ...float64) Series
MarkovSwitchProbLikelihood returns the filtered probability of regime 1 of a two-state Markov-switching model whose receiver is the per-bar likelihood ratio f2/f1 of regime 2 to regime 1.
The receiver is a likelihood-ratio series that the caller builds: at each bar, the density of that bar’s observation under regime 2 divided by its density under regime 1, so a ratio below 1 favours regime 1. A ratio of 0 or more, 0 and +Inf included, is an observation; a NaN or negative ratio, -Inf included, is a missing bar, which takes the prediction only, and the chain still advances once for the next bar, so the filter steps in bar time, not in event time. A ratio of 0 is decisive evidence for regime 1 and +Inf for regime 2: the output is then 1 or 0, unless the prediction is already at the opposite bound, where it is kept. Build a ratio with NaN on its undefined bars, not with Ratio or Div’s zero rule, which give 0 where a quotient is undefined; that 0 reads as regime 1 with certainty, as do the warm-up and invalid-parameter zeros of upstream methods. A negative ratio reads as missing, which can hide an error in the composition, such as a Bernoulli probability outside [0, 1], so validate its parameters. Mask an upstream warm-up of F bars, after a right-alignment segment of off bars, with SetN(off+F, math.NaN()) before the call. Series operations pair two inputs from their most recent bars and give 0 on the receiver’s bars before the overlap, so on those leading bars a ratio composed on a longer receiver than its partner holds the pairing’s zeros, or what later steps make of them; align the inputs by date and cut both with Overlap first.
The unobserved regime follows a two-state Markov chain whose stay probabilities p11 and p22 are fixed by the caller; nothing is estimated. With a = 1-p22 and L = (p11+p22)-1, the prediction from the current regime-1 probability xi is a + xi*L, clamped to [0, 1], and the posterior after a ratio r is pred/(pred + (1-pred)*r), each product rounded before the addition. In real arithmetic this is Bayes’ rule on the two densities, so a factor common to both, such as a normalising constant, cancels. The emission parameters belong to the composition, which validates them: finite means, standard deviations above 0 and below +Inf, Bernoulli probabilities in [0, 1], and more than 2 degrees of freedom for a standardised Student t. p0 is the probability of regime 1 before bar 0’s observation; no transition is applied before bar 0; the default is the stationary share a/((1-p11)+a). Supply at most one p0 element. With L >= 0 the one-step prediction lies between a and a + L, so it is at most p11 up to rounding; read a fixed threshold on it against that ceiling.
The first valid index is 0 and the minimum length is 1; bar 0 is filtered from p0, or is p0 when bar 0 is missing. There is no warm-up.
Invalid parameters give aligned zeros, which read as regime 2 with certainty. Each stay probability must be in [0, 1) and the optional p0 in [0, 1]; more than one p0 element, or a NaN in any parameter, is invalid, and -0 is valid. A nil or empty receiver gives an empty, non-nil Series. Validation precedes allocation. Each non-empty call makes one allocation and returns fresh storage without changing the receiver; filtering takes O(n) time and calls no exponential or logarithm, which the composition that builds the ratio pays for.
The filter is recursive, not start-invariant, and keeps no state between calls. With no observations the effect of p0 decays as |L|^t: the first bar from which every p0 in [0, 1] changes the output by less than 1e-6 against the stationary prior is bar 221 at the monthly preset below, 27 at p11 = 0.9 and p22 = 0.7, and 8 at p11 = 0.6 and p22 = 0.25. Informative observations usually shorten this. The state’s 1-xi has about 1.1e-16 absolute precision, so errors against exact Bayes grow like 1e-17/(1-p) near a stay probability p of 1: on 360 simulated months the largest is 2.2e-16 at the monthly preset below, and 8.4e-15 and 1.6e-11 with both gaps 1-p11 and 1-p22 at 1e-3 and at 1e-6. Agreement with exact Bayes to 1e-12 is claimed only where 1-max(p11, p22) >= 1e-3; stay probabilities within a few ulps of 1 behave as absorbing. All valid outputs are finite probabilities in [0, 1]. An output is -0 only at bar 0, when p0 is -0 and that bar keeps the prediction because it is missing or its ratio is 0.
Presets are float64 literals in the caller’s code, not defaults. The one published set is Daniel, Jagannathan and Kim’s monthly maximum-likelihood fit of momentum and market excess returns (Table 9 of their 2019 working paper, in decimals per month): regime 1 is turbulent with p11 = 0.95 and regime 2 is calm with p22 = 0.99, so a = 0.010000000000000009, L = 0.94, the default p0 is 0.16666666666666666 and the one-step prediction cannot exceed 0.95. It is a full-sample fit on January 1927 to December 2017, so a filter using it is an in-sample illustration over that span, not a causal indicator, and the Student t with 5 degrees of freedom for the market was chosen on the full sample too. The stay probabilities are printed to two decimals and are weakly identified: their t-statistics imply standard errors near 0.08 for p11 and 0.09 for p22. The paper’s timing rule exits momentum above a threshold chosen after the fact, 84.4 % by inference; its own Table 14 puts volatility scaling ahead of that rule, with Sharpe ratios of 0.96 and 1.07 against 0.89; Table 13’s advantage in false positives is strict only at the -20 % loss threshold; and a predicted turbulent probability above 0.8 also flags 8 of the 12 months with gains of 20 % or more. No source gives out-of-sample evidence of an edge for this filter with fixed parameters.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference forms the ratio compositions and the filter in binary64 with a correctly rounded exponential, and exact Bayes in decimal at 60 digits on the binary64 inputs, rounded once. A Julia reference forms the same quantities from the densities’ definitions, with 256-bit BigFloat checks. Given the references’ ratio column the output agrees with both bit for bit; on ratios composed in Go it agrees within the 1e-12 golden tolerance. Barberis, Shleifer and Vishny’s printed beliefs reproduce to two decimals through the Bernoulli ratio, and Jansen’s four-decimal path through the Gaussian ratio. For valid parameters the following compositions agree bit for bit. On every bar with a ratio of 0 or more, other than +Inf, and a finite non-zero denominator, P equals Q.Div(Q.Add(Q.Mul(-1.0).Add(1.0).Mul(R))).Clamp(0, 1), where Q = P.Shift(1).Mul(L).Add(a).Clamp(0, 1).SetN(1, p0), R is the receiver and P the output, and on a missing bar P equals Q. On the Gaussian ratio R = z1.Sub(z2).Mul(z1.Add(z2)).Mul(0.5).Exp().Mul(sigma1/sigma2), with z1 = x.Sub(mu1).Div(sigma1) and z2 = x.Sub(mu2).Div(sigma2), the output equals MarkovSwitchProb’s on the observations x. Here p0 is the chosen prior, and a and L are run-time values. The products feeding additions round first, matching separate Series operations.
MarkovSwitchProbUpDown
func (s Series) MarkovSwitchProbUpDown(p11, p22, q1, q2 float64, p0 ...float64) Series
MarkovSwitchProbUpDown returns the filtered probability of regime 1 of a two-state Markov-switching model whose observation is whether each price rose above the previous price.
The receiver is a price series. At each bar t from 1 the observation is 1 when the change c[t]-c[t-1] is above 0 and 0 when it is 0 or below, so a flat bar, a -0 change included, counts as not-up. Bar 0 has no change and is always missing, and so is any bar whose change is NaN or infinite: a NaN or infinite price on either side, or two finite prices whose difference overflows. A missing bar takes the prediction only, and the chain still advances once for the next bar, so the filter steps in bar time, not in event time. Chan’s up days appear to include flat days, by the change of 0 or more that defines his earlier up class; that flat-as-up form is MarkovSwitchProbLikelihood on the Bernoulli ratio of a greater-or-equal test on the change, with bar 0 masked, and this method does not build it.
The unobserved regime follows a two-state Markov chain whose stay probabilities p11 and p22 are constant parameters, and q1 and q2 are the probabilities of an up bar in regimes 1 and 2; nothing is estimated. With a = 1-p22 and L = (p11+p22)-1, the prediction from the current regime-1 probability xi is a + xi*L, clamped to [0, 1], and the posterior after an observation is pred/(pred + (1-pred)*r), each product rounded before the addition, with the likelihood ratio r1 = q2/q1 after an up bar and r0 = (1-q2)/(1-q1) after a bar that is not up. The ratios follow IEEE division. A q1 of 0 makes r1 +Inf, and a q1 of 1 makes r0 +Inf, which sets the output to 0 unless the prediction is 1; with q2 equal to q1 there, the ratio is NaN instead, and the observation keeps the prediction. Otherwise a q2 of 0 makes r1 0, and a q2 of 1 makes r0 0, which sets the output to 1 unless the prediction is 0. A q1 of -0 is read as 0 before the division, so the two give the same output. p0 is the probability of regime 1 before bar 0’s observation; no transition is applied before bar 0; the default is the stationary share a/((1-p11)+a). Supply at most one p0 element. The default is 0.6521739130434783 at Chan’s values below.
The first valid index is 0 and the minimum length is 1; bar 0 is always missing, so its output is the prior, p0 or its default. There is no warm-up. Mask an upstream warm-up of F bars, after a right-alignment segment of off bars, with SetN(off+F, math.NaN()) before the call: a warm-up of zeros is a run of flat bars, which reads as not-up evidence here and as missing in MarkovSwitchProbContinuation, and the step from the last zero to the first value is an artificial change.
Invalid parameters give aligned zeros, which read as regime 2 with certainty. Each stay probability must be in [0, 1), q1 and q2 in [0, 1], and the optional p0 in [0, 1]; more than one p0 element, or a NaN in any parameter, is invalid, and -0 is valid. A nil or empty receiver gives an empty, non-nil Series. Validation precedes allocation. Each non-empty call makes one allocation and returns fresh storage without changing the receiver; filtering takes O(n) time. All valid outputs are finite probabilities in [0, 1]. An output is -0 only at bar 0, and there exactly when p0 is -0.
The filter is recursive, not start-invariant, and keeps no state between calls. With no observations the effect of p0 decays as |L|^t: the first bar from which every p0 in [0, 1] changes the output by less than 1e-6 against the stationary prior is bar 8 at p11 = 0.6 and p22 = 0.25, Chan’s values, and bar 27 at p11 = 0.9 and p22 = 0.7, Barberis, Shleifer and Vishny’s. Observations usually shorten this, but some sequences delay it, to bar 30 on one at the latter values.
Presets are float64 literals in the caller’s code, not defaults. Chan’s values are p11 = 0.60 and p22 = 0.25, an up day with probability q1 = 0.81 in regime 1, the bull state, and q2 = 0.03 in regime 2; p0 = 1 reproduces his code, which starts in regime 1. He fitted p11, p22, q1 and q2 to daily SPY prices, with an up day presumed to be a daily change of 0 or more, by expectation maximisation, keeping the best of 10 runs, on 22 December 2004 to 15 September 2009, so a filter using them is an in-sample illustration over that span, not a causal indicator; his trading rule’s compound annual growth was 8.7 % on that training half and 1 % on the test half after it. The model is degenerate: at Chan’s values the state is close to the day’s direction, and the probability that the next bar is up, g*q1 + (1-g)*q2 for the prediction g, lies between 0.498 and 0.615. With no flat bar his rule, long when the next-up probability is above 0.5, is short exactly when UpDown(2) is 6, a down bar then an up bar. Under this method’s flat rule it is 2 or 6; under his own flat-as-up rule it is 4 or 6. Under this method’s rule the classification holds from bar 2 on, for any p0, wherever the last two changes are finite, and the next-up probability there is at least 1.24e-4 from 0.5, the distance on the prices 100, 99 and 100 from p0 = 0. No source shows an edge out of sample for these values.
SignPhi is a different quantity: a windowed concordance of two series’ up and down changes, not a filtered probability of a hidden regime.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference forms the observations and the filter in binary64, and exact Bayes in rational arithmetic on the binary64 parameters and ratios, rounded once; a Julia reference forms the same quantities from the specification, with exact rational Bayes as its oracle. The output agrees with both bit for bit. Chan’s preset reproduces its 12 filtered and 12 next-up values on the path U, U, D, U, D, D, U, U, U, D, U bit for bit. For valid parameters, with q1 not -0, the output equals MarkovSwitchProbLikelihood bit for bit on the ratio that is q2/q1 where o is 1, (1-q2)/(1-q1) where o is 0 and NaN elsewhere, for o = d.GT(0).MaskNonFinite(d).SetN(1, math.NaN()) and d = c.Delta(); with q1 = 1, q2 = 0 and stay probabilities in [0.001, 0.999], the output from bar 1 equals d.GT(0) on every bar with a finite change.
MarkovTransition
func (s Series) MarkovTransition(n, k, from, to int, alpha ...float64) Series
MarkovTransition returns the rolling estimate of the probability that state from is followed by state to, over the last n transitions of a state series whose valid values are the integer codes 0 to k-1.
The receiver z is the state series, and the window of bar t holds the n transitions (z[u-1], z[u]) for u = t-n+1 to t. So n counts transitions, not bars, and the window spans the n+1 bars t-n to t. Each transition counts in the row of its earlier state, from, and the column of its later state, to. With m the number of transitions in the window whose row is from, the support of the row, and c the number of those whose column is to, the output at bar t is c/m when m > 0.
A bar holds state j when its value is a whole number j from 0 to k-1, decided on the float before any conversion to an integer: NaN, the infinities, fractions, negative values and values of k or more are invalid states, and -0 is state 0. k runs from 1 to 98, so the codes of UpDown(1), UpDown(2) and UpDown(3) fit, at k = 3, 11 and 43, and those of UpDown(4) do not. UpDown(1) gives 0 for flat, 1 for down and 2 for up, but UpDownSum and RegimeDFA use +1 for up (trending, for RegimeDFA), so add 1 to their values first; a value that is then negative or fractional is still invalid. Both from and to must lie in [0, k).
The first valid index is n and the minimum length is n+1. The warm-up reads 0, not NaN, so an unmasked rule reads it as a state that never transitions or stays. Bars 0 to n-1 are +0 whatever z holds there.
The method is window-local: an invalid state at bar p gives NaN on [max(p, n), p+n], clipped to the last bar, since bar p is the later end of transition p and the earlier end of transition p+1, and the output recovers at bar p+n+1; several invalid bars give the union of their spans. The warm-up zeros take precedence over NaN, so an invalid bar inside the first window leaves the bars before n at 0, and the output on a prefix of z is the prefix of the output. Mask what should not count: z.SetN(1, math.NaN()) marks the first bar of UpDown(1), which has no earlier bar to compare with, and If can set NaN on the bars of a data gap, so that no window counts a transition across the gap.
When the window holds no transition from state from, the row is empty and the output is 0, which looks like an observed 0; empty rows are frequent at small n or large k. MarkovCount(n, k, from) is 0 exactly there, so it tells an empty row from an observed 0.
alpha is optional: only its first element is read, and the rest are ignored whatever they hold. Omitting it is the same as passing 0, bit for bit. A positive alpha adds alpha pseudo-counts to every cell of the row: the output is then the posterior mean of the row under a symmetric Dirichlet prior, (c + alpha)/(m + kalpha), with kalpha rounded to float64 before the addition by an explicit conversion, which the compiler may not fuse into the sum. An empty row then gives alpha/(kalpha), close to 1/k but not always exactly 1/k. The counts themselves are not changed. alpha must be at least 0 and finite, and so must kalpha; -0 behaves as 0. An invalid parameter (n outside 1 to len(z)-1, k outside 1 to 98, from or to outside [0, k), or an invalid alpha) gives len(z) zeros, and a nil or empty receiver gives an empty Series.
McKallip (1986) and Arrington (1993) put from in the rows, as here. Sherry puts the later state in the rows, the transpose; Trongone (2011) puts the from-states in the columns; Morley (2022) states a column-stochastic matrix, the transpose again; and Alexander, Scherer and Thompson print the initial state in the rows while their formula is the transpose of their prose.
Bar t reads z[t-n] to z[t] only, so the output is causal for point-in-time states. States defined with hindsight are not: McKallip’s chart patterns are labelled after they complete, Sherry cuts terciles over the whole sample, and Alexander, Scherer and Thompson re-cluster the whole history each month.
The sources estimate one table over the whole sample, and none shows a trading edge from a rolling transition probability. Gustafson’s share of up days after an up day is 513/1016 = 0.505, and Pearson chi-square re-tests of two of Sherry’s tables give 0.612 and 0.0976. At n = 50 a two-state row holds about 25 transitions, so a probability has a standard error near 0.1.
The method costs O(1) per bar after clearing its tables in O(k*k); it allocates the result and two counter tables. The current state’s stay probability has its own method; see the Markov Models introduction.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference (integer counters and exact fractions) and a Julia reference (exact rationals) agree with it bit for bit, and so does the composition z.EQ(to).Mul(z.EQ(from).Shift(1)).Sum(n).Ratio(z.EQ(from).Shift(1).Sum(n)) at every bar from n on whose window holds only valid states.
PatternEntropy
func (s Series) PatternEntropy(w int, n ...int) Series
PatternEntropy returns the rolling block entropy in bits of the w-bar words of up and not-up bars of any series over the trailing n words.
Bar u, for u >= 1, is up when s[u] is above s[u-1] and not-up otherwise: a flat bar is not-up, and there is no tolerance. The word that ends at bar u holds the w bits of bars u-w+1 to u, the newest bit lowest, as in UpDown, and the window of bar t holds the n words that end at bars t-n+1 to t, so it reads the w+n values s[t-n-w+1] to s[t]. With c the number of those words that have a given code, the output is the sum of c*log2(n/c) over the codes that occur, in ascending code order, divided by n; each term is rounded before it is added.
The output is in bits, from 0 to w, and is not negative zero: +0 when every word of the window is the same, and exactly w when all 2^w codes occur equally often. Divide by w for a rate per bar.
w runs from 1 to 12. n is optional: when it is omitted the window is 10*2^w words, ten for each code, and otherwise only its first element is read, which must be at least 1 and at most len(s)-w; a first element of 0 or less is invalid and is not read as the default. An invalid parameter gives len(s) zeros, and a nil or empty receiver gives an empty Series.
The first valid index is w+n-1 and the minimum length is w+n. The warm-up reads 0, not NaN, and 0 is also the reading of perfect order, so drop those bars with Window(-(w+n-1)), or mask them with SetN, before a percentile, a rank or a low-entropy rule reads the output.
The method is window-local: a value at bar p that is NaN or infinite gives NaN on the bars from w+n-1 on that lie in [p, p+w+n-1], and the output recovers at bar p+w+n.
The estimate is biased low when n is small beside 2^w. With w = 1 the output is a function of the share of up bars alone. Aronson and Masters read the same entropy with word length w over 10*2^w words and then transform it to a fixed range in a way they do not disclose; no such transform is applied here. Lopez de Prado’s rate per bit is this output divided by w on a series with no flat bars; his encoding drops flat bars, and his listing leaves out the last word. Massel’s rank-r entropy of a message of m wins and losses is PatternEntropy(r, m-r+1) at the last bar of a series of m+1 values that steps up for a win and down for a loss. No source shows a trading edge from it. CrossSectionalEntropy is a different quantity, the entropy of the shares of several series at one bar.
Cost is O(2^w) per bar, 4,096 cells at w = 12; a call allocates the result and one table of counts.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference and a Julia reference, with explicit loops in the same order, agree with each other digit for digit and with this method to 1e-12, and at w = 1 a composition of Delta, GT, Sum, Mul, Sub, Ratio, Max, Log2, Add and Div equals it bit for bit.
PatternMutualInfo
func (s Series) PatternMutualInfo(w int, n ...int) Series
PatternMutualInfo returns the rolling mutual information in bits between each bar’s up or not-up direction and the w directions before it, over the trailing n blocks.
Bar u, for u >= 1, is up when s[u] is above s[u-1] and not-up otherwise: a flat bar is not-up, and there is no tolerance. The block that ends at bar u pairs the w-bit word of bars u-w to u-1, the newest bit lowest, with the bit of bar u, and the window of bar t holds the n blocks that end at bars t-n+1 to t, so it reads the w+n+1 values s[t-n-w] to s[t]. With c the number of blocks that have a given word and bit, r the number that have the word and d the number that have the bit, the output is the sum of clog2((nc)/(r*d)) over the pairs that occur, divided by n. The pairs are read in ascending order of the word and then of the bit, the products are formed as integers, and each term is rounded before it is added.
The output is in bits, from 0 to 1 up to rounding, and it is not negative: math.Max turns a negative rounding residue into +0. It is +0 when the bit is independent of the word in the window. With w = 1 it equals MarkovMutualInfo(n, 2) on the up bits, bit for bit, from bar n+1 on.
w runs from 1 to 12. n is optional: when it is omitted the window is 10*2^(w+1) blocks, ten for each pair, and otherwise only its first element is read, which must be at least 1 and at most len(s)-w-1; a first element of 0 or less is invalid and is not read as the default, and n above 3,000,000,000 is invalid, a cap that keeps the integer products within int64. An invalid parameter gives len(s) zeros, and a nil or empty receiver gives an empty Series.
The first valid index is w+n and the minimum length is w+n+1. The warm-up reads 0, not NaN, and 0 is also the reading of independence, so drop those bars with Window(-(w+n)), or mask them with SetN, before a rule or a rank reads the output.
The method is window-local: a value at bar p that is NaN or infinite gives NaN on the bars from w+n on that lie in [p, p+w+n], and the output recovers at bar p+w+n+1.
The estimate is biased high: independent, equally likely bits average about 0.02 to 0.04 bits at the default windows for w from 1 to 5. Aronson and Masters read the same quantity with word length w over 10*2^(w+1) blocks and then transform it to a fixed range in a way they do not disclose; no such transform is applied here. With w = 1 the output is nearly a function of the phi coefficient of the two-by-two table and the base rate. No source shows a trading edge from it.
Cost is O(2^w) per bar, 8,192 cells at w = 12; a call allocates the result and two tables of counts.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference and a Julia reference, with explicit loops in the same order, agree with each other digit for digit and with this method to 1e-12, and at w = 1 a composition of Delta, GT, EQ, Shift, Sum, Mul, Ratio, Max, Log2, Add and Div equals it bit for bit.
QuantileState
func (s Series) QuantileState(n, k int) Series
QuantileState returns the rank class of each value within its trailing n-bar window, the number of the n-1 earlier values strictly below it mapped onto k classes numbered 0 to k-1, and NaN where the class is undefined.
For a bar t whose window s[t-n+1] .. s[t] holds only finite values, lt is the number of the n-1 earlier values s[t-n+1] .. s[t-1] that are strictly below s[t] by the IEEE comparison <, a whole number from 0 to n-1, and the class is (int64(k)int64(lt))/int64(n), Go’s truncating integer division of non-negative operands, returned as float64: a whole number from 0 to k-1. Class c holds the ranks lt from ceil(cn/k) to ceil((c+1)n/k)-1. When k divides n every class holds n/k ranks (7, 7 and 7 at n = 21, k = 3); otherwise the classes differ in size by one rank, each holding floor(n/k) or ceil(n/k) ranks and not always in favour of the lower classes: they hold 7, 7 and 6 ranks at n = 20, k = 3; 4, 3 and 3 at n = 10, k = 3; and 3, 2, 3 and 2 at n = 10, k = 4. With k = n the class is lt itself, and with k = 1 every valid bar is class 0. The product klt is below n*n, which fits int64 for n below 3,037,000,499.
The first valid index is n-1 and the minimum length is n. The warm-up reads NaN, not 0, and so does every bar whose window holds a non-finite value, every bar of a series shorter than n, and every bar for an invalid n < 2, k < 1 or k > n, which is decided by comparison before anything is allocated: a bar read as class 0 would be a valid state, and a chain of such bars would read as a state that always stays. An n above len(s) is a warm-up that does not end, not an error, and k has no cap beyond k <= n.
The class is window-local: bar t reads s[t-n+1] .. s[t] only, so a NaN or an infinity at bar p gives NaN on [p, p+n-1], clipped to the series, and the output recovers at bar p+n; several non-finite values give the union of their footprints. Both +Inf and -Inf are non-finite and are treated like a NaN. The output is start-invariant: dropping the first d bars leaves every bar t >= d+n-1 unchanged, and the output on a prefix of s is the prefix of the output. Under the IEEE comparison -0 equals +0, so neither is below the other, and class 0 is written as +0: no output is -0 and no output is a fraction. A nil or empty receiver gives an empty, non-nil Series, a one-bar receiver gives one NaN, and n = len(s) is valid and gives one class, at the last bar; the result is a fresh slice and the receiver is not modified.
Ties go to the lower class: strictly below is a definition, not a threshold, so an earlier value equal to s[t] is not counted and a constant series is class 0 at every valid bar; the tie vector 1, 1, 2, 2, 2, 3, 1, 2, 2 reads 1, 2, 0, 0, 0 from bar 4 at (5, 3) and 2, 4, 0, 1, 1 at (5, 5). Ties are binary64 ties, not decimal ones: of 25 pairs of daily AAPL changes that are equal in cents, only 15 are equal as doubles, so a caller who wants decimal ties rounds upstream, with d.Mul(100).Round() on changes d quoted to the cent. On discrete inputs the top classes can be unreachable: c.UpDownSum(1).SetN(1, math.NaN()) on 200 daily AAPL bars of 2023 occupies its classes 84, 95 and 0 times at (21, 3) and 82, 18, 69, 11 and 0 times at (20, 5).
The other tie conventions are compositions, bit for bit on finite windows from bar n-1. With le the number of the n window values at or below s[t], the current one included, and eq the number of earlier values equal to s[t], the ties-up class, ceil(kle/n)-1, is s.Mul(-1).QuantileState(n, k).Mul(-1).Add(float64(k-1)), and the mid-rank class, floor(k(2lt+eq)/(2n)), is, with up := s.QuantileState(n, n) and down := s.Mul(-1).QuantileState(n, n), up.Sub(down).Add(float64(n-1)).Mul(float64(k)).Div(float64(2*n)).Floor(), the negation turning the count of values below into the count of values above. On the tie vector at k = 3 they read 2, 2, 0, 2, 2 and 1, 2, 0, 1, 1 from bar 4.
The classes are serially dependent even on independent input, because consecutive windows share n-1 values: for an independent continuous series the chance of a stay is exactly 1/3 at n = k = 2 against the 1/2 of a fair coin, and about 0.33 at (21, 3), close to the 1/3 that three equal classes give without dependence. When k does not divide n the class probabilities are unequal, 0.35, 0.35 and 0.30 at n = 20, k = 3, so the null for a stay is the sum of the squared class probabilities rather than 1/k. A chain over these classes wants an n of at least 5k, so that every class holds several ranks.
Mask the upstream warm-up before ranking: unmasked, c.Log().Delta().StdDev(20).QuantileState(21, 5) reads 4, 4, 4, 3, 3, 3 at bars 20 to 25, all from the warm-up zeros of the standard deviation, whereas c.Log().Delta().StdDev(20).SetN(20, math.NaN()) has its first honest value at bar 20 and its first honest class at the upstream first valid index plus n-1, bar 40 at n = 21. Downstream, GT and EQ read NaN as 0, so a flag built from the classes keeps the mask only if it is put back: Carver’s merge of the two middle quartiles, with q := s.QuantileState(n, 4), is q.GT(0).Add(q.GT(2)).MaskNonFinite(q): it reads 0 for the lowest quartile, 1 for the middle two, 2 for the top one and NaN wherever q does.
RankPosition is the continuous rank, the rolling analogue of Carver’s continuous Q, on the 0 to 1 scale and 0 in its warm-up: s.RankPosition(n)[t] equals s.QuantileState(n, n)[t]*(1/(float64(n)-1)) bit for bit on finite windows from bar n-1, while the quotient s.QuantileState(n, n).Div(float64(n-1)) can differ from it by one ulp, as at n = 6 and lt = 3, where the quotient is 0.6 and RankPosition and the product are 0.6000000000000001. The quotient s.QuantileState(n+1, n+1).Div(float64(n)) is exactly j/n, with j, from 0 to n, the number of the n earlier values strictly below the current one, and equals s.RankPosition(n+1).Mul(float64(n)).Round().Div(float64(n)). PercentRank ranks a value the caller supplies, not each bar’s own, on the 0 to 1 scale: it gives -1 outside the window’s range, reads 0 in its warm-up and interpolates between order statistics. Quantile goes the other way, from a probability q to a value in the input’s units, and reads 0 in its warm-up.
McEwan’s share, the fraction le/n of the window at or below the current value, the current one included, is s.Mul(-1).QuantileState(n, n).Mul(-1).Add(float64(n)).Div(float64(n)), by the same negation; on the tie vector at n = 5 it reads 1, 1, 0.2, 0.8, 0.8 from bar 4, and on a tie-free window it is (lt+1)/n.
The published settings are documentation, not tuned parameters. McEwan ranks a 21-bar volatility over 21 bars, n = k = 21, and reads a crossing of 0.5 as a change of regime; Singha’s quintiles, with ties up, rank volume over 120 one-second bars of SPY data; Carver’s three regimes, at the 25th and 75th percentiles of an expanding window, have the rolling analogue QuantileState(n, 4) with the two middle classes merged, his gain coming from the expanding continuous rank rather than the rolling one; Connors’ percent rank of the one-day rate of change over 100 bars is QuantileState(101, 101) of RateOfChange(1), which ConnorsRSI(r, sp, p) scales to a percentage with Mul(100.0).Div(float64(p)).
Only McEwan’s published values are reproduced: his 33 printed ranks on 74 closes of 2010 match (class+1)/21 to four decimals. The rest is weaker: Sherry’s chain of tercile changes on daily data is not significant (p = 0.22 from his printed counts), Singha’s evidence is on one-second data rather than daily bars, and Carver’s gain comes from the expanding continuous rank, not from a rolling class.
The count is direct, O(n) per bar and O(len(s)*n) in all, with no sort, no tree and no scratch buffer; a call makes one allocation, the result, for any n and k, and none for an empty or nil receiver. Concurrent calls on a shared receiver are race-free and give the same bits.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: the Python reference (integer counts) and the Julia reference (count(<(v), w)) agree with this method bit for bit on every golden row; McEwan’s 74 closes give his 33 printed ranks, with (class+1)/21 within 0.00005 of each; QuantileState(n, n) equals the sum over j = 1 to n-1 of s.GT(s.Shift(j)) at every finite window; and with streak := c.ConsecUp().Sub(c.ConsecDown()), rank := c.RateOfChange(1).QuantileState(p+1, p+1) and pct := rank.Mul(100.0).Div(float64(p)), ConnorsRSI(r, sp, p) equals c.RSI(r).Add(streak.RSI(sp)).Add(pct).Div(3.0) from bar max(r, sp+1, p+1) on the AAPL closes and on tied inputs.
RunsZ
func (s Series) RunsZ(n int, tolerance ...float64) Series
RunsZ returns the Wald-Wolfowitz runs-test z-score of the up and not-up bars over the trailing n bars, negative when the window is streakier than chance and positive when it alternates.
Change u of a price series c runs from c[u-1] to c[u], for u >= 1, and its bit b[u] is 1 when the change is up and 0 when it is not. The window of bar t holds the n bits b[t-n+1] to b[t], so it spans the n+1 prices c[t-n] to c[t]. With n1 the number of up bits in the window, n2 = n - n1, R the number of runs (maximal blocks of equal bits, so R - 1 is the number of changes of bit), a = 2n1n2 and D = n*(R-1) - a, the output is D/sqrt(a*(a-n)/(n-1)). D and a are exact integers; after their conversion to float64 the expression is one product, one division, one square root and one division, each rounded once, so a fused multiply-add cannot change it. It is (R - E[R])/sigma_R, where E[R] = 1 + a/n is the expected number of runs given n1 and n2 and sigma_R^2 = a*(a-n)/(n^2*(n-1)) is the variance of R.
The sign is opposite to that of MarkovDirPhi and of Bryant’s -1 to +1 display, both positive when a direction tends to repeat. At tolerance 0, RunsZ(n) and MarkovDirPhi(n-1) read the same n bits, and when n1 is close to n2 the output is about -MarkovDirPhi(n-1)*sqrt(n). Under independence, given n1 and n2, z is close to a standard normal variable, and its two-sided p-value is erfc(|z|/sqrt(2)), computed as for MarkovDirPhi; the recipe is under Compositions.
The tolerance is a percentage, as in UpDown; the DirectionalChange family takes fractions (see DirectionalChange). A change is up when c[u] - c[u-1] exceeds |c[u-1]|*tolerance/100, strictly, as UpDown classifies it in float64, so 0.05 means 0.05 %, not 5 %, and a change equal to the threshold is not up. tolerance is optional: only its first element is read, and omitting it is tolerance 0. A flat change is not-up, with the downs, and it is not carried forward from the bit before it, so each bit depends on its own two prices only.
The first valid index is n and the minimum length is n+1. The warm-up reads 0, not NaN, so an unmasked rule reads it as no signal. Bars 0 to n-1 are +0, and n = len(c)-1 leaves one bar after the warm-up, the last.
The output is +0 on a degenerate window: all its bits up, all not-up, or n <= 2, where a <= n and the variance is 0, so n = 1 and n = 2 always give 0 and the useful minimum is 3. This 0 means undefined, not random. In a trend the minority bits leave the window one by one: on the bar where the last of them sits at the window’s left edge the output is -sqrt((n-2)/2), -3.74 at n = 30, and from the next bar it reads 0 for as long as the trend lasts, so the strongest trends read as no dependence.
The normal reading overstates significance when min(n1, n2) is small: with one minority bit at the window’s edge z is -3.74 at n = 30, although the exact chance of two runs or fewer given one minority bit is 2/30. Under independence with an up chance of 0.9 at n = 30, 4.7 % of windows fall below -1.96, against the nominal 2.5 %. A guard that keeps z only when the window holds at least five bits of each kind, the minimum Bryant asks of his proportion test, is under Compositions.
Read at every bar, the test is repeated on overlapping windows, so successive outputs are strongly correlated and its signals come in clusters. Under independence with equal chances of up and not-up at n = 30, |z| exceeds 1.96 on 4.8 % of bars, 2.5 % below and 2.3 % above, where the nominal level is 5 %.
A flat is not-up, so clustered flats, such as stale or forward-filled prices, lengthen the not-up runs and bias z negative without any directional dependence; flats that occur independently of each other leave the bits independent and do not.
For a sequence of trades, the receiver is the per-trade equity curve, the starting equity and then one value a trade, so that n counts trades, a winning trade is an up change and a trade that neither gains nor loses is not-up; each output belongs to its trade’s exit bar. Placing it at the entry bar uses the trade’s outcome before it is known.
The method is window-local: a NaN, +Inf or -Inf price at bar p leaves changes p and p+1 without a bit, so the output is NaN on [max(p, n), p+n], clipped to the last bar, and recovers at bar p+n+1; several bad prices give the union of their spans. The warm-up zeros take precedence over NaN. Bar t reads only bars t-n to t, so the output on a leading segment of c is the leading segment of the output, and dropping the first d bars leaves every bar from d+n on unchanged. A -0 price is finite, and -0 against +0 is a flat change.
No source shows a trading edge from the runs test. The evidence for its use is anecdotal and in-sample: most published uses compute one z over a whole trade history or backtest, from sequences of winning and losing trades, and choose and judge a money-management rule on the same trades, and the published tests on price bars are whole-sample counts with no trading rule. Bryant’s indicator, a rolling window over the last n trades updated at each exit, is the causal reading, which this method gives at every bar; he charts it and tests no rule on it.
Cost is O(1) per bar from three integer counters, the up bits, the changes of bit and the bits without a value in the window, and a call allocates only the result. An invalid n (outside 1 to len(c)-1) or tolerance (negative, NaN or infinite) gives len(c) zeros, and a nil or empty receiver gives an empty Series.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference and a Julia reference recount every window in integers and replay the expression bit for bit; with up := c.UpDownSum(1, tolerance).GT(0.0), n1 := up.Sum(n), x := n1.Mul(n1.Sub(float64(n))).Mul(-2.0), rm1 := up.Delta().Abs().Sum(n-1) and den := x.Mul(x.Sub(float64(n))).Div(float64(n-1)).Sqrt(), the output equals rm1.Mul(float64(n)).Sub(x).Div(den) bit for bit, for n up to 94,906,265, at every bar from n on whose prices c[t-n] to c[t] are finite; and the published sequences of Sherry, Bryant and Brown give their pinned values.
RunsZContinuity
func (s Series) RunsZContinuity(n int, tolerance ...float64) Series
RunsZContinuity returns the Wald-Wolfowitz runs-test z-score with the symmetric continuity correction, which moves the run count half a run towards its expected value and gives 0 when it is within half a run.
With n1, R, a and D counted as RunsZ counts them, the output is +0 when 2|D| <= n, where R lies within half a run of E[R], and otherwise (2D - sgn(D)n)/2 over RunsZ’s denominator sqrt(a(a-n)/(n-1)), where sgn(D) is 1 when D is above 0 and -1 when it is below: that is (R - E[R] - 1/2)/sigma_R above the mean and (R - E[R] + 1/2)/sigma_R below it, |R - E[R]| reduced by half a run with its sign kept. 2D - sgn(D)*n is one integer, formed in int64, converted to float64 once, halved exactly and divided by the denominator; no step adds a product to another term, so a fused multiply-add cannot change the output. The correction is the one Bradley gives for this test (Bradley (1960), WADD Technical Report 60-661, Ch. VIII, section 2, p. 206). He does not treat a count less than half a run from E[R], where the reduction would reverse the sign; the 0 there is this library’s convention, after the exception he makes to Yates’s correction for chi square (p. 68). At exactly half a run the correction itself gives 0.
Its magnitude is at most that of RunsZ, and it has RunsZ’s sign or is 0. Where 2D < -n it equals RunsZVince bit for bit, for n up to 94,906,265, since both raise the count by half a run there. Where 2D > n it reads half a run below RunsZ, where RunsZVince reads half a run above, so the correction is not RunsZVince’s term, which adds half a run on both sides.
The sign is that of RunsZ, opposite to that of MarkovDirPhi and of Bryant’s -1 to +1 display, and the two-sided p-value is erfc(|z|/sqrt(2)) of the output z, as for RunsZ. Under independence with equal chances of up and not-up at n = 30, |z| exceeds 1.96 on 3.5 % of windows, 1.9 % below and 1.6 % above, against 4.8 % for RunsZ and the nominal 5 %; with an up chance of 0.9, 3.3 % fall below -1.96, against 4.7 % for RunsZ and the nominal 2.5 %.
The tolerance is a percentage, as in UpDown; the DirectionalChange family takes fractions (see DirectionalChange). A change is up when c[u] - c[u-1] exceeds |c[u-1]|*tolerance/100, strictly, as UpDown classifies it in float64, so 0.05 means 0.05 %, not 5 %, and a change equal to the threshold is not up. tolerance is optional: only its first element is read, and omitting it is tolerance 0. A flat change is not-up, with the downs, and it is not carried forward from the bit before it, so each bit depends on its own two prices only.
The first valid index is n and the minimum length is n+1. The warm-up reads 0, not NaN, so an unmasked rule reads it as no signal. Bars 0 to n-1 are +0, and n = len(c)-1 leaves one bar after the warm-up, the last.
Besides the warm-up and an invalid call, the output reads +0 in two cases. On a degenerate window, as for RunsZ (all its bits up, all not-up, or n <= 2, where a <= n and the variance is 0), the 0 means undefined, not random, and the strongest trends read it. Within half a run of E[R] the 0 is a reading, a run count as close to its expectation as a whole number of runs allows; under independence with equal chances at n = 30 it is read on 15.4 % of windows. The output does not tell the two zeros apart.
The normal reading overstates significance when min(n1, n2) is small, as for RunsZ, and the guard under Compositions applies to this method too: with one minority bit at the window’s edge the output is -1.74 at n = 30, where RunsZ reads -3.74, and with that bit inside the window it reads 0. Read at every bar, the test is repeated on overlapping windows, so successive outputs are strongly correlated and its signals come in clusters.
A flat is not-up, so clustered flats, such as stale or forward-filled prices, lengthen the not-up runs and bias the output negative without any directional dependence.
For a sequence of trades, the receiver is the per-trade equity curve, the starting equity and then one value a trade, so that n counts trades, a winning trade is an up change and a trade that neither gains nor loses is not-up; each output belongs to its trade’s exit bar. Placing it at the entry bar uses the trade’s outcome before it is known.
The method is window-local: a NaN, +Inf or -Inf price at bar p leaves changes p and p+1 without a bit, so the output is NaN on [max(p, n), p+n], clipped to the last bar, and recovers at bar p+n+1; several bad prices give the union of their spans. The warm-up zeros take precedence over NaN. Bar t reads only bars t-n to t, so the output on a leading segment of c is the leading segment of the output, and dropping the first d bars leaves every bar from d+n on unchanged. A -0 price is finite, and -0 against +0 is a flat change.
No source shows a trading edge from the runs test, with the correction or without it. Bradley gives the correction for one test of a fixed sample, not for a window read at every bar.
Cost is O(1) per bar from three integer counters, the up bits, the changes of bit and the bits without a value in the window, and a call allocates only the result. An invalid n (outside 1 to len(c)-1) or tolerance (negative, NaN or infinite) gives len(c) zeros, and a nil or empty receiver gives an empty Series.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference and a Julia reference recount every window in integers and replay the expression bit for bit; with up, n1, x, rm1 and den as for RunsZ, d := rm1.Mul(float64(n)).Sub(x), sg := d.GT(0.0).Sub(d.LT(0.0)) and far := d.Abs().Mul(2.0).GT(float64(n)), the output equals d.Mul(2.0).Sub(sg.Mul(float64(n))).Mul(0.5).Mul(far).Div(den).Add(0.0) bit for bit, for n up to 94,906,265, at every bar from n on whose prices c[t-n] to c[t] are finite; and the published sequences of Sherry, Bryant and Brown and Bradley’s worked example give their pinned values.
RunsZVince
func (s Series) RunsZVince(n int, tolerance ...float64) Series
RunsZVince returns the runs-test z-score in the Vince form that MultiCharts and DeAmicis-Roberts report, which adds half a run and so leans towards alternation; prefer RunsZ unless a platform value must be matched.
Prefer RunsZ. With n1, R, a and D counted as RunsZ counts them, the output is (D + n/2)/sqrt(a*(a-n)/(n-1)), RunsZ’s denominator under a numerator half a run higher, that is (R + 1/2 - E[R])/sigma_R, RunsZ’s value plus 1/(2*sigma_R). The half run is added in every window, whichever side of E[R] the count R lies, so it is not a continuity correction, which would move R half a run towards E[R]: it shifts every window towards alternation. Under independence with equal chances of up and not-up at n = 30, 4.1 % of windows read above 1.96, against 2.3 % for RunsZ, and with an up chance of 0.9, 13.4 %. With one minority bit inside a window of 30 it reads 2.27, where RunsZ reads 0.27.
The sign is that of RunsZ, opposite to that of MarkovDirPhi and of Bryant’s -1 to +1 display. The two-sided p-value erfc(|z|/sqrt(2)) inherits the shift, which makes alternation look more significant than it is.
The tolerance is a percentage, as in UpDown; the DirectionalChange family takes fractions (see DirectionalChange). A change is up when c[u] - c[u-1] exceeds |c[u-1]|*tolerance/100, strictly, as UpDown classifies it in float64, so 0.05 means 0.05 %, not 5 %, and a change equal to the threshold is not up. tolerance is optional: only its first element is read, and omitting it is tolerance 0. A flat change is not-up, with the downs, and it is not carried forward from the bit before it, so each bit depends on its own two prices only.
The first valid index is n and the minimum length is n+1. The warm-up reads 0, not NaN, so an unmasked rule reads it as no signal. Bars 0 to n-1 are +0, and n = len(c)-1 leaves one bar after the warm-up, the last.
The output is +0 on a degenerate window, as for RunsZ: all its bits up, all not-up, or n <= 2, where a <= n and the variance is 0. This 0 means undefined, not random; the strongest trends read it, as for RunsZ.
The normal reading overstates significance when min(n1, n2) is small, as for RunsZ, and the guard under Compositions applies to this method too. Read at every bar, the test is repeated on overlapping windows, so successive outputs are strongly correlated and its signals come in clusters.
A flat is not-up, so clustered flats, such as stale or forward-filled prices, lengthen the not-up runs and bias the output negative without any directional dependence.
For a sequence of trades, the receiver is the per-trade equity curve, the starting equity and then one value a trade, so that n counts trades, a winning trade is an up change and a trade that neither gains nor loses is not-up; each output belongs to its trade’s exit bar. Placing it at the entry bar uses the trade’s outcome before it is known.
The method is window-local: a NaN, +Inf or -Inf price at bar p leaves changes p and p+1 without a bit, so the output is NaN on [max(p, n), p+n], clipped to the last bar, and recovers at bar p+n+1; several bad prices give the union of their spans. The warm-up zeros take precedence over NaN. Bar t reads only bars t-n to t, so the output on a leading segment of c is the leading segment of the output, and dropping the first d bars leaves every bar from d+n on unchanged. A -0 price is finite, and -0 against +0 is a flat change.
The platforms and articles that print this form compute one value over a whole sample, a trade history, a backtest or a run of daily signs, and those that act on it choose and judge a money-management rule on the same trades, so the evidence for it is anecdotal and in-sample.
Cost is O(1) per bar from three integer counters, the up bits, the changes of bit and the bits without a value in the window, and a call allocates only the result. An invalid n (outside 1 to len(c)-1) or tolerance (negative, NaN or infinite) gives len(c) zeros, and a nil or empty receiver gives an empty Series.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference and a Julia reference recount every window in integers and replay the expression bit for bit; with up, n1, x, rm1 and den as for RunsZ, the output equals rm1.Mul(float64(n)).Sub(x).Add(0.5*float64(n)).Div(den).SetN(n, 0) bit for bit, for n up to 94,906,265, at every bar before n and at every bar from n on whose prices c[t-n] to c[t] are finite; and the published sequences of Sherry, Bryant and Brown give their pinned values.
StateAtRisk
func (s Series) StateAtRisk(n int) Series
StateAtRisk returns the number of earlier finished spells of the current value that reached the current spell’s age, the support behind StateHazard and StateResidualLife.
It is a whole number stored as float64, and 0 means that no counted spell lasted this long, where the other three outputs read 0 for want of evidence. The receiver, the spells and the counted set are those of StateHazard: every finite value is a state, the age counts 1 on a spell’s first bar, and the counted spells are the finished spells of the current value whose length became known at a bar k with t0-n < k <= t0, where t0 is the first bar of the current spell. On a spell’s first bar the count is the size of the set, and it does not rise within a spell. Use it as a mask: a hazard, survival or residual life over fewer than about five spells, tested as StateAtRisk >= 5, is weak evidence.
n runs from 2 with no upper limit: n >= len(s) is the expanding set, a deliberate departure from the usual 1 <= n <= len-1, and n below 2 gives len(s) zeros. The first valid index is 0 and the minimum length is 1. A nil or empty receiver gives an empty Series.
Missing data follows the censoring class of StateHazard: a bar that is NaN or infinite reads NaN, and so does every bar of the spell that follows it, except that the first spell after leading missing bars reads 0; the first spell, a spell that starts after a missing bar, a spell ended by one and the current spell are left out of every set. Do not feed Swings, SwingsHL, SwingPoints or Pivots, which are dated with hindsight.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference in exact fractions and a Julia reference in exact rationals, written apart from this code, agree with it bit for bit. On the up state of finite closes c it equals D.GTE(a).Sum(N) bit for bit on every up bar whose window does not hold the first spell, with D, a and N as in StateHazard, which explains the exception.
StateCount
func (s Series) StateCount(state Series, n, h int) Series
StateCount returns the number of the last n realised anchor bars whose state equals the current bar’s state, the sample behind StateUpProb and StateMean.
It is an integer in [0, n], exact and start-invariant, and the denominator of StateUpProb and StateMean. The receiver is an outcome series whose value at bar j+h is paired with state[j], as for StateMean; with a price receiver it is StateUpProb’s denominator wherever StateUpProb is not NaN. A state code is a finite integer with |v| <= 2^53; -0 is the code 0; NaN marks an undefined bar, and any other value (an infinity, a fraction, a larger magnitude) is undefined too.
state is right-aligned with the receiver s at the most recent bar; with m the overlap, bars before it read 0, the first valid index is n+h-1 within the overlap and the minimum overlap is n+h; invalid n or h give len(s) zeros. The warm-up reads 0, not NaN, and an unseen state reads 0 as well.
The method is window-local, as StateMean is: a non-finite outcome at overlap bar p, when p >= h, makes NaN the bars p to p+n-1, an undefined state at p makes NaN the bar p and the bars p+h to p+h+n-1, and the output recovers after the footprint, bit for bit.
This method is listed under “Compositions” in the “Markov Models”, “Volatility Estimators” and “Volume Flow” categories.
Verification: at every bar with a defined state and valid anchors the output equals the composition state.EQ(v).Shift(h).Sum(n) for the current code v, bit for bit.
StateHazard
func (s Series) StateHazard(n int) Series
StateHazard returns the empirical hazard of the current state’s spell: the share of earlier finished spells of the same value that ended at the current age, among those that reached it.
The receiver is a state series in which every finite value is a state, a spell is a run of equal values whose age counts 1 on its first bar, and an earlier spell is finished when a valid bar of another value follows it; the output is E/G, with G the counted spells that lasted at least the current age and E those that lasted exactly it. A hazard of 0.25 at age 3 says that a quarter of the counted spells that reached three bars ended there. The value is a share in [0, 1], formed by one division of two whole numbers.
Any finite value is a state: 0/1 flags, signs of -1 and +1, UpDown codes, negative values and fractions all work, compared with exact float64 equality, so +0 and -0 are one state; NaN and the infinities are missing bars. This is StateAge’s domain, wider than the whole numbers 0 to k-1 that MarkovTransition reads and the signed whole numbers that StateUpProb reads.
The counted spells are the finished spells of the current value whose length became known at a bar k with t0-n < k <= t0, where t0 is the first bar of the current spell and a length is known one bar after the spell’s last. The window is anchored at the start of the current spell, so the set is fixed for the whole spell, and n must exceed the length of the spells of other values that lie between two spells of one value, or the set is empty. n runs from 2 with no upper limit: n >= len(s) counts every earlier spell, the expanding set, a deliberate departure from the usual 1 <= n <= len-1, and n below 2 gives len(s) zeros, because the bar before a spell cannot hold the spell’s value.
Four kinds of spell are left out of every set: the first spell of the series, a spell that starts after a missing bar, a spell ended by a missing bar, and the current spell. This is the censoring class of missing data, a departure from the windowed footprint: a missing bar reads NaN, and so does every bar of the spell that follows it, whose age is only a lower bound, while later spells may read differently because the cut spells have left their sets. The exception is the first spell after leading missing bars: it is the first spell of the data and reads 0.
The first valid index is 0 and the minimum length is 1; there is no warm-up. The output is 0 while no spell is counted, which covers the whole first spell and every later spell until a spell of the same value has finished inside the window, and it is 0 again once the current age exceeds every counted spell. A hazard of 0 there is want of evidence, not persistence: mask it with the support, for instance StateAtRisk >= 5. A nil or empty receiver gives an empty Series. The output at a bar reads only that bar and earlier ones, and the output on a prefix of s is the prefix of the output, for every n.
Build the state so that missing bars stay missing. GT, LT and EQ read a comparison with NaN as 0, which extends a spell without a word, and the warm-up zeros of a state builder look like a real first spell, so mask them with SetN or MaskNonFinite. Do not feed Swings, SwingsHL, SwingPoints or Pivots: they are dated with hindsight, so the hazard would read the future.
The complement 1 - StateHazard is the share of the spells at risk that continued, the empirical chance that the spell lasts another bar. StateSurvival is a different quantity, the share of all counted spells that outlasted the current age. Giner and Zakamulin (2023) print the hazard as f(n)/(1 - F(n)); read with a cumulative F that includes n, that gives (1-p)/p on geometric durations with stay probability p, where this method gives 1-p. MarkovDuration gives the expected length of a spell under the geometric model, whose hazard is constant, and ConsecUpContinuation gives the continuation share of up runs of the current length, capped at maxRun, among the bars of a trailing window, while StateHazard counts whole spells in a window anchored at the spell’s start, for any state. The hazards in published tables of runs and of days spent above an average are close to flat, and a year of daily bars leaves many ages with fewer than five spells at risk, so a single hazard is weak evidence.
The cost is O(len(s)) in time and memory for every n. A receiver whose values seldom repeat, such as a price series passed by mistake, has spells of one bar and reads 0 almost everywhere.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference in exact fractions and a Julia reference in exact rationals, written apart from this code, agree with it bit for bit. On the up state of finite closes c, c.Delta().GT(0) with its first bar masked, it equals D.EQ(a).Sum(N).Ratio(D.GTE(a).Sum(N)) bit for bit on every up bar whose window does not hold the first spell, with D = c.ConsecUp().Shift(1).Mul(c.Delta().LTE(0)), a the value of c.ConsecUp() at the bar and N = min(n, len(c)) + a - 1. The composition counts the first spell of the series when it is an up spell whose k lies in the window, and the method leaves it out.
StateMean
func (s Series) StateMean(state Series, n, h int) Series
StateMean returns the rolling mean of the outcome that followed the current bar’s state, the average of the receiver at bar j+h over the last n realised anchor bars j whose state equals the current state.
The receiver is an outcome series y whose value at bar i is realised at i, for example c.Delta(h) or c.RateOfChange(h); y[j+h] is paired with state[j]. At bar t the anchors are the n bars j from t-h-n+1 to t-h, and the output is the mean of y[j+h] over the anchors whose state equals the current one. RateOfChange reads a zero base as 0, so mask such bars with MaskNonFinite or SetN; StateMeanLogReturn is the log-return case. A state code is a finite integer with |v| <= 2^53; -0 is the code 0; NaN marks an undefined bar, and any other value (an infinity, a fraction, a larger magnitude) is undefined too.
state is right-aligned with the receiver s at the most recent bar; with m the overlap, bars before it read 0, the first valid index is n+h-1 within the overlap and the minimum overlap is n+h; invalid n or h give len(s) zeros. The warm-up reads 0, not NaN.
When the window holds no valid anchor in the current state the output is 0, not NaN, as Ratio reads an empty denominator; mask it on StateCount, for example where c.StateCount(state, n, h).GTE(5) is 0.
The method is window-local: a non-finite outcome at overlap bar p, when p >= h, makes NaN the bars p to p+n-1, and an undefined state at p makes NaN the bar p and the bars p+h to p+h+n-1; a non-finite outcome stays queued until it leaves, and the output recovers after the footprint.
The mean is a compensated rolling sum divided once by the count; the sum’s grouping follows the history of each state’s queue, so the output is not start-invariant and the last bit of a mean can differ after an undefined state bar; counts and probabilities are exact. The remaining rules are StateUpProb’s: both inputs are known at their bar’s close, builder warm-ups are valid codes to mask, and for h > 1 the effective sample can be as small as m_v/h.
The cost is O(1) amortised per bar plus at most three map lookups; the allocations are the output, the window’s index and rows and one queue per state, grown in steps, so their number is bounded by the number of codes and by n, not by the length.
This method is listed under “Compositions” in the “Markov Models”, “Volatility Estimators” and “Volume Flow” categories.
Verification: the references compute every mean in exact arithmetic and in a binary64 replay of the rolling sum; the output matches the replay bit for bit, and with a constant state bar t equals y[h:].Average(n) at bar t-h, bit for bit, wherever the window is finite.
StateMeanLogReturn
func (s Series) StateMeanLogReturn(state Series, n, h int) Series
StateMeanLogReturn returns the rolling mean h-bar log return that followed the current bar’s state, with one horizon h for both the return and the state lag.
The return at bar i is ln(c[i]) - ln(c[i-h]) over the overlap, a difference of logarithms, so it equals c.Log().Delta(h).StateMean(state, n, h) bit for bit for any lengths. The receiver c is a price series: a non-positive or non-finite price gives a non-finite return, which occupies the window and masks it. A state code is a finite integer with |v| <= 2^53; -0 is the code 0; NaN marks an undefined bar, and any other value (an infinity, a fraction, a larger magnitude) is undefined too.
state is right-aligned with the receiver s at the most recent bar; with m the overlap, bars before it read 0, the first valid index is n+h-1 within the overlap and the minimum overlap is n+h; invalid n or h give len(s) zeros. The warm-up reads 0, not NaN.
The method is window-local: a non-positive or non-finite price at overlap bar p makes NaN the bars p to p+n-1, when p >= h, and the bars p+h to p+h+n-1, and an undefined state at p makes NaN the bar p and the bars p+h to p+h+n-1; the output recovers after the footprint, and an unseen state reads 0, not NaN.
The mean is a compensated rolling sum divided once by the count; the sum’s grouping follows the history of each state’s queue, so the output is not start-invariant and the last bit of a mean can differ after an undefined state bar; counts and probabilities are exact. The remaining rules are StateMean’s and StateUpProb’s.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: the references compute every mean with logarithms taken at high precision then rounded, and an exact sum, which the output matches within 1e-14, and the composition c.Log().Delta(h).StateMean(state, n, h) matches it bit for bit at every bar.
StateResidualLife
func (s Series) StateResidualLife(n int) Series
StateResidualLife returns the mean number of further bars that earlier finished spells of the current value lasted beyond the current age, among those that reached it.
It is the sum of D - a over the counted spells of length D >= a, divided by their number, so a spell that ended at the current age adds 0. The receiver, the spells and the counted set are those of StateHazard: every finite value is a state, the age a counts 1 on a spell’s first bar, and the counted spells are the finished spells of the current value whose length became known at a bar k with t0-n < k <= t0, where t0 is the first bar of the current spell. The value is in bars, at least 0, and it is 0 exactly when StateHazard is 1 or no counted spell reached the current age. Under the geometric model the expected further life is the same at every age, MarkovDuration less one, and this method measures it age by age.
n runs from 2 with no upper limit: n >= len(s) is the expanding set, a deliberate departure from the usual 1 <= n <= len-1, and n below 2 gives len(s) zeros. The first valid index is 0 and the minimum length is 1. The output is 0 while no spell is counted and once the current age exceeds every counted spell, which is want of evidence and not a forecast that the spell ends: read it beside StateAtRisk. A nil or empty receiver gives an empty Series.
Missing data follows the censoring class of StateHazard: a bar that is NaN or infinite reads NaN, and so does every bar of the spell that follows it, except that the first spell after leading missing bars reads 0; the first spell, a spell that starts after a missing bar, a spell ended by one and the current spell are left out of every set. Do not feed Swings, SwingsHL, SwingPoints or Pivots, which are dated with hindsight.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference in exact fractions and a Julia reference in exact rationals, written apart from this code, agree with it bit for bit. On the up state of finite closes c it equals D.Sub(a).Mul(D.GTE(a)).Sum(N).Ratio(D.GTE(a).Sum(N)) bit for bit on every up bar whose window does not hold the first spell, with D, a and N as in StateHazard, which explains the exception.
StateSurvival
func (s Series) StateSurvival(n int) Series
StateSurvival returns the share of earlier finished spells of the current value that lasted longer than the current spell’s age, the age percentile of the current spell.
It is (G - E)/M over the M counted spells: the share that outlasted the current age, not the chance that the current spell continues, which is 1 - StateHazard. The receiver, the spells and the counted set are those of StateHazard: every finite value is a state, the age counts 1 on a spell’s first bar, and the counted spells are the finished spells of the current value whose length became known at a bar k with t0-n < k <= t0, where t0 is the first bar of the current spell. M is their number, G the number that lasted at least the current age and E the number that lasted exactly it. The count is strict: a spell exactly as long as the current age has not outlasted it. The value is a share in [0, 1] that does not rise within a spell. The share that reached the current age, ties included, is the survival of the bar before, and 1 on a spell’s first bar when the set is not empty.
n runs from 2 with no upper limit: n >= len(s) is the expanding set, a deliberate departure from the usual 1 <= n <= len-1, and n below 2 gives len(s) zeros. The first valid index is 0 and the minimum length is 1. The output is 0 while no spell is counted and from the age of the longest counted spell on, so read it beside StateAtRisk. A nil or empty receiver gives an empty Series.
Missing data follows the censoring class of StateHazard: a bar that is NaN or infinite reads NaN, and so does every bar of the spell that follows it, except that the first spell after leading missing bars reads 0; the first spell, a spell that starts after a missing bar, a spell ended by one and the current spell are left out of every set. Do not feed Swings, SwingsHL, SwingPoints or Pivots, which are dated with hindsight.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference in exact fractions and a Julia reference in exact rationals, written apart from this code, agree with it bit for bit. On the up state of finite closes c it equals D.GT(a).Sum(N).Ratio(D.GT(0).Sum(N)) bit for bit on every up bar whose window does not hold the first spell, with D, a and N as in StateHazard, which explains the exception.
StateUpChiSquareYates
func (s Series) StateUpChiSquareYates(state Series, n int, p0 float64, tolerance ...float64) Series
StateUpChiSquareYates returns Merrill’s Yates-corrected chi-square of how often the current state has been followed by an up bar over the trailing n bars, against an up probability p0 fixed in advance.
At bar t the anchors are the n bars j from t-n to t-1, counted up as StateUpZScore counts them. With m the anchors in the current state, u the up ones among them, E1 = mp0, E2 = m(1-p0) and D = |u - E1|, the output is (D-0.5)^2/E1 + (D-0.5)^2/E2, Merrill’s chi-square with Yates’s correction and one degree of freedom, whose 5 %, 1 % and 0.1 % points are 3.84, 6.635 and 10.83. The correction is clamped: when D <= 0.5 the output is 0, where Merrill’s printed form, unclamped, rises again as D falls below 0.5. E1 is rounded once before the subtraction, as in StateUpZScoreFixed, and E2 is m*(1-p0), not m - E1. The output is defined at m = n, and when D > 0.5 and (D-0.5)^2/E1 exceeds the largest float64, as at p0 = 5e-324 with u >= 1, it is +Inf; with u = 0 the clamp gives 0 there. The horizon is one bar, as for StateUpZScore.
p0 is fixed in advance and has no default; it is valid when 0 < p0 < 1, and +0, -0, 1, NaN, an infinity or a value outside give len(s) zeros. A full-sample rate, such as Merrill’s 52.1 % rising share, uses data from after every earlier bar and so looks ahead; take p0 from data that ends before the series starts, or fix it a priori. A fixed 0.5 under a trend confounds the trend with dependence (Oswalt’s point), which StateUpZScore avoids by testing against the window’s own up rate.
A state code is a finite integer with |v| <= 2^53; -0 is the code 0; NaN marks an undefined bar, and any other value (an infinity, a fraction, a larger magnitude) is undefined too. Unlike MarkovTransition, which reads the codes 0 to k-1, this method reads any signed whole number in that range, so negative codes and the codes of UpDown(k) for every k up to 24 are rows of their own, found by a lookup.
state is right-aligned with the receiver s at the most recent bar; with L the overlap, bars before it read 0, the first valid index is n within the overlap and the minimum overlap is n+1; invalid n, p0 or tolerance give len(s) zeros. n is valid when 1 <= n <= L-1. An empty receiver gives an empty Series. The warm-up reads 0, not NaN, and a warm-up zero is not a finding of no evidence against p0.
When the window holds no valid anchor in the current state, m = 0, the output is 0, not NaN, the empty-denominator value of StateUpProb; mask it on c.StateCount(state, n, 1), which reads 0 there.
The method is window-local: from the first valid index a bar is NaN exactly when its own state is undefined or an anchor of its window is invalid, and anchor j is invalid when its state is undefined or c[j] or c[j+1] is not finite, whatever its code. A non-finite price or an undefined state at overlap bar p makes NaN the bars p to p+n, and the output recovers after them, bit for bit. The warm-up takes precedence over these rules: its bars read 0 whatever the inputs.
Read it against those points only when both expected cells, E1 and E2, are at least 5. Read at every bar, the test is repeated, so a nominal 5 % signal fires by chance on many bars, in clusters; do not gate silently on m, but read it from StateCount.
Both inputs are known at their bar’s close and an anchor’s outcome is realised by bar t, so the output is causal. Builder warm-ups and UpDown’s flat reading of a missing price are valid codes counted silently, so mask them, as in c.UpDown(2).SetN(2, math.NaN()), and lag a later-closing market’s state with state.Shift(1).SetN(1, math.NaN()).
Merrill tests each weekday against the whole sample’s rising share and prints the unclamped form with the expectations rounded to whole days; his price-pattern table marks its significant rows without printing the statistic. His tables are whole-sample tests, of which this method is the rolling, causal recast, and no source shows that filtering on it improves trading.
The tolerance is a percentage, as in UpDown; the DirectionalChange family takes fractions (see DirectionalChange). The output is a chi-square value with one degree of freedom under the binomial null with rate p0.
The cost is O(1) amortised per bar plus at most three map lookups, and a call makes a handful of allocations (the output, the window’s rows and its index), at most one when the parameters are invalid. The rows are kept for every code the state has shown, so a state of many codes, such as UpDown(20), makes more allocations as the series grows.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: two references, in Python and Julia, recount every window in integers and replay the expression bit for bit, and reference B also reproduces Merrill’s printed weekday values in his literal form; at every bar whose state is v with valid anchors and the tolerance omitted the output equals the composition of Sub, Abs, Clamp, Mul, Div and Add over the counts of v from EQ, Shift, Delta, GT, Mul and Sum, bit for bit at a p0 where a fused multiply-add would change it.
StateUpProb
func (s Series) StateUpProb(state Series, n, h int, tolerance ...float64) Series
StateUpProb returns the rolling estimate of the probability that the price rises over the next h bars given the current state, the share of the last n realised anchor bars in the current bar’s state after which the price rose.
At bar t the anchors are the n bars j from t-h-n+1 to t-h, and anchor j counts as up when c[j+h] - c[j] exceeds |c[j]|*tolerance/100, strictly, as UpDown classifies it; a flat change is not up. The receiver c is a price series. The tolerance is a percentage, as in UpDown; the DirectionalChange family takes fractions (see DirectionalChange). h pairs state[t-h] with the change realised at t, which is Shift(h)’s sign.
A state code is a finite integer with |v| <= 2^53; -0 is the code 0; NaN marks an undefined bar, and any other value (an infinity, a fraction, a larger magnitude) is undefined too. Unlike MarkovTransition, which reads the codes 0 to k-1, this method reads any signed whole number in that range, so negative codes and the codes of UpDown(k) for every k up to 24 are rows of their own, found by a lookup.
state is right-aligned with the receiver s at the most recent bar; with m the overlap, bars before it read 0, the first valid index is n+h-1 within the overlap and the minimum overlap is n+h; invalid n, h or tolerance give len(s) zeros. n and h are valid when h >= 1 and 1 <= n <= m-h. An empty receiver gives an empty Series. The warm-up reads 0, not NaN, and a warm-up zero is not a zero chance of a rise.
When the window holds no valid anchor in the current state the output is 0, not NaN, as Ratio reads an empty denominator; mask it on StateCount, for example where c.StateCount(state, n, h).GTE(5) is 0.
The method is window-local: from the first valid index a bar is NaN exactly when its own state is undefined or an anchor of its window is invalid, and an anchor is invalid when its state is undefined or either of its prices is not finite, whatever its code. A non-finite price at overlap bar p makes NaN the bars p to p+n-1, when p >= h, and the bars p+h to p+h+n-1; an undefined state at p makes NaN the bar p and the bars p+h to p+h+n-1, and the output recovers after the footprint, bit for bit. The warm-up takes precedence over these rules: its bars read 0 whatever the inputs.
Both inputs are known at their bar’s close, so the output is causal. Lag a later-closing market’s state with state.Shift(1).SetN(1, math.NaN()). Builder warm-ups (UpDown’s first k bars, Shift’s pad, GT against a warming Average) are valid codes counted silently, so mask them, as in c.UpDown(2).SetN(2, math.NaN()); a mask of k bars delays the first numeric bar to n+h+k-1. For h > 1 consecutive anchors share h-1 bars, so the effective sample of a state whose anchors fall on consecutive bars is about m_v/h rather than m_v, and between the two when they are spread out.
The source tables (Vakkur, Pagonidis, Trongone, Merrill, Aronson, Snead) are whole-sample statistics; Weiderman found patterns with 65 % success in random coin tosses, and no source demonstrates an edge out of sample.
AverageWhere, QuantileWhere, StdDevWhere and FuncWhere summarise the receiver on the last event bars, the current bar counted and the value held, while this method selects the current state’s row and reads only outcomes realised by t. MarkovDirNext is the case h = 1 with UpDown(1)’s states.
The cost is O(1) amortised per bar plus at most three map lookups, and a call makes a handful of allocations (the output, the window’s rows and its index), at most one when the parameters are invalid.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: the references compute every row in exact arithmetic and agree bit for bit, each probability a correctly rounded quotient; at every bar with a defined state and valid anchors the output equals the composition e.Mul(U).Sum(n).Ratio(e.Sum(n)), with e the state’s equality flag shifted by h and U the up flag of the h-bar change; and c.StateUpProb(c.UpDown(1, tol).SetN(1, math.NaN()), n, 1, tol) equals c.MarkovDirNext(n, 2, tol) from bar n+1 on finite prices.
StateUpZScore
func (s Series) StateUpZScore(state Series, n int, tolerance ...float64) Series
StateUpZScore returns the adjusted-residual z-score of how often the current state has been followed by an up bar over the trailing n bars, against the window’s overall up rate.
At bar t the anchors are the n bars j from t-n to t-1, and anchor j counts as up when c[j+1] - c[j] exceeds |c[j]|tolerance/100, strictly, as UpDown classifies it; a flat change is not up. The receiver c is a price series. With v the current bar’s state, m is the number of anchors in state v, u the number of those that were up and U the number of up anchors in the window, and the output is z = (un - mU)/sqrt(m(n-m)U(n-U)/n), Haberman’s adjusted residual of the cell (v, up) in the two-by-two table of state v or another against up or not: the signed square root of the table’s Pearson chi-square, or sqrt(n) times its phi. It lies in [-sqrt(n), sqrt(n)], which rounding can pass by a few units in the last place, and it is +0 when m = n, one state filling the window as a constant state does, or when U is 0 or n, so n = 1 always gives 0. The horizon is one bar: the outcomes of longer horizons overlap, which makes the anchors dependent, so the method has no h.
It is meant for states of more than two codes, such as the patterns of UpDown(k), quantile classes or weekdays, and for states built from other series or timeframes; any state series is accepted. For the receiver’s own up or not-up state, state = c.Delta().GT(0).SetN(1, math.NaN()) with the tolerance omitted, z equals (2*state-1)*sqrt(n)*MarkovDirPhi(n) from bar n+1 on finite prices, within four units in the last place; such callers should prefer MarkovDirPhi, which takes the prices directly and carries their NaN footprint. The equivalence holds only at tolerance 0, since MarkovDirPhi has no tolerance; it also caps n at 2,000,000.
A state code is a finite integer with |v| <= 2^53; -0 is the code 0; NaN marks an undefined bar, and any other value (an infinity, a fraction, a larger magnitude) is undefined too. Unlike MarkovTransition, which reads the codes 0 to k-1, this method reads any signed whole number in that range, so negative codes and the codes of UpDown(k) for every k up to 24 are rows of their own, found by a lookup.
state is right-aligned with the receiver s at the most recent bar; with L the overlap, bars before it read 0, the first valid index is n within the overlap and the minimum overlap is n+1; invalid n or tolerance give len(s) zeros. n is valid when 1 <= n <= L-1. An empty receiver gives an empty Series. The warm-up reads 0, not NaN, and a warm-up zero is not a finding of no departure from the base rate.
When the window holds no valid anchor in the current state, m = 0, the output is 0, not NaN, the empty-denominator value of StateUpProb; mask it on c.StateCount(state, n, 1), which reads 0 there.
The method is window-local: from the first valid index a bar is NaN exactly when its own state is undefined or an anchor of its window is invalid, and anchor j is invalid when its state is undefined or c[j] or c[j+1] is not finite, whatever its code. A non-finite price or an undefined state at overlap bar p makes NaN the bars p to p+n, and the output recovers after them, bit for bit. The warm-up takes precedence over these rules: its bars read 0 whatever the inputs.
Under independence z is close to a standard normal variable, so |z| > 1.96 is a nominal two-sided 5 % signal, but only when the smallest expected cell, min(m, n-m)*min(U, n-U)/n, is at least 5 (the usual five per cell; McKallip’s own threshold, on the observed counts, is stricter): with m = 1, u = 1, U = 5 and n = 100 the output is 4.38, although the exact chance of that count is 0.05. Read at every bar, the test is repeated, so a nominal 5 % signal fires by chance on many bars, in clusters. Do not gate silently on m: choosing bars by m, or states by how often they occur, conditions on the outcomes and biases z; read m from StateCount and decide openly.
Both inputs are known at their bar’s close and an anchor’s outcome is realised by bar t, so the output is causal. Builder warm-ups (UpDown’s first k bars, Shift’s pad, GT against a warming Average) and UpDown’s flat reading of a missing price are valid codes counted silently, so mask them, as in c.UpDown(2).SetN(2, math.NaN()); a mask of k bars makes the bars n to n+k-1 NaN and n+k the first numeric bar. Lag a later-closing market’s state with state.Shift(1).SetN(1, math.NaN()).
The sources’ tests are whole-sample: Merrill’s weekday and price-pattern tables, Weiderman’s coin tosses and Sherry’s soymeal days; this method is their rolling, causal recast, and no source shows that filtering on it improves trading. Weiderman describes his THHH count as a little over two standard deviations above its mean: the pooled z of his counts, 2.0985, agrees with that, and so does the binomial z against one half, 1.9825, under a rounded standard deviation, and the source does not settle which he meant. Merrill’s one-sample form against the pooled rate is z*sqrt(1 - m/n), with m from StateCount, smaller in magnitude and so conservative. Oswalt’s point that the expectation must allow for the trend is why the base rate is the window’s own U/n; his trend-adjusted chi-square for Sherry’s table is the square of this z.
The tolerance is a percentage, as in UpDown; the DirectionalChange family takes fractions (see DirectionalChange). The output is in standard deviations under independence.
The cost is O(1) amortised per bar plus at most three map lookups, and a call makes a handful of allocations (the output, the window’s rows and its index), at most one when the parameters are invalid. The rows are kept for every code the state has shown, so a state of many codes, such as UpDown(20), makes more allocations as the series grows.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: two references, in Python and Julia, recount every window in integers and replay the expression’s operations in the same order, bit for bit; at every bar whose state is v with valid anchors the output equals the composition of EQ, Shift, Delta, GT, Sum, Mul, Add, Sub, Div and Sqrt over the counts of v with the tolerance omitted, bit for bit; and the method’s values on the published counts of Weiderman, Merrill and Sherry are pinned, the square of Sherry’s being Oswalt’s printed 0.61.
StateUpZScoreFixed
func (s Series) StateUpZScoreFixed(state Series, n int, p0 float64, tolerance ...float64) Series
StateUpZScoreFixed returns the binomial z-score of how often the current state has been followed by an up bar over the trailing n bars, against an up probability p0 fixed in advance.
At bar t the anchors are the n bars j from t-n to t-1, counted up as StateUpZScore counts them, and with m the anchors in the current state and u the up ones among them the output is (u - mp0)/sqrt(mp0*(1-p0)), the binomial z of u successes in m trials at p0. The product m*p0 is rounded once before the subtraction, so a fused multiply-add cannot change the result. The output is finite for every valid p0, and it is defined at m = n, where StateUpZScore reads 0. The horizon is one bar, as for StateUpZScore.
p0 is fixed in advance and has no default; it is valid when 0 < p0 < 1, and +0, -0, 1, NaN, an infinity or a value outside give len(s) zeros. A full-sample rate, such as Merrill’s 52.1 % rising share, uses data from after every earlier bar and so looks ahead; take p0 from data that ends before the series starts, or fix it a priori. A fixed 0.5 under a trend confounds the trend with dependence (Oswalt’s point), which StateUpZScore avoids by testing against the window’s own up rate.
A state code is a finite integer with |v| <= 2^53; -0 is the code 0; NaN marks an undefined bar, and any other value (an infinity, a fraction, a larger magnitude) is undefined too. Unlike MarkovTransition, which reads the codes 0 to k-1, this method reads any signed whole number in that range, so negative codes and the codes of UpDown(k) for every k up to 24 are rows of their own, found by a lookup.
state is right-aligned with the receiver s at the most recent bar; with L the overlap, bars before it read 0, the first valid index is n within the overlap and the minimum overlap is n+1; invalid n, p0 or tolerance give len(s) zeros. n is valid when 1 <= n <= L-1. An empty receiver gives an empty Series. The warm-up reads 0, not NaN, and a warm-up zero is not a finding of no departure from p0.
When the window holds no valid anchor in the current state, m = 0, the output is 0, not NaN, the empty-denominator value of StateUpProb; mask it on c.StateCount(state, n, 1), which reads 0 there.
The method is window-local: from the first valid index a bar is NaN exactly when its own state is undefined or an anchor of its window is invalid, and anchor j is invalid when its state is undefined or c[j] or c[j+1] is not finite, whatever its code. A non-finite price or an undefined state at overlap bar p makes NaN the bars p to p+n, and the output recovers after them, bit for bit. The warm-up takes precedence over these rules: its bars read 0 whatever the inputs.
Under the binomial null |z| > 1.96 is a nominal two-sided 5 % signal when both expected cells, mp0 and m(1-p0), are at least 5. Read at every bar, the test is repeated, so a nominal 5 % signal fires by chance on many bars, in clusters; do not gate silently on m, but read it from StateCount.
Both inputs are known at their bar’s close and an anchor’s outcome is realised by bar t, so the output is causal. Builder warm-ups and UpDown’s flat reading of a missing price are valid codes counted silently, so mask them, as in c.UpDown(2).SetN(2, math.NaN()), and lag a later-closing market’s state with state.Shift(1).SetN(1, math.NaN()).
Weiderman’s binomial test of his coin-toss counts is the case p0 = 0.5: it gives 1.9825 for THHH, and exactly -4 and -1 for his two weekday examples. His and Merrill’s tables are whole-sample tests, of which this method is the rolling, causal recast, and no source shows that filtering on it improves trading.
The tolerance is a percentage, as in UpDown; the DirectionalChange family takes fractions (see DirectionalChange). The output is in standard deviations under the binomial null with rate p0.
The cost is O(1) amortised per bar plus at most three map lookups, and a call makes a handful of allocations (the output, the window’s rows and its index), at most one when the parameters are invalid. The rows are kept for every code the state has shown, so a state of many codes, such as UpDown(20), makes more allocations as the series grows.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: two references, in Python and Julia, recount every window in integers and replay the expression bit for bit; at every bar whose state is v with valid anchors and the tolerance omitted the output equals u.Sub(e1).Div(e1.Mul(1 - p0).Sqrt()), with e1 := m.Mul(p0) and m and u the counts of v from EQ, Shift, Delta, GT, Mul and Sum, bit for bit at a p0 where a fused multiply-add would change it; and Weiderman’s two weekday examples give the four and one standard deviations he states.
WonhamBull
func (s Series) WonhamBull(lambda1, lambda2, mu1, mu2, sigma float64, opts ...float64) Series
WonhamBull returns Dai, Zhang and Zhu’s clipped Euler discretisation of the Wonham filter, the probability that prices are in the bull regime of a two-state regime-switching model with caller-fixed annual parameters.
The receiver c holds positive finite prices: bar t has an observation only when c[t-1], c[t] and their ratio c[t]/c[t-1] are all finite and positive, so a bad price (NaN, infinite, zero or negative) has no observation and the filter takes its prediction step on that bar and the next, and a ratio that overflows to +Inf or underflows to 0 makes its own bar a prediction step. The move across a bad price is dropped, not bridged.
Dai, Zhang and Zhu (Trend Following Trading under a Regime Switching Model, SSRN working paper 1762118, 2009; SIAM Journal on Financial Mathematics 1, 2010) model the price as a geometric Brownian motion with volatility sigma whose drift is mu1 in the bull regime and mu2 in the bear regime, the paper requiring mu1 > mu2; the regime is a two-state Markov chain that leaves the bull regime at intensity lambda1 and the bear regime at intensity lambda2 (pp. 5-6). Wonham’s filter for the bull probability p is dp = f(p) dt + g(p) d(log c) (eq (16), p.16), where, with L = lambda1+lambda2, d = mu1-mu2 and s2 = sigmasigma, f(p) = (-Lp + lambda2) - dp(1-p)((dp + mu2) - s2/2)/s2 and g(p) = dp(1-p)/s2, each evaluated left to right. As the paper does in simulation and testing (p.17), the method takes explicit Euler steps clipped to [0, 1]: with p bar t-1, bar t is min(max(u, 0), 1), where u = p + f(p)*dt + g(p)r with the observation r = ln(c[t]/c[t-1]), taken from the single ratio, and u = p + (-Lp + lambda2)*dt, the prediction step, on a bar without one. Each product that feeds a sum is rounded on its own, so a fused multiply-add cannot change a bit. The pages are those of the SSRN PDF; the SIAM pagination differs and is not given here.
lambda1 and lambda2 are intensities per year, mu1 and mu2 the annual drifts of the price’s return dc/c in the two regimes and sigma its annual volatility. opts is [dt [, p0]]: dt is the bar length in years, 1/250 (a daily bar) when omitted, and p0 is the probability at bar 0, xi when omitted. p0 = 0 is a legal start, so omitting p0 is the only way to ask for xi. The published sets, given as (lambda1, lambda2, mu1, mu2, sigma), are DJIA (0.36, 2.53, 0.18, -0.77, 0.184), in Table 1 (p.15) and the second Table 6 (p.21), and SP500 (0.353, 2.208, 0.196, -0.616, 0.173) and NASDAQ (2.158, 2.3, 0.875, -1.028, 0.31), in the second Table 6, estimated on 1962-2008 for DJIA and SP500 and on 1991-2008 for NASDAQ, with sigma the mean of the two regimes’ volatilities. They are documentation, not causal parameters.
xi is the one root of f in [0, 1] (f(0) = lambda2 > 0 and f(1) = -lambda1 < 0, p.16): on constant prices the filter is attracted to it, and the paper calls it an unbiased choice for p0 (p.17). The method finds it by 200 bisection steps on [0, 1], keeping the upper half when f(mid) > 0 and the lower half otherwise, and returns the midpoint of the last interval: 0.8499830985463823, 0.814018556495999 and 0.5494359846638477 for the DJIA, SP500 and NASDAQ sets. xi, not the stationary share lambda2/(lambda1+lambda2) of the regime chain, is the default p0, an exception to the stationary-share start of a regime filter that follows the paper’s recommendation; with the DJIA set the share is 0.875 and xi 0.850.
The method is recursive and not start-invariant: bar t depends on p0 and on every price up to c[t], so a later start gives different bars, while the output on a prefix of c is the prefix of the output, bit for bit. On constant prices at dt = 1/250 the output from either extreme start, p0 = 0 or p0 = 1, is within 1e-6 of xi from bar 540, 601 and 242 on with the DJIA, SP500 and NASDAQ sets, the settling length of the start.
Invalid inputs give len(c) zeros at O(1) cost: more than two opts; a parameter or option that is NaN or infinite; lambda1, lambda2 or sigma at or below 0, or mu1 below mu2; dt at or below 0, which is an error and not the default; p0 outside [0, 1]; (lambda1+lambda2)dt above 1, where the prediction step would overshoot; or a failure of the derived check. With A = d + |mu2| + s2, G = d/s2 and B = L + lambda2 + (dA)/s2, the derived check requires s2 > 0 and L, d, s2, A, dA, G, B and 1 + Bdt + 1500*G all finite. That bounds every intermediate of a step for p in [0, 1] and any finite positive ratio, whose logarithm lies within 744.45 of 0, because g(p) <= G/4 keeps |g(p)*r| at most 1500*G; so no step can give NaN, which the clip could not remove. mu1 == mu2 is allowed, the no-information case, and p0 = -0 is written +0.
There is no warm-up: bar 0 is p0 and has no observation, so the first valid index is 0 and the minimum length is 1; an empty receiver gives an empty result. Invalid parameters give aligned zeros, which read as bear with certainty. A nil receiver gives an empty, non-nil Series; the method costs O(1) per bar, allocates only the result and does not modify c.
The model observed once a bar, with the regime held for the bar, is a two-state hidden Markov chain with stay probabilities p11 = (lambda2 + lambda1e)/(lambda1+lambda2) and p22 = (lambda1 + lambda2e)/(lambda1+lambda2), where e = exp(-(lambda1+lambda2)*dt), emitting Gaussian log returns with means (mu1 - sigma^2/2)*dt and (mu2 - sigma^2/2)dt and standard deviation sigmasqrt(dt); its exact Bayes filter is not this method’s Euler step.
The Euler step is accurate while kappa = (mu1-mu2)*sqrt(dt)/sigma stays below about 0.4: kappa is 0.327, 0.297 and 0.388 for the DJIA, SP500 and NASDAQ sets at dt = 1/250. Beyond that range the Euler step degrades and the exact Bayes filter of the previous paragraph is the better choice. Even with the DJIA set the two differ: on the 200 daily AAPL closes of 2023 from 16 March, the Euler filter differs from the exact-Bayes filter of the same model (that discretisation, the same p0 = xi and the same log returns) by up to 0.086 (bar 134; mean absolute difference 0.0115), and the inclusive 0.934/0.768 latch (state 1 at >= 0.934, 0 at <= 0.768, starting from 0) disagrees on 8 of 200 bars.
The published clip has two artefacts. A large move overshoots and the output is exactly 0 or 1: on the same closes the 4.7% rise of bar 35 clips to 1 with the DJIA and SP500 sets. And because g(0) = g(1) = 0, the bar after a clip ignores its price move: bar 36 is 1 - lambda1*dt, 0.99856 with the DJIA set.
WonhamDrift weights mu1 and mu2 by this probability and its complement.
The evidence is in-sample. The published sets and the paper’s trading thresholds come from a hindsight division of the index histories into bull and bear markets at rallies of 24% and declines of 19% (p.20), over the years that the trading tests then cover. The paper’s remark that the DJIA already includes dividends (p.22) is wrong for a price index, so the DJIA results omit dividends, and there trend following, which grows a dollar to 26.03, barely beats the 23.44 of ten-year bonds (Table 8, p.22). Zakamulin and Giner (Optimal Trend-Following in a Markov Switching Model, working paper, 25 April 2022, pp. 1 and 6-7) show that under a two-state Markov-switching model the optimal trend-following rule is an exponential moving average.
This method is listed under “Compositions” in the “Markov Models” category.
Verification: a Python reference (decimal arithmetic at 60 digits, and a binary64 column) and a Julia reference (BigFloat at 256 bits, and a Float64 column) agree bit for bit on every golden row and serve as the alternative oracle, because no identity with an existing method exists; the method matches the binary64 column bit for bit on xi and every row without a logarithm, and the exact column within 1e-12. It gives 0.5 on every bar when lambda1 == lambda2 and mu1 == mu2 and p0 is 0.5 or omitted; with mu1 == mu2 it ignores the prices, bad ones included, and follows the closed form pbar + (p0 - pbar)*(1 - (lambda1+lambda2)*dt)^t, pbar the stationary share, within 1e-15; c.Mul(2^k), for a k that keeps the prices normal, gives the same output as c; and constant prices give xi on every bar at dt = 1/250 for the three published sets.
WonhamDrift
func (s Series) WonhamDrift(lambda1, lambda2, mu1, mu2, sigma float64, opts ...float64) Series
WonhamDrift returns the filtered annual drift of Dai, Zhang and Zhu’s regime-switching model, the bull and bear drifts weighted by WonhamBull’s probability and its complement.
The receiver c holds positive finite prices: bar t has an observation only when c[t-1], c[t] and their ratio c[t]/c[t-1] are all finite and positive, so a bad price (NaN, infinite, zero or negative) has no observation and the filter takes its prediction step on that bar and the next, and a ratio that overflows to +Inf or underflows to 0 makes its own bar a prediction step. The move across a bad price is dropped, not bridged.
With p the output of WonhamBull for the same arguments, the clipped Euler recursion of Dai, Zhang and Zhu’s filter (SSRN working paper 1762118, 2009: the model pp. 5-6, eq (16) p.16 and the clipped recursion p.17), bar t is float64((mu1-mu2)*p[t]) + mu2, the product rounded before the sum, so it equals c.WonhamBull(…).Mul(mu1-mu2).Add(mu2) bit for bit. It is an annual drift of the price’s return dc/c, in the units of mu1 and mu2, and lies from mu2 to (mu1-mu2)+mu2: exactly mu2 where p = 0, and (mu1-mu2)+mu2 where p = 1, which can miss mu1 by the roundings of mu1-mu2 and of the sum (0.17999999999999994 for the DJIA set’s mu1 = 0.18).
The parameters and their units, opts = [dt [, p0]] with dt = 1/250 and p0 = xi when omitted (p0 = 0 is a legal start), and the published sets are WonhamBull’s, documentation and not causal parameters.
xi, the default p0, is the root of the filter’s drift term f in [0, 1], found by WonhamBull’s pinned bisection, not the stationary share lambda2/(lambda1+lambda2): an exception to the stationary-share start of a regime filter that follows the paper’s recommendation (p.17).
The method is recursive and not start-invariant, as WonhamBull is, while the output on a prefix of c is the prefix of the output, bit for bit. On constant prices at dt = 1/250 the drift from either extreme start, p0 = 0 or p0 = 1, is within 1e-6 of its value at xi from bar 538, 591 and 254 on with the DJIA, SP500 and NASDAQ sets, the settling length of the start.
Invalid inputs give len(c) zeros at O(1) cost: more than two opts; a parameter or option that is NaN or infinite; lambda1, lambda2 or sigma at or below 0, or mu1 below mu2; dt at or below 0, which is an error and not the default; p0 outside [0, 1]; (lambda1+lambda2)*dt above 1, where the prediction step would overshoot; or a failure of WonhamBull’s derived check, which also keeps mu1-mu2 finite. mu1 == mu2 is allowed and gives mu2 on every bar.
There is no warm-up: bar 0 is the drift at p0 and has no observation, so the first valid index is 0 and the minimum length is 1; an empty receiver gives an empty result. Invalid parameters give aligned zeros, which read as a flat drift. A nil receiver gives an empty, non-nil Series; the method costs O(1) per bar, allocates only the result and does not modify c.
The exact Bayes alternative, the Euler step’s validity (kappa below about 0.4) and its gap on AAPL are WonhamBull’s. So are the clip artefacts: at a clip to 1 the drift is (mu1-mu2)+mu2, and at a clip to 0 it is mu2.
The evidence caveats are WonhamBull’s: the published sets are in-sample, from a hindsight bull and bear division of the years the paper’s trading tests cover (p.20).
This method is listed under “Compositions” in the “Markov Models” category.
Verification: it equals c.WonhamBull(…).Mul(mu1-mu2).Add(mu2) bit for bit for valid parameters, and the drift columns of the Python reference (decimal at 60 digits) and the Julia reference (BigFloat at 256 bits), which agree bit for bit, serve as its alternative oracle, because its one identity reaches only WonhamBull, itself checked against them.
Compositions
The CAM transition recipe marks a bar whose CAM state is CT after a DN bar, counts those events over a window of n transitions and gives the rolling probability of CT after DN. Its state is the CAM code cam of “ADX states: CAM and Chesler’s no-trend” in this category, passed with its first valid index fc. The count and the probability are the numerator and the ratio of the same window counts, so they agree exactly on windows of valid states; the count drops an invalid bar silently where MarkovTransition reads NaN, as the masks below say. The CAM code is built from h, l and c, and the recipes that combine several series pair them by position; an empty operand gives zeros; date-align first.
DN-to-CT event and its rolling probability (Star; the Traders’ Tips)
dnct := cam.EQ(2).Shift(1).Mul(cam.EQ(1))
events := dnct.Sum(n).SetN(fc+n, 0)
pCTgivenDN := cam.MarkovTransition(n, 4, 2, 1).SetN(fc+n, 0)- Codes:
camholds 3 UP, 2 DN, 1 CT and 0 PB, and NaN where it has no state.dnctis 1 on a CT bar whose previous bar is DN and 0 on every other bar;eventscounts those bars among the last n, the transitions of the window;pCTgivenDNis the share of the window’s transitions out of DN that end in CT, and 0 on an empty row, a window with no DN bar before its last. EQ comes before Shift: Shift’s pad is 0, whichcam.Shift(1).EQ(0)reads as PB, so a PB-to-CT event written with the Shift first fires on bar 0 (on the codes 1, 1, 0, 1, 0, 1 it reads 1, 0, 0, 1, 0, 1 where the event is 0, 0, 0, 1, 0, 1). For DN the pad cannot fire, but the order is the same. - First valid index: fc+1 for
dnctand fc+n foreventsandpCTgivenDN, where fc,cam’s first valid index, is max(nA+1, slow), 26 at the published ADX 10 and MACD 12 and 26; the minimum length is one more.dnctis 0 before fc+1 by construction, since EQ reads the NaN warm-up as not in state and the pad is 0, so it takes no SetN; convert it withdnct.SetN(fc+1, math.NaN())before a state consumer. MarkovTransition is 0 before n and NaN on [n, fc+n), 26 bars at the published lengths, andSetN(fc+n, 0)gives 0 on both, as it does on the partial windows ofevents. fc is a variable because a CAM code with other lengths, or codes built by hand, start elsewhere: at ADX 10 and MACD 3 and 8 fc is 11. - Masks:
dnctandeventsdrop a NaN state silently, because EQ reads NaN as not in state, where MarkovTransition reads NaN on every bar whose window holds one; soevents.Ratio(cam.EQ(2).Shift(1).Sum(n))equalspCTgivenDNon the bars from fc+n whose window holds only valid states, and after a bad pricepCTgivenDNis NaN for ever whilednctis 0 andeventscounts only the events before it. A NaN, +Inf or -Inf high, low or close at bar p makescamNaN from max(p, 1) to the end, as the ADX section says, sodnctis 0 from p,eventsfalls to 0 within n bars andpCTgivenDNis NaN from max(p, fc+n) to the end. No output is -0. - Alignment: h, l and c must have equal length: ADX returns an empty series on a length mismatch, so
camand the three outputs are empty too. - Anchors: E:
events.Ratio(cam.EQ(2).Shift(1).Sum(n))equalspCTgivenDNbit for bit on every bar from fc+n whose window holds only valid states, empty rows included, where both are 0: on the 200 AAPL bars of 2023 on 164, 154 and 124 bars at n = 10, 20 and 50, of which 43, 11 and 0 are empty rows. E: on the codes NaN, 2, 1, 1, 2, 2, 1, 0, 2, 1dnctis 0, 0, 1, 0, 0, 0, 1, 0, 0, 1. E: AIQ’s rule reads its raw DN rule one bar back and its CT rule, each with a non-strict ADX test and a strict MACD test: ADX at least its previous value and MACD below its previous value on the DN bar, ADX at most its previous value and MACD above it on the CT bar. Its CT is the strict CT, and its DN differs from the strict DN only at an exact ADX tie and at an unchanged MACD, so the AIQ event equalsdncton AAPL, which holds no ADX tie, and differs from it on 12 bars of a constant-range series, whose ADX is exactly 0, the first at bar 28. G: on AAPL at ADX 10 and MACD 12 and 26dnctfires on 3 bars, the first bar 109. - Sources: Star (Stocks & Commodities V36:1) defines the four CAM patterns. In the January 2018 Traders’ Tips, Denning’s AIQ listing enters on the rule BuyDNCT, DN on the previous bar and CT on this one, which he chose as the best of his three rules over 48 months of the NASDAQ 100 with a nine-bar hold (0.62% a trade); its data-length guard is not reproduced. The TradersStudio listing’s optimised pair is DN then PB, on S&P futures from 1991 to 2014, the same recipe with
cam.EQ(2).Shift(1).Mul(cam.EQ(0)). Both pairs were chosen in sample: fix the pair a priori or choose it walk-forward. Neither listing has a window; the rolling probability is MarkovTransition’s estimate of the same transition, the causal reading. - Pinned by
TestRecipeCAMTransition; runnable exampleExampleSeries_MarkovTransition_camTransition.
First valid index of the transition stages
| Stage | First valid index f | Before f |
|---|---|---|
EQ(y), Mul(y), Ratio(s2) | 0 | nothing |
Shift(k) | k | zeros |
Sum(n) | n - 1 | the sum of the bars so far |
MarkovTransition(n, k, from, to) | n | zeros |
Continuation Index state
ci := c.ContinuationIndex(n, gamma, order)
long := ci.If(func(x float64) bool { return x == 0 }, math.NaN(), ci.GT(0.0)).MaskNonFinite(ci).SetN(2*n-2, math.NaN())- Codes:
longis 1 while Ehlers’s Continuation Index is above 0, its UltimateSmoother above its Laguerre filter, and 0 while it is below, strict. A bar whose index is exactly 0 is NaN, not a code. - First valid index: 2n-2, 78 at the published Length 40 (38 at 20 and 118 at 60); the minimum length is one more. ContinuationIndex reads 0 before it, which the
Ifalready makes NaN;SetNstates the warm-up. - Masks: the index is exactly 0 where the n-bar average of |US - LG| is 0, as on a constant series, and at an exact crossing of the two filters; neither is a direction, so
Ifmasks both without recomputing the average. A constant series is NaN from bar 78 at n = 40. The UltimateSmoother and the Laguerre filter are recursive and never recover: a NaN, +Inf or -Inf close at bar p makes the index NaN from p on, solongis NaN from max(p, 2n-2) to the end, with no recovery. - Anchors: E:
longequals a per-bar reading of the method’s value, NaN for NaN or 0. W: a port of the article’s three listings as printed, with the four differences below, gives the same state aslongon every bar from 2n-2 of the 200 AAPL bars of 2023 at Length 40, 20 and 60 (122, 162 and 82 bars), its values lying within 2.4e-3, 9.7e-2 and 9.9e-5 of the method’s from bar 3n-2. T: on AAPL at n = 40 no index lies within 0.052 of 0;longholds 51 bars at 0 and 71 at 1 and stays 115 times in 121 transitions. G: MarkovTransition and MarkovNext return a value onlongonce their windows are valid. - Sources: Ehlers (Stocks & Commodities V43:10) smooths the price with his UltimateSmoother over half the length and with a Laguerre filter of damping gamma and the given order, divides twice their difference by the n-bar average of its absolute value and applies the inverse Fisher transform, which is tanh; he takes Length as the intended holding period, with gamma 0.8, order 8 and Length 40 as his defaults. ContinuationIndex departs from his listings in four ways, which the state inherits: (1) where the average of |US - LG| is 0 his listing keeps the previous value, so the index repeats, while ContinuationIndex gives 0, which
longmasks; (2) his UltimateSmoother uses the constants 1.414 and 3.14159 and a cosine in degrees, where the method uses the square root of 2 and pi in radians and its exact-form recursion; (3) his Length/2 is a real number and the method’s n/2 an integer, so they differ for odd n, and the state is stated for even n, as the published 20, 40 and 60 are; (4) his Laguerre stages start at 0 on the first bar, while the method starts them at the UltimateSmoother’s value at bar n-1 and reads 0 before, hence the first valid index. The article prints no inequality on the index, only the test of the average against 0, so the state follows the strict house rule. The entry thresholds that some Traders’ Tips add are trading rules, GLE-223’s, and are not used. - Pinned by
TestRecipeContinuationIndexStates; runnable exampleExampleSeries_MarkovTransition_continuationIndex.
Indicator-regime alphabets turn published regime indicators into the integer state codes that the state-chain methods of this category count. Codes are 0-based integers, and a bar that cannot be classified is NaN, not a code: GT, LT and EQ read NaN as false, so every alphabet below ends with MaskNonFinite on the stages it compares, the gap idiom of this category, and with SetN(F, math.NaN()) on its warm-up, where F is its first valid index and F+1 its minimum length. The legacy stages read 0 or pass their input through before their own first valid bar (the stage table at the end), and those values would otherwise read as real states. The recipes that combine several series pair them by position; an empty operand gives zeros; date-align first. If the lengths differ by off bars, convert the bars before the overlap with SetN(off+F, math.NaN()) before a state consumer. QuantileState needs k <= n and gives NaN on every bar otherwise, so the rank windows m below are at least 5, or 3 for the DFA alternative. Each section’s anchors are tagged E (an exact identity), G (a property every valid output has), T (a tolerance or margin) or W (a witness that agrees as documented, not exactly). Every alphabet here has at most five codes and feeds MarkovTransition and MarkovNext, and MarkovChiSquare and MarkovCramerV test its transition table for dependence. Named builders for the CAM states, the risk regime, the Volatility Switch regime and the four-state trend are candidates for GLE-223’s regime filters, which own these indicators as filters and any trading rule built on them; the recipes here stay compositions. No source models the transitions of these states, so their chains are descriptive: states built on long windows persist by construction, and a stay probability is to be compared with the same alphabet’s on independent returns, not with 1/k.
ADX states: CAM and Chesler’s no-trend
adx := c.ADX(h, l, c, nA)
macd := c.MACD(fast, slow)
cam := adx.Delta().GT(0.0).Mul(2.0).Add(macd.Delta().GT(0.0)).MaskNonFinite(adx, macd).SetN(max(nA+1, slow), math.NaN())
a14 := c.ADX(h, l, c, 14)
noTrend := a14.LT(15.0).MaskNonFinite(a14).SetN(14, math.NaN())
noTrendLE := a14.LTE(15.0).MaskNonFinite(a14).SetN(14, math.NaN())- Codes:
camis Star’s CAM pattern: 3 UP (ADX and MACD both rising), 2 DN (ADX rising, MACD not), 1 CT (MACD rising, ADX not) and 0 PB (neither), each “rising” strict, so an unchanged value is not rising.noTrendis 1 while ADX(14) is below 15 andnoTrendLEwhile it is 15 or less, else 0. - First valid index: max(nA+1, slow) for
cam, 26 at the published ADX 10 and MACD 12 and 26, and 14 fornoTrendandnoTrendLE; the minimum length is one more. ADX is 0 on bars 0 to nA-1 and MACD’s first full value is at slow-1, so their changes are first valid at nA+1 and slow. - Masks: ADX and MACD are recursive and never recover: a NaN, +Inf or -Inf high, low or close at bar p makes ADX NaN from max(p, 1) on, and a bad close makes MACD NaN at p and not finite from max(p, fast-1) on: before fast-1 both averages pass the close through, and the fast average’s seed at fast-1 holds it. An infinite close makes MACD infinite, not NaN, on bars max(p+1, fast-1) to slow-2 and NaN from max(p, slow-1) on; the mask catches both. So all three states are NaN from max(p, 1) to the end, with no recovery; a bad bar 0 lies inside the warm-up. Without the mask, GT and LT read ADX’s NaN as not rising and as not below 15, so
camwould read PB andnoTrend“trend” for ever. - Alignment: h, l and c must have equal length: ADX returns an empty series on a length mismatch, so the three states are empty too.
- Anchors: E:
cam.GTE(2.0)is “ADX rising”,camless twice that is “MACD rising”, andcam.EQ(3.0),EQ(0.0),EQ(2.0)andEQ(1.0)are the TradeStation listing’s UP, PB, DN and CT conditions. E: each state equals a per-bar loop of ADX and MACD. E: the mask equals the earlier expanding guard.Add(bad)withbad := h.Add(l).Add(c).Mul(0.0).Sum(len(c))on every bar of every injected series, NaN for NaN, a bad bar 0 included. E: AIQ’s precedence and MetaStock’s non-strict ADX give the strict codes on the 200 AAPL bars of 2023, which hold no ADX tie, and differ from them on every bar from 26 of a constant-range series, whose ADX is exactly 0. T: on AAPL no change of ADX(10) lies within 1.16e-3 of 0 and none of MACD(12, 26) within 2.31e-3, and ADX(14) is at least 15.865 from bar 14, sonoTrendis constant 0 there; on a synthetic trend-range-trend series ADX(14) runs from 8.7 to 100 and comes no closer to 15 than 0.22, andnoTrendtakes both codes. G: MarkovTransition and MarkovNext return a value oncamandnoTrendonce their windows are valid. - Sources: Star (Stocks & Commodities V36:1) defines the four patterns from the direction of ADX(10) and MACD(12, 26) and names no order of them. The January 2018 Traders’ Tips print three listings: TradeStation’s, a strict four-way partition, which
camreproduces; AIQ’s, with non-strict ADX tests and the precedence UP, DN, PB, CT coded 2, -2, 1 and -1 (3, 2, 0 and 1 here); and TradersStudio’s, with the same codes and a slow MACD of 25, probably a misprint for 26. Star’s MetaStock sidebar tests ADX non-strictly, so an unchanged ADX satisfies two patterns, and rounds ADX to a whole number, which is not reproduced. The Tips’ transition rules (AIQ’s DN then CT, TradersStudio’s DN then PB) were chosen in sample. On AAPLcamholds 51 PB, 31 CT, 41 DN and 51 UP bars and stays 110 times in 173 transitions. Chesler (V15:9) reads ADX(14) below 15 as an absence of trend, and his Fig 10 caption “15 or less”,noTrendLE; Le Beau and Lucas’s rising ADX above 15, Kramer’s environments and the other published ADX levels are under “ADX environments and the rising-ADX gate (Kramer; Le Beau and Lucas)” in the “Average Directional Index” category. - Pinned by
TestRecipeCAMStates; runnable exampleExampleSeries_MarkovTransition_cam.
DFA regime and its calibrated alternative
a := c.DFAAlpha(n)
am := a.If(func(x float64) bool { return x == 0 }, math.NaN(), a).SetN(n, math.NaN())
dfa := am.GT(0.55).Sub(am.LT(0.45)).Add(1.0).MaskNonFinite(am)
rel := am.QuantileState(m, 3)- Codes:
dfais 0 mean-reverting (alpha below 0.45), 1 neutral and 2 trending (alpha above 0.55), both strict: RegimeDFA’s defaults plus 1.relis the class of alpha among its last m values, 0 low, 1 middle and 2 high persistence relative to the series’ own recent alpha. - First valid index: n for
dfaand n+m-1 forrel; the minimum length is one more. DFAAlpha’s first value is at bar n-1, but its window of returns there holds the warm-up change 0 of bar 0, soSetN(n)drops it. n must be at least 20, below which alpha is 0 and every bar NaN. - Masks: DFAAlpha gives 0, not NaN, on its warm-up, on any window holding a non-finite return and where fewer than two scales have a positive fluctuation (a straight profile, as from closes with a constant change), so
amtreats every alpha of exactly 0 as undefined. A bad close at bar p spoils the returns of bars p and p+1, so both states are NaN on [p, p+n] fordfaand on [p, p+n+m-1] forrel, and recover after. - Anchors: E:
dfaequalsc.RegimeDFA(n).Add(1.0)on every bar from n where alpha is not 0; RegimeDFA reads neutral on its warm-up and mean-reverting where alpha is 0, anddfais NaN on both. E:relisQuantileState(m, 3)of the masked alpha and equals a per-bar rank. T: on AAPL no alpha lies within 1.99e-3 of a threshold at n = 40 and within 5.30e-3 at n = 64. T: the band is not centred on independent returns: on 20 seeded log-normal walks of 3,000 bars, with daily returns of 1%, 57.6% of the bars read trending and 13.4% mean-reverting at n = 64, which is whyrelranks alpha against its own recent values instead. - Sources: DFAAlpha and RegimeDFA under “Regime Detection”, whose 0.55 and 0.45 are the library’s defaults; no published source defines this regime. On AAPL
dfaholds 22, 17 and 121 bars of the three codes and stays 107 times in 159 transitions at n = 40, and 12, 14 and 110 bars and 106 stays in 135 at n = 64. The block calls DFAAlpha once and sharesambetween the two states. - Pinned by
TestRecipeDFARegime; runnable exampleExampleSeries_MarkovTransition_dfaRegime.
Risk regime (Di Prima and Baruffa)
r := hyg.Div(ief)
z := r.Sub(r.Average(nz)).Div(r.StdDev(nz).Mul(math.Sqrt(float64(nz) / float64(nz-1))))
sma := spx.Average(nt)
k := spx.GT(sma).Add(vix.LT(vix3m)).Add(z.GT(-2.0))
risk := k.GTE(2.0).Add(k.GTE(3.0)).MaskNonFinite(z, sma, vix, vix3m).SetN(max(nt, nz)-1, math.NaN())
tradable := risk.Shift(1).SetN(max(nt, nz), math.NaN())
label := risk.EQ(2.0).Add(risk.EQ(1.0).Mul(2.0)).MaskNonFinite(risk)- Codes:
kcounts the favourable conditions, each strict: the S&P 500 above its nt-bar average, VIX below VIX3M (contango) and the credit z-score of HYG against IEF above -2.riskis 2 ON (all three), 1 Caution (two) and 0 OFF (one or none);tradableis the previous bar’srisk;labelis the authors’ own coding, 1 ON, 2 Caution and 0 OFF. The z-score uses the sample standard deviation, as the authors’ code: StdDev is the population one, so it is scaled by sqrt(nz/(nz-1)), andfloat64(100)/float64(99)is the same double as the constant100.0 / 99. - First valid index: max(nt, nz)-1 for
riskandlabel, 199 at the published nt = 200 and nz = 100, and max(nt, nz) fortradable; the minimum length is one more. Unmasked, the z-score is 0 before bar nz-1 and reads favourable, and the trend vote is 0 before nt-1. - Masks: by the z-score, the average and both volatility series: a bad VIX or VIX3M at bar p gives NaN on [p, p], a bad HYG or IEF on [p, p+nz-1] and a bad S&P on [p, p+nt-1], and
tradableone bar later; the codes recover after. An infinite IEF gives a finite ratio of 0, which no mask catches, so the recipe assumes closes that are finite or NaN. A credit ratio that is constant over the window has a zero deviation, which Div turns into a z-score of 0, favourable, as in the TradeStation and RealTest Tips; pandas would give NaN. - Alignment: the five series must be equal-length and date-aligned. If HYG, IEF, VIX or VIX3M is off bars shorter, the codes are NaN before bar off. A shorter HYG or IEF also leaks the z-score’s warm-up 0, which reads favourable, on bars max(off, F) to off+nz-2 once off is above max(nt, nz)-nz: convert them with
SetN(off+F, math.NaN()). A shorter VIX or VIX3M leaks nothing. - Anchors: E:
vix.LT(vix3m)equalsvix.Div(vix3m).LT(1.0)on positive finite closes, so the recipe avoids the division. E:labelis the authors’ coding ofrisk, andkis MetaStock’s 0-to-3 output. E:tradableisriskone bar later from bar max(nt, nz). E:riskequals a per-bar count of the three conditions. T: the z-score is a tolerance value (StdDev’s running moments against a two-pass sample deviation differ by up to 1.2e-13 relative), so the codes are pinned with a margin: on the test fixture no z-score lies within 1.07e-2 of -2. - Sources: Di Prima and Baruffa (Stocks & Commodities V44:5) and their regimes.py (github.com/fbaru-dev/regime-framework at 86e82b6): the S&P against its 200-day average, VIX/VIX3M below 1 and the 100-day credit z-score above -2 with the pandas sample deviation; ON when all three hold, Caution when two do, rows before the 200-day average dropped. The column header of their Figure 4 reverses the volatility inequality that the text, the code and every Tip use. Their 100/50/0% exposure is a filter rule, GLE-223’s. The July 2026 Tips: TradeStation uses the sample variance and a z-score of 0 on a zero deviation; MetaStock and TradingView use the population deviation, which reads a bar whose sample z-score lies in (-2, -1.98997] as unfavourable; AIQ uses SPY and a 63-day average of VIX in place of VIX3M, and its Figure 8’s printed flags have no inputs (plausibility only). VIX settles after the equity close, so a strictly tradable state is the previous bar’s, which is why
tradableexists. The credit vote alone is “Z-score of the raw ratio” in the “Relative: Ratio and Relative Strength” category. - Pinned by
TestRecipeRiskRegime; runnable exampleExampleSeries_MarkovTransition_riskRegime.
Other daily alphabets: Zhang, trend quadrant, moving-average side, Singha, volatility classes, Batten
a5 := c.Average(5)
mid, e := a5.Shift(9), a5.Shift(25)
zh := a5.GT(mid).Mul(a5.GT(e)).Sub(a5.LT(mid).Mul(a5.LT(e))).Add(1.0).MaskNonFinite(a5, mid, e).SetN(29, math.NaN())
lc := c.Log()
sl, r2 := lc.Slope(n), lc.R2(n)
quad := sl.GT(0.0).Mul(2.0).Add(r2.GT(0.5)).MaskNonFinite(sl, r2).SetN(n-1, math.NaN())
ma := c.Average(10)
side := c.GT(ma).MaskNonFinite(ma).SetN(9, math.NaN())
u := c.Delta().GT(0.0).Shift(1)
g := c.Delta().Shift(1).Mul(0.0).Sum(63)
drift := u.Sum(63).GTE(38.0).MaskNonFinite(g).SetN(64, math.NaN())
sd := c.Log().Delta().StdDev(20).SetN(20, math.NaN())
q := sd.QuantileState(m, 4)
vol3 := q.GT(0.0).Add(q.GT(2.0)).MaskNonFinite(q)
vol5 := sd.QuantileState(m, 5)
v := sd.Div(sd.Average(L)).SetN(L+19, math.NaN())
volV := v.QuantileState(m, 4)
realYield := tips.LTE(0.0).MaskNonFinite(tips)- Codes:
zhis Zhang’s staggered average: 2 UP when the 5-bar average is above both its values 9 and 25 bars earlier, 0 DOWN when below both, 1 FLAT otherwise, ties included.quadis D’Errico and Zaffino’s quadrant of the n-bar regression of the log price: 3 up and stable (slope above 0, R^2 above 0.5), 2 up and unstable, 1 down or flat and stable, 0 down or flat and unstable, both strict.sideis 1 when the close is above its 10-bar average, strict, our reading where Baker and Arnold are silent.driftis Singha’s drift regime, 1 when at least 38 of the previous 63 one-bar changes were rises: 38/63 is the first count above his 60%, and today’s change is excluded.vol3is 0 low, 1 medium and 2 high volatility, the quartile class of the 20-bar deviation of log returns among its last m values with the two middle classes merged;vol5is its quintile class, 0 to 4;volVis the quartile class of V, the deviation over its own L-bar average.realYieldis 1 when the TIPS yield is 0 or below. - First valid index: 29 for
zh, n-1 forquad, 9 forside, 64 fordrift, 20+m-1 forvol3andvol5, L+19+m-1 forvolVand 0 forrealYield; the minimum length is one more.zhneeds the average of bars 0 to 4 25 bars back;driftreads the changes of bars 1 to 63 at bar 64, not the warm-up change of bar 0; Average passes its input through before bar L-1, which would give V = 1, hence V’sSetN(L+19). - Masks: each windowed or shifted input that a comparison reads is a ref. Footprints of a bad close at bar p: [p, p+4], [p+9, p+13] and [p+25, p+29] for
zh(the three averages); [p, p+n-1] forquad; [p, p+9] forside; [p+1, p+64] fordrift, through the sum of zero termsg, which is 0 or NaN and never overflows, as the raw sum of the changes can; [p, p+20+m-1] forvol3andvol5; [p, p+L+m+18] forvolV; and [p, p] of a bad yield forrealYield. The states recover after. - Anchors: E: with the gaps written one bar later,
a5.Shift(1)againsta5.Shift(10)anda5.Shift(26), Zhang’s rule giveszh.Shift(1), which checks the direction of the gaps both ways. E:driftequalsu.Average(63).GT(0.6)from bar 64: the average is the integer count divided once by 63. E: each alphabet equals a per-bar loop. T: on AAPL no 5-bar average lies within 0.052 of its earlier values, no slope of log prices within 2.8e-5 of 0 and no R^2 within 8.0e-4 of 0.5 at n = 20, and no close within 0.01 of its average. On AAPLzhholds 43 DOWN, 23 FLAT and 105 UP bars with 157 stays in 170 transitions,quad21, 23, 57 and 80 bars with 155 stays in 180 at n = 20,side68 below and 123 above with 159 stays in 190, anddrift123 zeros and 13 ones. - Periods: D’Errico and Zaffino use n = 26 on weekly bars, which the caller supplies, for instance the close of the bar before each first-bar-of-week flag, a completed week read from the next week’s first bar; on the 41 weekly AAPL closes of 2023 at n = 26
quadholds 9, 0, 6 and 1 bars. Their 240 daily bars recalculated weekly is a dailyquadat n = 240, labelled approximate; the weekly recalculation is not built. - Sources: Zhang (Fig 2) compares the averages of the closes 5 to 1, 14 to 10 and 30 to 26 days before the trading day, so the gaps are 9 and 25 bars, and the state at close t serves day t+1. D’Errico and Zaffino (Stocks & Commodities V44:5, Fig 1) print eight weekly slope and R^2 pairs, which map to the codes 3, 2, 3, 1, 1, 2, 3 and 3, with both thresholds strict. Baker and Arnold (V20:5, Fig 6) count 15,594 days above the 10-day average and 11,786 below, with 2,049 crosses each way, so their stay probabilities are 1 - 2049/15594 above and 1 - 2049/11786 below. Singha’s regime gates a cross-sectional signal; his 63 and 0.60 are his best case, probably in sample. The volatility classes are our construction: Carver (Advanced Futures Trading Strategies, strategy thirteen) divides a blended exponentially weighted deviation by its ten-year mean and pools 102 instruments, and D’Errico and Trombetta’s quintiles (V42:8) are a next-session target with an unstated measure. Batten et al. (Table 10) split at a real yield of 0 (49 of 229 months and 205 of 847 weeks with negative yields), and their estimated thresholds of 0.609% and 1.780% are full-sample. The Volatility Switch regime and the four-state trend are published with their own methods, and Poster’s Trend Persistence Rate is “Trend Persistence Rate (Poster)” in the “Momentum” category. Withdrawn: a Hurst state on prices, which is above 0.5 on nearly every bar of a random walk (at n = 50, on 99.6% of the bars of five log-normal walks of 1,000 bars; rank a returns-based estimate with QuantileState instead); Mulliner’s z, a continuous observation, not a state; and Tabatabaei’s above-the-mean state, whose mean is full-sample.
- Pinned by
TestRecipeIndicatorAlphabets; runnable exampleExampleSeries_MarkovTransition_indicatorAlphabets.
Monthly market states and DJK’s depressed market
r12 := tr.RateOfChange(12)
ant := r12.GT(tb12).MaskNonFinite(r12, tb12).SetN(12, math.NaN())
r36 := vw.RateOfChange(36)
coop := r36.GTE(0.0).MaskNonFinite(r36).SetN(36, math.NaN())
r36p := r36.Shift(1)
coopGap := r36p.GTE(0.0).MaskNonFinite(r36p).SetN(37, math.NaN())
r10 := ew.RateOfChange(10).Shift(2)
gs := r10.GTE(0.0).MaskNonFinite(r10).SetN(12, math.NaN())
r24 := vw.RateOfChange(24)
dm := r24.GTE(0.0).MaskNonFinite(r24).SetN(24, math.NaN())
q36 := r36.SetN(36, math.NaN()).QuantileState(m, 5)
djk3 := q36.GT(0.0).Add(q36.GT(3.0)).MaskNonFinite(q36)
depressed := q36.EQ(0.0).MaskNonFinite(q36)
rv := d.RateOfChange(1).SetN(1, math.NaN()).Squared().Sum(y).Sqrt().SetN(y, math.NaN())
qv := rv.QuantileState(m, 5)
highVol := qv.EQ(4.0).MaskNonFinite(qv)
monthlyHighVol := flags.If(func(x float64) bool { return x == 1 }, highVol.Shift(1).SetN(y+m, math.NaN()), math.NaN())- Codes: each sign is 1 for up or not down.
antis Antonacci’s absolute momentum: the 12-month return of a total-return indextrabove the T-bill returntb12over the same 12 months, both in percent, strict.coopis Cooper, Gutierrez and Hameed’s UP state, a 36-month return of 0 or more, andcoopGapthe same return one month earlier.gsis Geczy and Samonov’s not-down state, the return from month t-12 to t-2 of 0 or more.dmis Daniel and Moskowitz’s bull state, a 24-month return of 0 or more; their bear indicator is 1 -dm.q36is the quintile class of the 36-month return among the last m months,djk3merges it into 0 Low (depressed), 1 Medium and 2 High, anddepressedis 1 for the bottom class.highVolis 1 for the top quintile of the realised volatility of daily returns over y bars, the square root of their sum of squares, not demeaned, andmonthlyHighVolreads it on the first daily bar of each month. - First valid index: 12 for
ant, 36 forcoop, 37 forcoopGap, 12 forgs, 24 fordm, 36+m-1 forq36,djk3anddepressed, y forrv, y+m-1 forqvandhighVol, and y+m formonthlyHighVol, which is NaN on every bar that is not a month’s first; the minimum length is one more. RateOfChange is 0 before bar L, which would read as “not down”. - Masks: each sign masks the return it compares (and
antthe T-bill return too): RateOfChange carries a NaN level at month p to months p and p+L, where GT and GTE would read 0. Footprints of a NaN level at p: p and p+12 forant, p and p+36 forcoop, p+1 and p+37 forcoopGap, p+2 and p+12 forgs, p and p+24 fordm, [p, p+m-1] and [p+36, p+36+m-1] forq36,djk3anddepressed; a NaN daily close at p gives NaN on [p, p+y] forrvand [p, p+y+m-1] forqvandhighVol. An infinite level is not missing data for RateOfChange: a +Inf or -Inf level at p is NaN at p, but L months later x/Inf reads as a return of -100%, and an infinite daily close likewise reads -100% on the next bar. A level of 0 is finite, but its return reads -100% and the return L months later reads 0, both codes, and a daily close of 0 does the same on its bar and the next. So these recipes assume levels and closes that are positive and finite, or NaN. - Periods: every source is monthly and uses an index: the caller supplies the monthly closes. The daily variant reads a completed month from the next month’s first bar, through the caller’s first-bar-of-month
flagsandShift(1), never by sampling month ends. y = 252 bars is an approximate year, and any daily recast of a monthly sign (252 bars for 12 months) is approximate and defined by no source. - Alignment:
trandtb12, anddandflags, pair by position; date-align them first. - Anchors: E: each sign equals a per-bar loop of its return’s sign, and
q36,djk3anddepresseda per-bar rank of the 36-month return. E:q36isQuantileState(m, 5)of the masked return, andmonthlyHighVolishighVolone bar later on the flagged bars. Unmasked, a NaN level at p reads “down” at p and p+L. - Sources: Antonacci (Dual Momentum Investing, chapters 7 and 8, appendix
B) compares the excess return over T-bills with 0 over 12 months, with no skipped month, on total-return indexes, re-evaluated monthly; the informal “price higher than 12 months ago” is not his rule. Cooper, Gutierrez and Hameed define UP as a non-negative three-year return of the CRSP value-weighted index, with 12 and 24 months as robustness lengths; the text puts the 36 months just before the holding period and the Table I caption suggests a one-month gap, hence
coopGap. Their 124 DOWN months of 798 (219 of 579 at 12 months, 131 of 667 at 24) are plausibility only. Geczy and Samonov use an equal-weighted price index from t-12 to t-2, with zero not down. Daniel and Moskowitz count 183 bear months of 1,035 (plausibility only). Daniel, Jagannathan and Kim (2019) split months by the 36-month market return and by the 12-month realised volatility of daily returns into bottom and top fifths of the whole sample; the rolling ranks here are a causal recast, ties to the lower class, and they name neither the index nor total against excess returns. The hinge regression they fit within each group is “Hinge beta (Henriksson and Merton)” in the “Relative: Regression and Spread” category, cross-referenced here only. - Pinned by
TestRecipeMarketStates; runnable exampleExampleSeries_MarkovTransition_marketStates.
First valid index of the indicator stages
| Stage | First valid index f | Before f |
|---|---|---|
ADX(h, l, c, n) | n | zeros |
MACD(fast, slow) | slow - 1 | zeros before fast - 1, then the fast average less the input |
DFAAlpha(n) | n - 1 | zeros |
Delta() | 1 | zeros |
Shift(k) | k | zeros |
Sum(n) | n - 1 | the sum of the bars so far |
Average(n) | n - 1 | the input, passed through |
StdDev(n) | n - 1 | zeros |
RateOfChange(n) | n | zeros |
Slope(n), R2(n) | n - 1 | zeros |
Log(), Squared(), Sqrt() | 0 | nothing |
QuantileState(n, k) | n - 1 | NaN |
ContinuationIndex(n, gamma, order) | 2*n - 2 | zeros |
DirectionalChange(theta), DirectionalChangeEvent(theta) | 0 | nothing |
Transition probabilities of a state series
MarkovTransition, MarkovNext, MarkovPersistence and MarkovCount count the transitions of a state series z, whose valid values are the integer codes 0 to k-1, over the last n transitions, which span n+1 bars. A transition is counted in the row of its earlier state and the column of its later state. MarkovTransition(n, k, from, to) is one cell of the table, MarkovNext the current state’s row read at one column, MarkovPersistence the current state’s diagonal cell, and MarkovCount the number of transitions leaving a state, the support of its row.
The warm-up and the empty row. Before bar n every output is +0, not NaN. From bar n on, an empty row (no transition leaves the state) also gives 0, which looks the same as an observed 0; recipe (b) tells them apart. A window that holds an invalid state, such as NaN at bar p, gives NaN: the output is NaN from bar max(p, n) to bar p+n and recovers at bar p+n+1.
(a) Up/down codes, with UpDown’s first bar masked
z := c.UpDown(1).SetN(1, math.NaN())
upAfterUp := z.MarkovTransition(5, 3, 2, 2)- Codes:
UpDown(1)gives 0 for flat, 1 for down and 2 for up, so k = 3. Its bar 0 is 0 (flat) for want of a previous close: masking it to NaN keeps it out of the counts.UpDownSumandRegimeDFAuse +1 for up and -1 for down; add 1 before counting their codes. - First valid index: n; the minimum length is n+1.
- Anchor:
MarkovTransition(n, k, from, to)equalsz.EQ(to).Mul(z.EQ(from).Shift(1)).Sum(n).Ratio(z.EQ(from).Shift(1).Sum(n))bit for bit at every bar from n on whose window holds only valid states. - Pinned by
TestRecipeMarkovStateLayer; runnable exampleExampleSeries_MarkovTransition.
(b) The current row’s support
support := z.EQ(0).Mul(z.MarkovCount(n, k, 0))
for i := 1; i < k; i++ {
support = support.Add(z.EQ(float64(i)).Mul(z.MarkovCount(n, k, i)))
}
stay := z.MarkovPersistence(n, k)- Use:
supportis the number of transitions in the window that leave the current state. Where it is 0 the row is empty andstay(orMarkovNext) reads 0 for want of data, not because the state always switched; mask those bars before trading on the probability. - Pinned by
TestRecipeMarkovStateLayer; runnable exampleExampleSeries_MarkovCount_currentRow.
(c) Masking a data gap
present := func(_ float64, i int) bool { return !math.IsNaN(c[i]) && i > 0 && !math.IsNaN(c[i-1]) }
codes := c.UpDown(1)
z := codes.If(present, codes, math.NaN())- Use:
UpDownreads a NaN close as flat, so a gap would count as flat bars. A code reads its close and the previous one, so it is kept only when both are present, and the bar after the gap is masked too. The output is NaN from the first masked code to n bars after the last, and recovers on the bar after that. - Pinned by
TestRecipeMarkovStateLayer; runnable exampleExampleSeries_MarkovTransition_masks.
Testing a transition table for dependence
MarkovDirPhi, MarkovDirChiSquare and MarkovDirCramerV test whether a price change depends on the change before it, over the last n pairs of consecutive changes, which span n+2 prices. MarkovDirPhi splits each change into up and not-up (a flat change is not-up) and returns the phi coefficient; the two tables keep the three directions of UpDown(1), 0 for flat, 1 for down and 2 for up, with UpDown’s tolerance, a percentage of the previous price. MarkovChiSquare and MarkovCramerV do the same for any state series of integer codes 0 to k-1, with the pairs lag bars apart. The chi-square statistic sums (On - RC)^2/(nRC) over the occupied rows and columns, and Cramer’s V is sqrt(chi2/(n*(m-1))), m the smaller number of occupied rows and columns, clamped to 1.
The warm-up, the footprint and what a large value means. Bars before the first valid index, n+1 for the direction forms and n+lag-1 for the generic forms, are +0, which reads as independence, not NaN. A NaN or infinite price, or an invalid state, gives NaN on the windows that hold it, and the output recovers after them. Rolling windows overlap, so the values of successive bars are not independent tests, and a state series with transitions that cannot occur by construction (UpDown codes over two or more bars, streaks) or with the overlap of its own windows (quantiles of a smoothed series) gives large values on any input.
(a) The p-value of phi
p := c.MarkovDirPhi(n).Abs().Mul(math.Sqrt(float64(n) / 2)).Erfc()- Use: under independence n*phi^2 is a chi-square statistic with one degree of freedom, so erfc(|phi|*sqrt(n/2)) is its p-value. On Sherry’s 63 signs as a unit walk (n = 62) phi is -0.1071 and p 0.3989; on Sherry’s 34 automobile price-earnings ratios (n = 32) phi is 0.0552 and p 0.7547. The warm-up’s +0 gives p = 1, and a NaN window gives NaN.
- First valid index: n+1; the minimum length is n+2.
- Pinned by
TestRecipeMarkovDependence; runnable exampleExampleSeries_MarkovDirPhi_pValue.
(b) The generic test on direction codes, at a lag
z := c.UpDown(1, tol).SetN(1, math.NaN())
chi := z.MarkovChiSquare(n, 3, lag)
v := z.MarkovCramerV(n, 3, lag)- Use: each change against the change lag bars before it, which the direction methods do not offer.
SetN(1, math.NaN())marks bar 0, which has no earlier close; at lag 1 the pair equalsMarkovDirChiSquare(n, tol)andMarkovDirCramerV(n, tol)bit for bit on finite prices, from bar n+1.UpDownreads a change to or from a NaN close as flat, so where prices can be missing mask the codes of a missing close and of the bar after it. - First valid index: n+lag-1, where the masked bar 0 gives NaN, so the first value is at bar n+lag; the minimum length is n+lag+1.
- Pinned by
TestRecipeMarkovDependence; runnable exampleExampleSeries_MarkovChiSquare_upDownLag.
(c) Cramer’s V of rank classes
levels := walk.QuantileState(5, 3)
changes := walk.Delta().SetN(1, math.NaN()).QuantileState(5, 3)- Use:
QuantileStategives integer classes with NaN in its warm-up, ready as states. The rank of a close shares most of its window with the next bar’s, so on Sherry’s walklevels.MarkovCramerV(n, 3)reads 0.436 at n = 30 where the changes are not associated; the classes of the changes, withDelta’s warm-up masked first, read 0.056. - Pinned by
TestRecipeMarkovDependence; runnable exampleExampleSeries_MarkovCramerV_quantileState.
Transition probabilities of price directions
MarkovDirTransition, MarkovDirNext and MarkovDirPersistence count the pairs of consecutive price changes over the last n pairs, which span n+2 prices. Each change has the direction of UpDown(1), 0 for flat, 1 for down and 2 for up, with UpDown’s tolerance, a percentage of the previous price; a change equal to the threshold is flat. A pair is counted in the row of its earlier direction and the column of its later one. MarkovDirTransition(n, from, to) is one cell of the table, MarkovDirNext the current direction’s row read at one column and MarkovDirPersistence the current direction’s diagonal cell. On finite prices each equals the generic methods on c.UpDown(1, tol).SetN(1, math.NaN()) from bar n+1 on; the methods add the zero warm-up and NaN for a window that holds a NaN or infinite price, where UpDown alone gives each change a code, flat across a NaN.
The warm-up and the empty row. Bars 0 to n are +0, not NaN: the first pair would read bar 0, which has no earlier price, so the first valid index is n+1. From bar n+1 on, an empty row (no pair leaves the direction) also gives 0, which looks the same as an observed 0; recipe (c) tells them apart. A NaN or infinite price at bar p gives NaN from bar max(p, n+1) to bar p+n+1, and the output recovers at bar p+n+2.
(a) An up change after an up change
upAfterUp := c.MarkovDirTransition(5, 2, 2)- First valid index: n+1; the minimum length is n+2.
- Anchor: with
z := c.UpDown(1, tol),MarkovDirTransition(n, from, to, tol)equalsz.EQ(to).Mul(z.EQ(from).Shift(1)).Sum(n).Ratio(z.EQ(from).Shift(1).Sum(n))bit for bit at every bar from n+1 on whose window holds only finite prices. - Pinned by
TestRecipeMarkovDirChain; runnable exampleExampleSeries_MarkovDirTransition.
(b) The two-state chain: up against not up
up := c.UpDown(1, tol).EQ(2).SetN(1, math.NaN())
upUp := up.MarkovTransition(n, 2, 1, 1)
upNotUp := up.MarkovTransition(n, 2, 1, 0)- Use: state 1 is an up change and state 0 a down or flat one, the alphabet that avoids the sparse flat row at tolerance 0. Only the up-to-up cell equals the three-state chain’s: on Arrington’s ten closes (n = 8) the not-up share after an up change is 0.5, where the down share is 0.25 and the flat share 0.25.
UpDownreads a NaN close as flat, so this chain has no NaN footprint; mask the codes as in recipe (c) if prices can be missing. - Pinned by
TestRecipeMarkovDirChain; runnable exampleExampleSeries_MarkovDirTransition_upNotUp.
(c) The support of the current row
codes := c.UpDown(1, tol)
finite := func(_ float64, i int) bool { return i > 0 && c[i]-c[i] == 0 && c[i-1]-c[i-1] == 0 }
z := codes.If(finite, codes, math.NaN())
support := z.EQ(0).Mul(z.MarkovCount(n, 3, 0))
for from := 1; from < 3; from++ {
support = support.Add(z.EQ(float64(from)).Mul(z.MarkovCount(n, 3, from)))
}
nextUp := c.MarkovDirNext(n, 2, tol)- Use:
zis the methods’ own direction series: NaN at bar 0 and wherever a price is not finite.z.MarkovCount(n, 3, from)is the support of row from, which equalsc.UpDown(1, tol).EQ(from).Shift(1).Sum(n)on finite prices; the three supports sum to n.supportis the support of the current direction’s row: where it is 0 the row is empty andnextUp(orMarkovDirPersistence) reads 0 for want of data. The first flat change of any window has an empty current row. - First valid index: n+1.
MarkovCountis NaN at bar n, where the methods read 0, and from bar n+1 on it is NaN exactly where they are. - Pinned by
TestRecipeMarkovDirChain; runnable exampleExampleSeries_MarkovDirTransition_rowSupport.
McKallip’s edge reads the transition table of the day type: which type of day follows which. Each cell of his difference matrix is a lift, the probability of the next day’s type j given today’s type, less type j’s share of all the days that follow; his trade example turns one row into a directional edge. The recipe below computes them over a rolling window of n transitions on the day type day of “Bar-type states: Siroky, McKallip, Pezzutti” in this category, passed as the state z with its first valid index fz. The lift has a readable route through MarkovNext, three roundings, which is pinned within a tolerance of its exact value; the count lift and the edge are made of whole window counts and one division, so they are exact. The window sums read a NaN state as not in state, so they drop an invalid bar silently where MarkovNext reads NaN; the masks below say where. The day type is built from h and l, and the recipes that combine several series pair them by position; an empty operand gives zeros; date-align first.
Lift, count lift and directional edge (McKallip)
from := z.EQ(i).Shift(1)
lift := z.MarkovNext(n, 6, j).Sub(z.EQ(j).Average(n)).SetN(fz+n, 0)
countLift := z.EQ(j).Mul(from).Sum(n).Mul(float64(n)).Sub(from.Sum(n).Mul(z.EQ(j).Sum(n))).SetN(fz+n, 0)
fav := z.EQ(1).Add(z.EQ(2))
unf := z.EQ(3).Add(z.EQ(4))
edgeRow := fav.Mul(from).Sum(n).Ratio(fav.Add(unf).Mul(from).Sum(n)).SetN(fz+n, 0)
edge := z.EQ(i).Mul(edgeRow)- Codes and sets:
zholds the day types 0 IN, 1 DN, 2 DG, 3 UN, 4 UG and 5 OD, in the order of McKallip’s Fig 2, and NaN where a bar has no type. The window of bar t holds the n transitions into bars t-n+1 to t.iis a row, the type of the day on which a trade is entered (2, DG, in McKallip’s example), andja column, the next day’s type.fromflags the bars whose previous bar has typei.liftis the share of the window’s transitions out of the bar’s own type z[t] that end in type j, less the share of type j among the window’s n later ends.countLiftis nn_ij - n_in_j for row i, with n_ij the transitions from i to j, n_i those from i and n_j the later ends of type j: n*n_i times the lift of row i, with no division.favflags DN and DG, the days on which a short entered the evening before wins, andunfUN and UG, the days on which it loses; IN and OD are neither.edgeRowis the winning share of row i’s winning and losing transitions, andedgeis that edge on the bars of type i and 0 on the others. Numbering UG 3 and UN 4 instead swaps the lift’s and the count lift’s columns 3 and 4 and leaves the edge unchanged, since both are losing days. - First valid index: fz+n for
lift,countLift,edgeRowandedge, which is 1+n for the day type; the minimum length is fz+n+1. Every output is 0 before it: the window of bar fz+n-1 still holds the transition into bar fz, whose earlier end has no type, MarkovNext is 0 before n and Average passes its input through before n-1.from,favandunfare flags on every bar. fz is a variable because a state valid from bar 0, such as a code path built by hand, has fz = 0, and a fixed 1+n would zero its first valid bar. n is at least 1: at n = 0 MarkovNext gives zeros and Average passes its input through, soliftwould read -1 on the bars of type j. - Masks: the day type is already NaN on bar 0 and on [p, p+1] after a NaN, +Inf or -Inf high or low at bar p, so the recipe adds no mask. MarkovNext reads NaN on every bar whose window holds an invalid state, so
liftis NaN on [max(p, fz+n), p+n+1] after a bad high or low at p, which is [100, 121] at n = 20 for p = 100, and recovers after.countLift,edgeRowandedgedrop a NaN state silently, because EQ reads NaN as not in state, where MarkovNext reads NaN on every bar whose window holds one; so they equal their exact definitions on the bars from fz+n whose window holds only valid states, and after a bad high or low they stay finite and count only the valid transitions of the window. On a bar whose own type is NaN,edgereads 0, as on an empty row.edgeRowis 0 where row i holds no winning or losing transition in the window, which reads like a row of losses:fav.Add(unf).Mul(from).Sum(n)is 0 exactly there. Where the bar’s own row is empty MarkovNext reads 0, soliftis -n_j/n there. No output is -0. - Alignment: the recipe reads one series. If l is off bars shorter than h, the day type holds a made-up code at bar off, as the bar-type section says: pass
z.SetN(off+1, math.NaN())with fz = off+1, and the outputs are those of the equal-length bars from bar off on. - Anchors: E:
edgeRowis float64(fav)/float64(fav+unf) of row i’s whole window counts, and 0 on an empty row, on every bar from fz+n whose window holds only valid states. E:countLiftis nn_ij - n_in_j computed in integers, and its sum over j is 0 for every row on every bar whose window holds only valid states; the partial values are whole numbers of at most n^2, so they are exact while n is at most 94,906,265, the largest n whose square is below 2^53. E:z.EQ(j).Average(n)isz.EQ(j).Sum(n)divided by n, bit for bit (whole counts, one division). E: the sum over i ofedgeis the edge of each bar’s own row,edgeRowat row z[t], and 0 where z[t] is NaN. E: on the code path z = 2, then each later type of Fig 2’s DG row in turn, 18 IN, 86 DN, 36 DG, 57 UN, 14 UG and 32 OD, each followed by a return to DG unless it is DG (451 bars, fz = 0, n = 450), bar 450 counts that row,edgeRowis 122/193 = 0.6321243523316062 and the count lift row is 3726, 17802, -42849, 11799, 2898 and 6624. T:liftlies within 5e-16 of the exact ratio countLift/(n*n_i) at row z[t], on every bar whose window holds only valid states and whose own row is not empty; on the 200 AAPL bars of 2023 the two differ in the last place on 300 of 1,002 such cells at n = 20 and on 426 of 888 at n = 50, by at most 1.11e-16, and on the code path above on 5 of the 6 cells of bar 450, where the lift row sums to -7.63e-17. Built from MarkovNext’s probabilities, asz.MarkovNext(n, 6, 1).Add(z.MarkovNext(n, 6, 2))over itself plus the sum of columns 3 and 4, the edge is not exact: it gives 0.6321243523316061 on that path. - Sources: McKallip (Stocks & Commodities V5:11) tallies over 2,900 transitions of 16 unrelated commodities from March to November 1986, about 180 days, and prints six matrices in Fig 2: the transitions (2,936), the probabilities, the expected transitions and probabilities (each column’s total over all transitions), the difference matrix, which is the lift, and the chi-square matrix (153.8 with 25 degrees of freedom). His DG row is 18, 86, 36, 57, 14 and 32 transitions of 243, or 7.4, 35.4, 14.8, 23.5, 5.8 and 13.2 percent. His trade example shorts at the close of a DG day, wins on a DN or DG day, loses on a UN or UG day and is flat on IN and OD: he rounds the four probabilities 35.39, 14.81, 23.46 and 5.76 percent to 35, 15, 23 and 6 before dividing by their sum, so his 50/79 and 29/79 print as 63% and 37%, where the exact counts give 122/193 = 63.21% and 71/193 = 36.79%. His tables pool the whole sample, and his totals have no inputs, so they are plausibility only; the rolling window is the causal recast, and the code path above restates his DG row. On the 200 AAPL bars of 2023 the day types number 23, 58, 10, 80, 13 and 15, so at n = 50 row DG holds at most 4 transitions, and the edge on the six DG bars from bar 51 is 2/3, 1, 1, 1, 0 and 0, the fifth an empty row and the sixth one losing transition: a rolling edge needs a long window or, as McKallip’s, many markets pooled.
- Pinned by
TestRecipeMcKallipEdge; runnable exampleExampleSeries_MarkovNext_mckallipEdge.
First valid index of the edge stages
| Stage | First valid index f | Before f |
|---|---|---|
EQ(y), Add(y), Sub(y), Mul(y), Ratio(s2) | 0 | nothing |
Shift(k) | k | zeros |
Sum(n) | n - 1 | the sum of the bars so far |
Average(n) | n - 1 | the input, passed through |
MarkovNext(n, k, to) | n | zeros |
Rank classes in a rolling window
QuantileState(n, k) ranks each bar’s value among the n-1 values before it and maps the rank onto k classes numbered 0 to k-1: lt, the number of earlier values strictly below the current one, gives the class (k*lt)/n rounded down, worked out in integers. With k = n the class is lt itself. The output is a state series of integer codes, ready for the state-chain methods of this category.
The warm-up and gaps. The output is NaN before bar n-1, not 0, because a bar read as class 0 would be a valid state. A NaN or an infinity at bar p gives NaN from bar p to bar p+n-1, and the output recovers at bar p+n. Every finite value is ranked, so mask an upstream warm-up with SetN first: its aligned zeros would otherwise be ranked as data.
(a) The class of each bar
q := s.QuantileState(5, 3)- Ties: an earlier value equal to the current one is not below it, so ties go to the lower class and a constant series is class 0. Ties are binary64 ties: round price changes to the tick first, as in
d.Mul(100).Round(), when equal cents are meant. - First valid index: n-1; the minimum length is n.
- Anchor:
QuantileState(n, n)equals the sum over j = 1 to n-1 ofs.GT(s.Shift(j))bit for bit on finite windows. - Pinned by
TestRecipeQuantileStateTies; runnable exampleExampleSeries_QuantileState.
(b) Other tie conventions
tiesUp := s.Mul(-1).QuantileState(n, k).Mul(-1).Add(float64(k - 1))
up := s.QuantileState(n, n)
down := s.Mul(-1).QuantileState(n, n)
mid := up.Sub(down).Add(float64(n - 1)).Mul(float64(k)).Div(float64(2 * n)).Floor()- Use:
tiesUpputs a tied value in the upper class, ceil(kle/n)-1 with le the number of window values at or below it;midcounts each earlier value equal to it as half below it, floor(k(2lt+eq)/(2n)) with eq the number of earlier values equal to it. On the series 1, 1, 2, 2, 2, 3, 1, 2, 2 at n = 5 and k = 3 the three readings from bar 4 are 1 2 0 0 0 (strict), 2 2 0 2 2 (ties up) and 1 2 0 1 1 (mid-rank). Both compositions are exact on finite windows. - Pinned by
TestRecipeQuantileStateTies; runnable examplesExampleSeries_QuantileState_tiesUpandExampleSeries_QuantileState_midRank.
(c) Merging classes, with the mask put back
q := s.QuantileState(8, 4)
merged := q.GT(0).Add(q.GT(2)).MaskNonFinite(q)- Use: Carver’s three regimes from quartile classes: the bottom quartile, the two middle ones merged, and the top quartile. GT reads NaN as 0, so the warm-up would read as the bottom regime;
MaskNonFinite(q)puts the NaN back wherever q is NaN. - Pinned by
TestRecipeQuantileStateTies; runnable exampleExampleSeries_QuantileState_carver.
(d) The continuous rank
q := s.QuantileState(n, n)
cont := q.Mul(1 / (float64(n) - 1))- Use:
contis the rank on the 0 to 1 scale. It equals RankPosition(n) bit for bit on finite windows from bar n-1, because both multiply the same whole number by the rounded reciprocal; RankPosition reads 0 in its warm-up wherecontreads NaN. Dividing instead,q.Div(float64(n - 1)), can differ by one ulp: at n = 6 and lt = 3 the quotient is 0.6 and the product 0.6000000000000001. - Pinned by
TestRecipeQuantileStateTies; runnable exampleExampleSeries_QuantileState_continuousRank.
Price- and bar-state alphabets turn prices into the integer state codes that the state-chain methods of this category count. Codes are 0-based integers, and a bar that cannot be classified is NaN, not a code: GT, LT and EQ read NaN as false and UpDown reads a NaN change as flat, so every alphabet below ends with MaskNonFinite on the series it compares, the gap idiom of this category, and with SetN(F, math.NaN()) on its warm-up, where F is its first valid index and F+1 its minimum length. A NaN, +Inf or -Inf input at bar p then gives NaN on the bars listed as the footprint, and the codes recover after it. The alphabets that combine highs, lows, closes or volumes pair them by position; an empty operand gives zeros; date-align first. With an empty operand the codes are all NaN, because MaskNonFinite with an empty reference gives NaN on every bar. If the lengths differ by off bars, convert the bars before the overlap with SetN(off+F, math.NaN()) before a state consumer. Each section’s anchors are tagged E (an exact identity), G (a property every valid output has) or T (a tolerance or margin). Any alphabet with k <= 98 codes feeds MarkovTransition and MarkovNext, and MarkovChiSquare and MarkovCramerV test its transition table for dependence.
Direction and pattern states
d := c.Delta()
up := d.GT(0).MaskNonFinite(d).SetN(1, math.NaN())
dir := c.UpDown(1, tol).MaskNonFinite(d).SetN(1, math.NaN())
g := d.Sub(d)
pat := c.UpDown(k, tol).MaskNonFinite(g.Sum(k)).SetN(k, math.NaN())
dense := dir.Add(dir.Shift(1).Mul(3)).Add(dir.Shift(2).Mul(9)).Add(dir.Shift(3).Mul(27))
pair := z.Shift(1).Mul(float64(kz)).Add(z).SetN(1, math.NaN())- Codes:
upis 1 for a rise and 0 otherwise.diris UpDown’s direction, 0 flat, 1 down and 2 up, with UpDown’s tolerance tol, a percentage of the previous close.patis the order-k pattern ofUpDown(k), the newest direction in the lowest two bits: 3^k of its 4^k values occur, the largest is 42 at k = 3 and 170 at k = 4, so the chain methods take k <= 3.densepacks four directions in base 3, 0 to 80.pairis the order-2 code kzz[t-1] + z[t] of any state z with kz codes, 0 to kzkz - 1, so kz <= 9 for the chain methods. - First valid index: 1 for
upanddir,kforpat, 4 fordenseand that of z plus 1 forpair; the minimum length is one more. Shift pads a valid 0, hence theSetN(1, math.NaN())onpair. - Masks: the change d is not finite wherever a close or the one before it is not finite.
g.Sum(k)is 0, or NaN while one of the last k changes is not finite; it is the sum of zero terms, notd.Sum(k), whose changes of 9e307 sum to +Inf and would mask a valid pattern. Footprint of a bad close at bar p: [p, p+1] forupanddir, [p, p+k] forpat, [p, p+4] fordense, and z’s footprint extended by one bar forpair. - Anchors: E:
patequalsc.UpDown(k).SetN(k, math.NaN())for k = 1 to 4 on finite closes. E:pairwith z =dirand kz = 4 equalsc.UpDown(2).SetN(2, math.NaN()), andc.UpDown(4).Mod(64)equalsc.UpDown(3)from bar 4: dropping the oldest direction is why Merrill’s three-swing counts are the sums of his four-swing counts. E:denseequals a per-bar loop of the sum over j of 3^j times the direction j bars back. E: summed over the oldest direction, the transition counts ofpairwith kz = 3 are the order-1 counts ofdir, in every window. E: at tol 0,direquals the If-mask formcodes.If(present, codes, math.NaN())of “Transition probabilities of a state series” (c) on closes with no infinity, and so doesupwithd.GT(0)as the codes; at tol 0,upalso equals the up/not-up statec.UpDown(1, tol).EQ(2).SetN(1, math.NaN())of “Transition probabilities of price directions” (b) on finite closes. E: each mask equals the.Add(x.Sub(x))form bit for bit on finite data and is NaN wherever that form is NaN under NaN, +Inf and -Inf. G: MarkovTransition and MarkovNext return a value on each alphabet once its window is valid. - Sources: Merrill (Stocks & Commodities V9:4) counts the next day’s rises and declines after his 16 four-swing and 8 three-swing patterns of the day’s last hourly swings, up and down only; UpDown adds a flat code, rare on daily closes at tol 0 (one bar of the 200 AAPL closes of 2023, bar 42). Weiderman (V7:10) uses coin-toss patterns of length k and Sherry (V6:9) digrams of tercile states, the
pairof the tercilesterbelow. Crabel’s close-and-open patterns of “Up / Down” are UpDown codes with an open digit, another alphabet. - Pinned by
TestRecipeDirectionStates; runnable exampleExampleSeries_MarkovTransition_directionStates.
Bar-type states: Siroky, McKallip, Pezzutti
h1, l1 := h.Shift(1), l.Shift(1)
bar := h.GT(h1).Add(l.LT(l1).Mul(2)).MaskNonFinite(h, l, h1, l1).SetN(1, math.NaN())
in := h.LT(h1).Mul(l.GT(l1))
od := h.GT(h1).Mul(l.LT(l1)).Add(h.EQ(h1).Mul(l.EQ(l1)))
ug := l.GT(h1)
dg := h.LT(l1)
res := in.Add(od).Add(ug).Add(dg).Mul(-1).Add(1)
un := res.Mul(h.GT(h1).Add(l.GT(l1)).GT(0))
day := res.Add(un.Mul(2)).Add(dg.Mul(2)).Add(ug.Mul(4)).Add(od.Mul(5)).MaskNonFinite(h, l, h1, l1).SetN(1, math.NaN())
vz := v.If(func(x float64) bool { return x > 0 }, v, math.NaN())
df := h.Sub(l).Div(vz).Delta()
dv := v.Delta()
four := dv.GT(0).Mul(2).Add(df.GT(0))
tie := df.EQ(0).Add(dv.EQ(0)).GT(0)
fac := tie.If(func(x float64) bool { return x == 1 }, 4.0, four).MaskNonFinite(h, l, h1, l1, vz, vz.Shift(1)).SetN(1, math.NaN())- Codes:
baris Siroky’s bar state, 1 for a new high only, 2 for a new low only, 3 for both and 0 for neither, both tests strict.dayis McKallip’s day type in the order of his Fig 2: 0 inside (IN), 1 normal down (DN), 2 gap down (DG), 3 normal up (UN), 4 gap up (UG) and 5 outside (OD). IN is h < h1 and l > l1, OD is h > h1 and l < l1 or an equal day (h == h1 and l == l1), UG is l > h1 and DG is h < l1; on bars with h >= l these four exclude each other, and the rest is UN when h > h1 or l > l1, else DN. With h1 = 10 and l1 = 5 the bars (h, l) of (9, 4), (9, 5) and (10, 4) are DN, (9, 6) IN, (10, 5) OD, (10, 6), (11, 5) and (11, 6) UN and (11, 4) OD.facis Pezzutti’s market-facilitation type on Williams’s index (h - l)/v, 3 green (index and volume up), 2 squat (index down, volume up), 1 fake (index up, volume down), 0 fade (both down) and 4 a tie in either. - First valid index: 1 for all three; the minimum length is 2.
- Masks: the refs are both bars’ highs and lows, so a bad high or low at bar p gives NaN on [p, p+1]. A zero volume is finite and Div turns a zero divisor into 0, so
vzmakes zero and negative volumes NaN andfacmasks byvzandvz.Shift(1), not by v: a zero-volume bar gives NaN on [p, p+1]. - Alignment: h, l and v must have equal length. If l is off bars shorter, the three give NaN before bar off and a made-up code at bar off, where Shift’s pad is finite, and the equal-length codes from bar off+1:
SetN(off+1, math.NaN())converts them. - Anchors: E:
baris 3 exactly on the bars that OutsideBars flags, from bar 1; InsideBars is non-strict and tests against the last bar that was not inside, so it is not code 0. E:dayequals a per-bar switch in the precedence above. E:facequals Pezzutti’s four rules and the tie rule per bar, and the tie flag equals the product formdf.GT(0).Add(df.LT(0)).Mul(dv.GT(0).Add(dv.LT(0))).EQ(0)after the mask. E: the masks equal the.Add(b).Add(b.Shift(1))form with b = (h+l) - (h+l). - Sources: Siroky (Stocks & Commodities V38:12) defines the new high and the new low and averages the two flags; the four codes are this alphabet’s. Kaufman’s outside day
h.GT(hp).Mul(l.LT(lp))under “Bar Classification” is code 3, and the strict inside dayh.LT(hp).Mul(l.GT(lp))there is McKallip’s IN. McKallip (V5:11) defines only IN and OD, both strict, and counts an equal day as outside; the gap and normal days are pictured, not defined, so their predicates and the residual tie rule are this alphabet’s. The residual rule is symmetric: the earlier “UN when h > h1” sent (10, 6) above to DN. His Fig 2 pools 2,936 transitions of 16 commodities, printed counts with no inputs, so they are plausibility only. Pezzutti (V24:3) prints four strict EasyLanguage rules on the index against its previous value and on volume against its previous value; nseries’ MFI is the Money Flow Index, a different quantity. On the 200 AAPL bars of 2023 the day types number 23, 58, 10, 80, 13 and 15, and the facilitation types 0 to 3 number 45, 58, 48 and 48 with no tie and 28 stays in 198 transitions. - Pinned by
TestRecipeBarStates; runnable exampleExampleSeries_MarkovTransition_barStates.
Bucket states: IBS, Trongone, Sherry, Arrington
d := c.Delta()
ibs := c.Stochastic(h, l, 1)
rng := h.Sub(l)
bucket := rng.If(func(x float64) bool { return x > 0 }, ibs.Div(20).Floor().Clamp(0, 4), math.NaN()).MaskNonFinite(h, l, c)
j := c.Sub(l).Div(tk).Round()
w := rng.Div(tk).Round()
bucketTick := w.If(func(x float64) bool { return x > 0 }, j.Mul(5).Div(w).Floor().Clamp(0, 4), math.NaN()).MaskNonFinite(h, l, c)
bp := c.RateOfChange(1).Mul(100).Round()
pct := bp.GT(-200).Add(bp.GT(-100)).Add(bp.GT(0)).Add(bp.GTE(100)).Add(bp.GTE(200)).MaskNonFinite(d).SetN(1, math.NaN())
dc := d.Mul(100).Round()
big := dc.GTE(400).Sub(dc.LTE(-400)).Add(1).MaskNonFinite(dc).SetN(1, math.NaN())
ter := dc.GT(-120).Add(dc.GTE(190)).MaskNonFinite(dc).SetN(1, math.NaN())
lo, hi := x.Lowest(L), x.Highest(L)
span := hi.Sub(lo)
bin := span.If(func(r float64) bool { return r > 0 }, x.Sub(lo).Div(span).Mul(float64(k)).Floor().Clamp(0, float64(k-1)), math.NaN()).MaskNonFinite(hi, lo).SetN(L-1, math.NaN())
dm := d.SetN(1, math.NaN())
m := dm.Average(n).Shift(1)
s := dm.StdDev(n).Shift(1)
area := dm.LT(m.Sub(s.Mul(0.25))).Add(dm.GT(m.Add(s.Mul(0.25)))).Add(dm.LT(m.Sub(s.Mul(1.75)))).Add(dm.GT(m.Add(s.Mul(1.75)))).MaskNonFinite(dm, m, s).SetN(n+1, math.NaN())- Codes:
bucketis the internal-bar-strength bucket, floor(IBS/20) of the 0 to 100 IBS, on [0, 20), [20, 40), [40, 60), [60, 80) and [80, 100].bucketTickis the same bucket in whole ticks tk, floor(5j/w) of the close’s and the range’s tick counts.pctis Trongone’s daily change class, 0 at -2.00% or below, 1 to -1.00%, 2 to 0.00%, 3 below 1.00%, 4 below 2.00% and 5 from 2.00%.bigis Sherry’s large move, 0 at -4.00 or below, 2 at +4.00 or above, else 1, andterhis tercile of the change with the cut-offs -1.20 and +1.90: each is his class minus 1.binis Arrington’s equal-width bin of x among the trailing L bars, 0 to k-1.areais Arrington’s area minus 1: 0 when the change lies within 0.25 standard deviations of the mean, 2 when it lies beyond 1.75, else 1. - First valid index: 0 for
bucketandbucketTick, 1 forpct,bigandter, L-1 forbinand n+1 forarea; the minimum length is one more. Arrington bins changes: with x =d.SetN(1, math.NaN())the first valid index ofbinis L. - Masks: a range of 0 (h == l) gives NaN, not bucket 0, since Div turns a zero divisor into 0; so does a flat window for
bin. The bucket masks by h, l and c, sinceFloorandClampwould read a +Inf close as bucket 4 and a +Inf high as bucket 0, andbinmasks byhiandlo, since a +Inf in the window would make the other bars bin 0. Footprints of a bad bar p: [p, p] for the buckets, [p, p+1] forpct,bigandter(an infinite close too, because the mask comes from d: RateOfChange reads a +Inf close at p as -100 at p+1), [p, p+L-1] forbinand [p, p+n+1] forarea. - Decimal edges: the difference or quotient of decimal prices can land on either side of a decimal edge, so
pctrounds to hundredths of a percent andbigandterto cents, half away from zero, andbucketTickcounts ticks. Without the rounding, 348 of 2,998 exact moves of 1% and 2% and 32 of 6,002 exact moves of 4.00 on a 0.10 grid are misclassified; with it, none.Roundrounds half away from zero, soDecimal(x).to_integral_value(ROUND_HALF_UP)in Python andround(x, RoundNearestTiesAway)in Julia reproduce it, and Python’sround()does not. The rounding assumes |x/tk| below 2^52. - Alignment: h, l and c must have equal length; trim with Window first. Stochastic returns zeros on mismatched lengths, so
bucketwould read 0 on every covered bar.bucketTickreads no Stochastic and pairs by position. - Anchors: E:
c.Sub(l).Div(h.Sub(l)).Mul(100)equalsc.Stochastic(h, l, 1)on every bar, a zero range included (both 0), sobucketis defined on the Stochastic value: floor(5IBS) is not the same bucket (a low of 24.20, a high of 30.70 and a close of 29.40 give an IBS of 80, bucket 4, where floor(5IBS) is 3). E:x.Sub(lo).Div(span).Mul(100)equalsx.Stochastic(x, x, L)from bar L-1 where the window is not flat. E: each alphabet equals a per-bar loop. T: the area limits come from a float mean and standard deviation, so the tests assert that no change on the AAPL closes lies within 1.3e-3 of a limit, relative to the change (1.3662e-3 at n = 6). - Sources: Pagonidis (The IBS Effect) defines IBS as a one-bar stochastic and five buckets between 0% and 100%; their closedness is this alphabet’s, and his “IBS of 0.2 or less” closes the bottom bucket at 0.2. Trongone (Stocks & Commodities V29:1) labels the 1.00% edge three ways; this alphabet follows his Fig 3 and puts 0.00%, which he leaves out, in class 2. His Fig 3 counts 376 days where the text says 366, printed with no inputs, so they are plausibility only. Sherry (V4:3; V4:8, Fig 1) chose his cut-offs on the whole sample of soybean meal closes; on the closes of his Fig 1,
teris his printed sector minus 1 on all 21 changes andbigis 1 on all of them. For another market or tick, scale the rounding unit and the thresholds together. Arrington (V11:12) bins the whole sample into k = 5 equal widths;binuses a trailing window and folds the top edge into bin k-1. Arrington (V9:6) varies n between 5 and 10 with his moving average, and his limits for the next day use the mean and the population standard deviation of the n changes ending the day before, whichareafixes as n: inner bounds non-strict and outer bounds strict, they reproduce his Fig 5 on all 9 rows whose window lies in the table, where a window that includes the day’s change, the sample deviation or his limits as printed to two decimals each fail a row. - Pinned by
TestRecipeBucketStates; runnable exampleExampleSeries_MarkovTransition_bucketStates.
Rank states
dc := c.Delta().Mul(100).Round().SetN(1, math.NaN())
terRoll := dc.QuantileState(n, 3)
r := c.Delta().Div(c.Shift(1)).SetN(1, math.NaN())
q := r.Abs().QuantileState(n, 4)
tail := q.EQ(3)
pos := r.GT(0)
quart := tail.Mul(-1).Add(1).Add(pos.Mul(tail.Mul(2).Add(1))).MaskNonFinite(q, r)- Codes:
terRollis the tercile of the change in cents among the last n changes, ties to the lower class.quartis Durenard’s class of the return r: 0 for a fall in the top quartile of |r| (T-), 1 for another fall (B-), 2 for another rise (B+) and 3 for a rise in the top quartile (T+), with r = 0 counted as a fall. - First valid index: n for both; the minimum length is n+1. QuantileState needs k <= n, so n >= 4 for
quart; take n >= 20. - Masks: EQ and GT read QuantileState’s NaN as 0, so
quartis masked again by q and r. A bad close at bar p gives NaN on [p, p+n]. - Anchors: E: each equals a per-bar loop of the strict-below count.
terRollranks the change rounded to cents, as the fixed cut-offs do: changes equal in cents can differ as doubles (192.5 to 194.7 and 100 to 102.2 both rise 2.20), and ranking the raw change would split them. - Sources: Sherry’s terciles are whole-sample; the rolling form is causal. Durenard (Professional Automated Trading, 10.3.2) suggests the quartiles of the negative and of the positive returns over the whole history;
quarttakes one quartile of the pooled |r| over a trailing window, which no single method computes per sign. - Pinned by
TestRecipeRankStates; runnable exampleExampleSeries_MarkovTransition_rankStates.
Continuation and regime states
d := c.Delta()
p := d.Mul(d.Shift(1))
cont := p.GTE(0).MaskNonFinite(p).SetN(2, math.NaN())
dir := c.UpDown(1).MaskNonFinite(d).SetN(1, math.NaN())
a := c.Average(n)
regime := c.GT(a).Mul(3).Add(dir).MaskNonFinite(a).SetN(n-1, math.NaN())- Codes:
contis 1 when the change continues the previous one or either is 0, and 0 on a reversal.regimeis 3 times “the close is above its n-bar average” plus the direction, 0 to 5. - First valid index: 2 for
contand n-1 forregime(1 at n = 1, where the close is its own average andregimeisdir); the minimum length is one more. Average passes the close through before bar n-1, so without theSetNthose bars would read codes. - Masks: a bad close at bar p gives NaN on [p, p+2] for
contand on [p, p+n-1] forregime([p, p+1] at n = 1, throughdir’s mask). - Anchors: E: with
u2 := c.UpDown(2),contequalsu2.EQ(6).Add(u2.EQ(9)).Mul(-1).Add(1).SetN(2, math.NaN())on finite closes (6 is down then up, 9 up then down). E: each equals a per-bar loop. - Sources: Lopez de Prado (Advances in Financial Machine Learning, Exercise 18.2(b)) encodes returns as 0 if r[t]r[t-1] < 0 and 1 otherwise, for entropy estimates; the product of changes has the sign of the product of returns for positive prices. Gayed (Leverage for the Long Run) compares the close with its 200-day average (n = 200) and tabulates up-day streaks above and below it, contemporaneous frequencies printed with no inputs, plausibility only. Zahorchak’s postures under “Regime Detection” also read the close against averages, a different family of states.
- Pinned by
TestRecipeContinuationStates; runnable exampleExampleSeries_MarkovTransition_continuationStates.
Directional-change run state
z := c.DirectionalChange(theta)
run := z.If(func(x float64) bool { return x == 0 }, math.NaN(), z.Add(1).Div(2)).MaskNonFinite(c)- Codes:
runis 0 in a downward run and 1 in an upward run, and NaN before the first confirmation, where DirectionalChange reads its undetermined 0. - First valid index: the first confirmation, which depends on the data;
z.EQ(0)detects the bars before it. - Masks: DirectionalChange holds its state through a missing price, so only bar p of a bad close is NaN, and the state carries on after it as if the bar were absent.
- Anchors: E:
runequals a per-bar loop of the directional-change rules mapped to 0 and 1. - Sources: the state of DirectionalChange, whose settings and sources are documented with it.
- Pinned by
TestRecipeDirectionalChangeStates; runnable exampleExampleSeries_MarkovTransition_directionalChangeStates.
First valid index of the alphabet stages
| Stage | First valid index f | Before f |
|---|---|---|
Delta() | 1 | zeros |
UpDown(k, tol) | k | zeros |
Sum(k) | k - 1 | the sum of the bars so far |
Shift(1) | 1 | zeros |
Stochastic(h, l, 1) | 0 | nothing |
RateOfChange(1) | 1 | zeros |
Highest(L), Lowest(L) | L - 1 | the extreme of the bars so far |
Average(n) | n - 1 | the input, passed through |
StdDev(n) | n - 1 | zeros |
QuantileState(n, k) | n - 1 | NaN |
DirectionalChange(theta) | 0 | nothing |
Dai’s trading rule on the two filters
Dai, Zhang and Zhu’s trading rule is a two-threshold latch on the bull probability: buy when the probability reaches the buy threshold, sell when it falls to the sell threshold, and hold in between. The two recipes below apply the rule to the clipped Euler filter WonhamBull, as the paper does, and to the exact-Bayes filter of the same model, MarkovSwitchProb on preset (d). The thresholds are those of the published thresholds table of “The Wonham bull filter” in this category, written there as (on = buy, off = sell), with its note on the swapped headers; this page does not restate them. Each recipe reads one series of closes c.
Dai’s rule on the Euler filter
pos := c.WonhamBull(0.36, 2.53, 0.18, -0.77, 0.184).Hysteresis(math.Nextafter(on, math.Inf(-1)), math.Nextafter(off, math.Inf(1))).GT(0)
exec := pos.Shift(1)- Rule:
on, off := 0.934, 0.768, the pair of p.17 for the DJIA set of Table 1 that the block passes. Each of Table 7’s pairs goes with its own index’s set from the published sets table of the same page: substitute both.posis 1 when long and 0 when flat, started flat (the paper’s Lambda*_0), andexecis the same position one bar later, for a backtest that trades on the next bar. - Ties: Theorem 5 (p.12) stops at p >= p*_b and at p <= p*_s, while
Hysteresisis strict, so the block moves both thresholds one ulp inwards withmath.Nextafter. That is exact for every input, because each published pair is many ulps apart. On the input 0.5, 0.934, 0.9, 0.768, 0.8 at the p.17 pair the latch reads -1, 1, 1, -1, -1 andpos0, 1, 1, 0, 0, where the strictHysteresis(on, off)reads -1 on every bar andpos0. On the AAPL closes no probability equals a threshold, and the two forms agree on all 800 bars of the four composites below. - The printed order: the paper writes each pair as (p*_s, p*_b), sell first. Passed in that order,
Hysteresis(0.768, 0.934)is an invalid pair and returns zeros, soposis 0 on every bar: flat for ever, with no error. - First valid index: 0, and the minimum length is 1. Bar 0 is the prior xi, 0.84998 for the DJIA set, and each set’s xi lies inside the band of its own pairs, so
posis 0 until the first bar at or beyond a threshold.posandexecare 0 or 1 and never NaN;execis 0 at bar 0, Shift’s pad. No output is -0. - Masks: none. A NaN, infinite, zero or negative close is a missing observation to the filter, which takes its prediction step there and on the next bar, so the probability stays finite and the latch decides on the predicted value. Invalid filter parameters give zeros, a probability of 0, which latches -1:
posreads flat on every bar. - The breakeven (commentary, not Dai’s trading rule): Theorem 4 i) (p.10) places the breakeven (rho-mu2)/(mu1-mu2) between the two thresholds, so
be := p.GT(pBE), with p the filter’s output, is a single strict threshold that needs only the parameters. The breakevens are 0.8820 for the DJIA set at Table 1’s rho = 0.0679, 0.8811 for the DJIA set at rho = 0.067, 0.8411 for SP500 at rho = 0.067 and 0.5686 for NASDAQ at rho = 0.054, each inside its band. Without the band the flag switches more often than the latch: on the four composites below it switches 9, 11, 5 and 7 times, the latch 1, 3, 1 and 5 times. It is valid only with parameters fixed by the caller from a training prefix: nseries has no adaptive Wonham filter that estimates the drifts bar by bar, and one that did would not expose them, so the breakeven cannot be composed with it. - Anchors: E: the latch equals a per-bar loop with Theorem 5’s tests, p >= on and p <= off, on every input, and the strict form wherever no probability equals a threshold. E: the latch is monotone in its input, so a latch that is unchanged when p moves by eps either way is certified against any error below eps in p. On the 200 AAPL closes of 2023 the four composites are long from bar 6 with the p.17 pair (194 long bars; the nearest probability 1.685e-4 from a threshold, certified at eps 1e-3); long at 9, flat at 106 and long at 114 with the DJIA set at (0.94, 0.78) (183 long bars; 2.158e-5, certified at 3.5e-3); long from bar 6 with the SP500 set at (0.91, 0.74) (194; 1.161e-3, certified at 3.5e-3); and long at 10, 115 and 163 and flat at 97 and 120 with the NASDAQ set at (0.69, 0.45) (129; 4.639e-5, certified at 1.1e-4). T: the filter’s values are within TOL-R of the committed references of
WonhamBull; the latch states are compared bit for bit only after the certificate holds. - Evidence: the parameters and the thresholds are in-sample: both come from a hindsight division of 1962-2008 into bull and bear markets, the period that the paper’s trading tests then cover. Its first Table 6 (p.20) shows the spread between the thresholds controlling turnover, not returns. Only the constant thresholds of p.16 are used: the paper’s exact rule has thresholds that depend on the time left to the end of the sample and sells at that end, which no causal series can do. The latch is not start-invariant: its settling length is path-dependent, and a change of one ulp in a probability near a threshold can change every later bar until the next decision.
- Pinned by
TestRecipeDaiLatch; runnable exampleExampleSeries_WonhamBull_daiLatch.
The exact-Bayes filter of the same model
x := c.Log().Delta().SetN(1, math.NaN())
pb := x.MarkovSwitchProb(0.9985682912204104, 0.9899382688545507, 0.000652288, 0.011637181789419635, -0.0031477120000000004, 0.011637181789419635)
posB := pb.Hysteresis(math.Nextafter(on, math.Inf(-1)), math.Nextafter(off, math.Inf(1))).GT(0)- Preset: the six arguments are row (d) of the presets table of “The two-state Gaussian Markov-switching filter” in this category, passed as the literals printed there: the discretisation that
WonhamBull’s doc comment gives for the DJIA set at dt = 1/250, a model observed once a bar with the regime held for the bar. Regime 1 is the bull emission (mu1, sigma1), sopbis the bull probability and the latch reads it directly. Five literals are the correctly rounded values of that discretisation; mu2’s literal, -0.0031477120000000004, is one ulp below the correctly rounded value, -0.003147712, because it is the binary64 evaluation of the doc comment’s formula. Pass the literals as printed. - Approximation: Dai’s thresholds were solved for the continuous-time filter, so applying them to this discrete filter is an approximation. On the 200 AAPL closes of 2023 the two filters differ by up to 0.086 (bar 134), and the positions at the p.17 pair differ on 11 of the 200 bars, 8 when both start from xi.
- Start: bar 0 of
xis masked, sopbat bar 0 is the prior, by default the stationary share 0.8754325259515552 and not xi; pass xi, 0.8499830985463823, as the seventh argument to start whereWonhamBullstarts. A zero close gives a log of -Inf, soxis -Inf there and +Inf on the next bar, and a negative close gives NaN on both: missing observations, on which the filter takes its prediction step. - First valid index: 0, and the minimum length is 1;
pbis a finite probability on every bar, andposBis 0 or 1, never NaN and never -0. - Anchors: T:
pbis within TOL-R of the committed references ofMarkovSwitchProbfor preset (d) on the AAPL log returns. E: the latch’s certificate as above. On the 200 AAPL closes of 2023 at the p.17 pairposBis long at bar 3, flat at 106 and long at 114 (189 long bars; the nearest probability 1.888e-4 from a threshold, certified at eps 5e-4); at (0.94, 0.78) long at 6, flat at 106 and long at 114 (186; 1.067e-3); and with p0 = xi at the p.17 pair long at 6, flat at 106 and long at 114 (186). - Pinned by
TestRecipeExactBayesWonham; runnable exampleExampleSeries_MarkovSwitchProb_exactBayesWonham.
First valid index of the latch stages
| Stage | First valid index f | Before f |
|---|---|---|
WonhamBull(lambda1, lambda2, mu1, mu2, sigma), MarkovSwitchProb(p11, p22, mu1, sigma1, mu2, sigma2), Hysteresis(on, off), GT(y), Log() | 0 | nothing |
Shift(k) | k | zeros |
Delta() | 1 | zeros |
SetN(n, val) | n | the value val |
The two-state Gaussian Markov-switching filter
MarkovSwitchProb(p11, p22, mu1, sigma1, mu2, sigma2, p0...) is the filtered probability that a two-regime model is in regime 1, updated once per bar from an observation series; MarkovSwitchPredict is the probability for the next bar and MarkovSwitchMean the expected next observation. The parameters are fixed by the caller: p11 and p22 are stay probabilities, and regime k draws observations from a normal distribution with mean mu_k and standard deviation sigma_k, in the units of the observation. Nothing is estimated, so a preset is only as good as the sample it came from.
The warm-up and gaps. There is no warm-up: bar 0 is filtered from p0, the probability of regime 1 before bar 0’s observation. A NaN or infinite observation is missing and takes the prediction only, so mask every upstream warm-up with NaN rather than leave it as an aligned zero, which the filter would read as an observation of 0.
(a) Receivers, masks and the regime-2 view
x := c.Log().Delta().SetN(1, math.NaN())
prob := x.MarkovSwitchProb(p11, p22, mu1, sigma1, mu2, sigma2, p0)
regime2 := prob.Mul(-1.0).Add(1.0)
xs := c.Log().XAverage(span).Delta().SetN(span, math.NaN())- Receiver: log returns with bar 0 masked; the output at bar 0 is then p0 itself. Without the mask, Delta’s 0 at bar 0 is read as a flat return.
- Smoothed receiver: smooth first, then take the difference and mask the whole warm-up, bars 0 to span-1. Smoothing the masked returns instead leaves bars 1 to span-2 unsmoothed and gives NaN from bar span-1 on, because the exponential average carries the NaN at bar 0 forward.
- Regime 2 is one minus the output, bit for bit
1 - Prob. - Pinned by
TestRefMarkovSwitch; runnable exampleExampleSeries_MarkovSwitchProb_views.
(b) Presets and the daily rule
p11, p22 := 0.9985682912204104, 0.9899382688545507
mu1, mu2, sigma := 0.000652288, -0.0031477120000000004, 0.011637181789419635
prob := x.MarkovSwitchProb(p11, p22, mu1, sigma, mu2, sigma)The presets are documentation, not defaults: each published set summarises bull and bear phases dated with hindsight over a whole sample (Jansen’s toy set is made up for illustration), and none comes with out-of-sample evidence. Pass them as float64 literals, exactly as printed; the default p0 is the stationary share.
| Preset | p11 | p22 | mu1 | sigma1 | mu2 | sigma2 |
|---|---|---|---|---|---|---|
| (a) Jansen’s toy set (p0 0.8; tests only) | 0.95 | 0.90 | 0.05 | 0.06 | -0.10 | 0.08 |
| (b) Zakamulin and Giner 2022, monthly | 0.9649614576033637 | 0.9258160237388724 | 0.019825 | 0.046736504290900205 | -0.023908333333333334 | 0.056869001515178146 |
| (c) Giner and Zakamulin 2023, S&P, monthly | 0.965552876334826 | 0.931129476584022 | 0.019166666666666665 | 0.04477351337565548 | -0.022775 | 0.05331829735966195 |
| (c) Giner and Zakamulin 2023, DJIA, monthly | 0.9631132423459978 | 0.9230769230769231 | 0.019933333333333334 | 0.04604368396787266 | -0.024058333333333334 | 0.055079215680690304 |
| (d) Dai, Zhang and Zhu 2009, daily | 0.9985682912204104 | 0.9899382688545507 | 0.000652288 | 0.011637181789419635 | -0.0031477120000000004 | 0.011637181789419635 |
| (b) daily, by the matrix root | 0.9982380050673411 | 0.9962694855060766 | 0.000944047619047619 | 0.010198741363365647 | -0.0011384920634920634 | 0.012409833530469629 |
| (c) S&P daily, by the matrix root | 0.9982730808312953 | 0.996547351000861 | 0.0009126984126984126 | 0.009770381627288525 | -0.0010845238095238095 | 0.011635006360800714 |
| (c) DJIA daily, by the matrix root | 0.9981405914203078 | 0.9961224179541956 | 0.0009492063492063492 | 0.010047555574161957 | -0.0011456349206349207 | 0.012019270241693428 |
- Sources: (b) Table 1, p. 8: mean durations 28.54 and 13.48 months, p = 1 - 1/E[d], annual means and volatilities divided by 12 and sqrt(12) on S&P 500 capital-gain returns; (c) Table 1, p. 28, on total returns; (d) Table 1, p. 15: intensities 0.36 and 2.53, drifts 0.18 and -0.77 and one volatility 0.184 a year (the Dow’s bull and bear statistics for 1962 to 2008 of Table 6, p. 21, with the volatility the average of the two phases’), mapped to daily bars with dt = 1/250 through the exact two-state discretisation, an approximate mapping of the continuous-time model.
- The daily rule. A monthly set is not made daily by dividing p by 21. Take the 21st root of the chain’s second eigenvalue, L_d = L_m^(1/21) with L_m = p11 + p22 - 1 > 0, keep the stationary share pi1, and set 1 - p11_d = (1 - pi1)(1 - L_d) and 1 - p22_d = pi1 (1 - L_d); divide the means by 21 and the standard deviations by sqrt(21). The daily rows above are this rule evaluated exactly by reference A and rounded once; a caller with other figures can evaluate the root with
Series.Pow. - Pinned by
TestRecipeMarkovSwitchPresets(every preset on AAPL’s 2023 returns, all three outputs, and the daily literals); runnable exampleExampleSeries_MarkovSwitchProb_presets.
(c) The h-step regime forecast
q, Lh := prob, 1.0
for i := 0; i < h; i++ {
q = q.Mul(L).Add(a).Clamp(0, 1)
Lh *= L
}
closed := prob.Sub(pi).Mul(Lh).Add(pi)- With a = 1 - p22, L = p11 + p22 - 1 and pi = a/((1 - p11) + a), one step of the iteration is
MarkovSwitchPredictbit for bit; h steps forecast bar t+h from bar t. The closed form pi + (Prob - pi)L^h agrees within 1e-13 (it is not bitwise). Form L^h by repeated multiplication. - Pinned by
TestMarkovSwitchExampleGoldens; runnable exampleExampleSeries_MarkovSwitchPredict_horizon.
(d) The predictive log score
z1 := x.Sub(mu1).Div(sigma1)
z2 := x.Sub(mu2).Div(sigma2)
lnf1 := z1.Mul(z1).Mul(-0.5).Sub(math.Log(sigma1) + 0.5*math.Log(2*math.Pi))
r := z1.Sub(z2).Mul(z1.Add(z2)).Mul(0.5).Exp().Mul(sigma1 / sigma2)
pred := x.MarkovSwitchPredict(p11, p22, mu1, sigma1, mu2, sigma2, p0).Shift(1).SetN(1, p0)
ls := lnf1.Add(pred.Add(pred.Mul(-1.0).Add(1.0).Mul(r)).Log())- ls_t = ln(pred f1 + (1 - pred) f2), the log density of x_t under the model’s forecast from bar t-1, is written as ln f1 plus the log of the forecast mixed with the likelihood ratio r = f2/f1, so that no density is formed and nothing underflows. Its rolling sum
ls.Sum(n)compares parameter sets on the same data. - On a bar far out in the tail where regime 2 is overwhelmingly more likely (with sigma1 < sigma2, a bar many sigmas out), r can overflow to +Inf, and then ls is +Inf although the true score is finite and very negative: mask such bars, or compare sets only on bars where both are finite.
- The score is in the units of the observation: scores on log returns and on simple returns differ by the log of the Jacobian, ln|dx/dy|, so compare sets only on one scale.
- Pinned by
TestMarkovSwitchExampleGoldens; runnable exampleExampleSeries_MarkovSwitchProb_logScore.
Chen and Tsang’s B-Simple and B-Strict thresholds (research composition)
Research composition. Chen and Tsang’s B-Simple and B-Strict rules classify a static naive-Bayes posterior on tracking features, fitted on labels from a full-sample EM fit (their §5.3 and §5.4). Applying the two rules to a causal filtered probability with caller-fixed parameters is our transfer; the book gives no parameters for it and its Tables 6.6 to 6.8 report regime information lowering final wealth in 8 of 9 cells.
The rules read the probability of the abnormal regime, Regime 2 of the book, the regime of rapid price changes. The recipe below takes it from MarkovSwitchProb on an observation series x, the log returns c.Log().Delta().SetN(1, math.NaN()) of closes c in the Example.
pA := x.MarkovSwitchProb(p11A, p22N, muA, sigmaA, muN, sigmaN)
bSimple := pA.GT(0.5)
bStrict := pA.GT(0.8)- The abnormal regime first:
MarkovSwitchProbreturns the probability of its regime 1, so pass the abnormal regime’s stay probability and emission first:p11Ais the abnormal regime’s stay probability,p22Nthe normal regime’s, and (muA,sigmaA) and (muN,sigmaN) their emissions. ThenpAis the abnormal probability itself, and B-Simple’s test that it exceeds the normal probability, p2 > p1 with p1 = 1 - p2, is exactlypA.GT(0.5). Passing the normal regime first and forming 1 - p is not exact, because 1 - p rounds: with stay probabilities 0.6 for the abnormal regime and one ulp below 0.6 for the normal one, the default prior is 0.5000000000000001 with the abnormal regime first, and 0.49999999999999994 with the normal regime first, whose 1 - p, 0.5 + 2^-54 exactly, rounds to 0.5: a tie, read as regime 1. On the 200 AAPL log returns of 2023 with the Example’s set the two routes differ in value on 119 bars on arm64 and 122 on amd64 (GOAMD64=v1), by at most 2.2e-16 on both, and in no flag. - The band and the tie:
bSimpleis 1 whenpAexceeds 0.5 andbStrictwhen it exceeds threshold2 = 0.8. The book leaves the band (0.5, 0.8] under B-Strict and the tie at 0.5 unclassified; both rules read them as regime 1, as its two-level figures do. With equal stay probabilities the default prior is 0.5, and with bar 0 ofxmaskedpAat bar 0 is that prior exactly: a tie, read as regime 1.pA.GTE(0.5)would read it as regime 2. - Parameters: the book publishes none for a Gaussian filter. The Example’s set is illustrative: stay probabilities 0.9, drifts -0.001 and 0.0005 and volatilities 0.02 and 0.004 a bar for the abnormal and the normal regime. Fix the parameters a priori or from a training prefix.
- First valid index: 0, and the minimum length is 1. Mask an upstream warm-up with NaN before the filter, as for every receiver of
MarkovSwitchProb; the masked bar 0 of the log returns is a missing observation, not a warm-up, so nothing is trimmed. The flags are 0 or 1 and never NaN or -0. - Invalid parameters:
MarkovSwitchProbreturns zeros, a stay probability of 1 included, and zeros read as regime 1 on every bar under both rules. With the normal regime first they would read as regime 2 certain. - Anchors: E:
pA.GT(0.5)equalspA.Mul(2.0).GT(1.0)bit for bit, because doubling is exact, and that is p2 > 1 - p2 in exact arithmetic. E:bStrictimpliesbSimpleon every bar. On the 200 AAPL log returns of 2023 with the Example’s setbSimpleis 1 on 141 bars andbStricton 85, 56 bars lie in the band and bar 0 is the tie. - Sources: Chen and Tsang (Detecting Regime Change in Computational Finance, CRC Press, 2021): B-Simple is Eq 5.6 (§5.4.2, PDF p.119) and B-Strict Eq 5.7 (§5.4.3, PDF p.120), with threshold2 = 0.8 set by the authors as an investor’s choice; Regime 1 is the normal regime and Regime 2 the abnormal one in the panel titles of p.119, and §6.2.2 (PDF p.132) measures an abnormal regime by a rapid change of prices. B-Simple is B-Strict with the threshold at 0.5.
- Pinned by
TestRecipeChenTsangThresholds; runnable exampleExampleSeries_MarkovSwitchProb_chenTsangThresholds.
First valid index of the threshold stages
| Stage | First valid index f | Before f |
|---|---|---|
MarkovSwitchProb(p11, p22, mu1, sigma1, mu2, sigma2), GT(y) | 0 | nothing |
Outcomes conditioned on a state
StateUpProb, StateMean, StateCount and StateMeanLogReturn read the row of the current bar’s state. At bar t the anchors are the n bars j from t-h-n+1 to t-h; each is paired with the outcome realised h bars later, at j+h, and the row is the anchors whose state equals state[t]. StateUpProb is the share of the row after which the price rose by more than the tolerance, StateMean the mean of the receiver at j+h, StateCount the row’s size and StateMeanLogReturn the mean h-bar log return. A state code is a signed whole number of magnitude up to 2^53, so negative codes and the codes of UpDown(k) are rows of their own, and NaN marks an undefined bar. The state is right-aligned with the receiver at the most recent bar.
Warm-up, empty rows and masks. The bars before n+h-1 read 0, and a state with no valid anchor in the window reads 0 with a count of 0: read StateCount before trusting a probability or a mean. A builder’s warm-up values are valid codes (the first k bars of UpDown(k) are 0, k flat changes), so the recipes mask them with SetN; a mask of k bars makes bars n+h-1 to n+h+k-2 NaN, and bar n+h+k-1 is the first numeric one. An undefined state at the current bar gives NaN there, and an undefined state or a non-finite outcome in the window gives NaN until it leaves.
The evidence. The conditional tables of Vakkur, Pagonidis, Trongone, Merrill and Williams are whole-sample statistics, read in the sample they describe. The recipes rebuild their constructions on a rolling window; they do not reproduce the tables’ figures, and no source shows an edge out of sample.
The Examples’ closes are the 40 bars 100 + float64(i*i%17) + float64(i%5)/4, whose up and down rows always mix rises and falls, with a flat change from bar 34 to 35; n = 20 throughout, and h = 1 except in (e), where h is the day k.
(a) The probability of a fall
state := c.UpDown(1, tol).SetN(1, math.NaN())
pUp := c.StateUpProb(state, n, h, tol)
pDn := c.Mul(-1).StateUpProb(state, n, h, tol)
m := c.StateCount(state, n, h)- Use: negating the prices turns each fall into a rise of the same size and leaves the threshold |c[j]|*tol/100 unchanged, so
pDnis the share of falls, exactly; 1 - pUp - pDn is the share of flat changes, within rounding. The last bar is in state 1, a fall, with 8 anchors: 3 up, 4 down and 1 flat at tol 0, and 2 up, 4 down and 2 flat at tol 0.5. - First valid index: n+h-1, NaN there under the one-bar mask; bar n+h, 21 here, is the first numeric one.
- Anchor: with h = 1 on these states
pUpequalsc.MarkovDirNext(n, 2, tol)from bar n+1 on where the prices are finite: 0.3750 at tol 0 and 0.2500 at tol 0.5 on the last bar. - Pinned by
TestRecipeStateOutcomes; runnable exampleExampleSeries_StateUpProb_views.
(b) Merrill’s Up/(Up+Down)
merrill := pUp.Div(pUp.Add(pDn))
up, down := pUp.Mul(m).Round(), pDn.Mul(m).Round()- Use: the share of rises among the changes that moved, leaving out the flats: 0.4286 (3 of 7) at tol 0 and 0.3333 (2 of 6) at tol 0.5. It divides two rounded quotients, so it can miss up/(up+down) in the last bit (3 up and 1 down in 5 anchors give 0.7499999999999999), and
Divreads a row with neither rises nor falls as 0. The counts are whole numbers recovered by rounding. Merrill’s own states are the last three or four hourly swings of each day, built by the caller and aligned to the daily closes, with h = 1; the daily analogue is the pattern state of (f). - First valid index: as for (a).
- Pinned by
TestRecipeStateOutcomes; runnable exampleExampleSeries_StateUpProb_views.
(c) The percent change
roc := c.RateOfChange(h).MaskNonFinite(c.Log().Delta(h))
percent := roc.StateMean(state, n, h)- Use: the mean h-bar percent change after the current state, the outcome of Vakkur’s and Pagonidis’s tables: 0.7729 after state 1 on the last bar.
RateOfChangereads a zero base as 0, a flat bar, rather than a missing one, so the mask makes NaN of every bar wherec.Log().Delta(h)is not finite: a zero, negative or non-finite price at either end. - First valid index: n+h-1, as for (a).
- Pinned by
TestRecipeStateOutcomes; runnable exampleExampleSeries_StateMean_outcomes.
(d) The dollar change and the log return
dollar := c.Delta(h).StateMean(state, n, h)
logMean := c.StateMeanLogReturn(state, n, h)
viaLog := c.Log().Delta(h).StateMean(state, n, h)- Use: the mean price change in the receiver’s units, 0.719 after state 1, and the mean h-bar log return, 0.00620.
- Anchor:
logMeanequalsviaLogbit for bit for any lengths. - First valid index: n+h-1, as for (a).
- Pinned by
TestRecipeStateOutcomes; runnable exampleExampleSeries_StateMean_outcomes.
(e) Trongone’s day-k change
roc1 := c.RateOfChange(1)
bucket := roc1.GT(2.0).Sub(roc1.LT(-2.0)).SetN(1, math.NaN())
day := c.Delta().StateMean(bucket, n, k)- Use: the single-day change on the k-th day after a day in the bucket, +1 for a rise of more than 2%, -1 for a fall of more than 2% and 0 otherwise: with h = k,
c.Delta()at j+k is the change from day j+k-1 to day j+k. The last bar is in bucket -1, and days 1, 2 and 3 after the 7 such anchors of each window average 0.8214, 2.2857 and -2.8214. Mask a zero base as in (c) where prices can be zero. - First valid index: n+k-1, NaN there under the one-bar mask; bar n+k is the first numeric one.
- Pinned by
TestRecipeStateOutcomes; runnable exampleExampleSeries_StateMean_outcomes.
(f) Order-k patterns
pattern := c.UpDown(2, 0.5).SetN(2, math.NaN())
pPattern := c.StateUpProb(pattern, n, h, 0.5)- Use: the state is the last k directions, the newest in the low two bits, so code 9 is a rise followed by a fall; at tol 0.5 the last bar’s pattern 9 has 4 anchors, and 1 of them was followed by a rise, 0.2500. Rows thin out as 3^k grows against n, so read
StateCountwith each pattern. - First valid index: n+h-1, NaN to bar n+h+k-2 under the k-bar mask; bar n+h+k-1, 22 here, is the first numeric one.
- Pinned by
TestRecipeStateOutcomes; runnable exampleExampleSeries_StateUpProb_views.
(g) Williams’s at-least-k down closes
flag := c.ConsecDown().GTE(float64(k)).SetN(k, math.NaN()).MaskNonFinite(c.Sum(k + 1))
oc := c.Sub(o)
rows := flag.Copy()
rows[last] = row
mean := oc.StateMean(rows, n, 1)- Use: Williams buys the open after at least k down closes and sells at the same session’s close. The flag is 1 on such days, and
oc.StateMean(flag, n, 1)is the mean open-to-close change of the sessions that followed the anchors whose flag equals the current bar’s. Overwriting the last bar of a copy, which is no anchor of its own window, selects a row whatever today’s flag is: row 1, the published condition, has 4 sessions averaging 2.19, and row 0, the rest, 16 averaging -0.61 (opens from the previous close plus float64(i%4-1)/2). The mask reads the k+1 closes throughc.Sum(k + 1), which is NaN when any of them is:ConsecDownresets to 0 on a NaN comparison, so a mask on c alone leaves a flag of 0 on the k bars after a missing close. - First valid index: n, NaN to bar n+k-1 under the k-bar mask; bar n+k, 22 here, is the first numeric one.
- Pinned by
TestRecipeStateOutcomes; runnable exampleExampleSeries_StateMean_williams.
(h) Conditional volatility
y := c.Log().Delta(h)
m1 := y.StateMean(state, n, h)
m2 := y.Mul(y).StateMean(state, n, h)
cnt := y.StateCount(state, n, h)
sd := m2.Sub(m1.Mul(m1)).Max(0.0).Sqrt()
sdBessel := m2.Sub(m1.Mul(m1)).Max(0.0).Mul(cnt.Div(cnt.Sub(1))).Sqrt()- Use: the standard deviation of the log returns after the current state, from E[y^2] - E[y]^2 clipped at 0, in the population form and with Bessel’s correction cnt/(cnt-1): 0.05432 and 0.05807 over 8 returns on the last bar.
Divreads cnt = 1 as 0, so the corrected form is 0 on one return and -0 on an empty row (bar 35 here): mask both forms wherecnt.GTE(2)is 0. - Cancellation: the difference loses the digits the two means share when |mean| is large against the spread. Fifty values alternating 1e6 and 1e6+1e-5 give 1.221e-4 against a true 2.5e-11, so use returns rather than prices, or subtract a constant near the mean first.
- First valid index: n+h-1, as for (a).
- Pinned by
TestRecipeStateOutcomes, with tolerance goldens; runnable exampleExampleSeries_StateMean_conditionalVolatility.
First valid index of the state stages
A state masked for its first k bars makes the four methods NaN from bar n+h-1 to bar n+h+k-2, after the zeros.
| Stage | First valid index f | Before f |
|---|---|---|
StateUpProb(state, n, h, tol), StateMean(state, n, h), StateCount(state, n, h), StateMeanLogReturn(state, n, h) | n + h - 1 | zeros |
UpDown(k, tol) | k | zeros |
Delta(h), RateOfChange(h) | h | zeros |
ConsecDown() | 1 | zeros |
Sum(n) | n - 1 | the sum of the bars so far |
MarkovDirNext(n, to, tol) | n + 1 | zeros |
Log() | 0 | nothing |
Vakkur’s extendedness strata
Vakkur runs a 10% swing filter on monthly S&P 500 closes and tabulates, for each 25% band of extendedness (the move from the last confirmed swing extreme), how often the index rose one month and twelve months later and the mean change (his Fig 4). The recipe takes the band as a state from DirectionalChange and DirectionalChangeExtension and reads its rows with StateUpProb and StateMean over a rolling window of n months, the causal recast of his whole-sample table.
Units. The threshold 0.10 and the extension are fractions: 0.10 means a 10% move, and Vakkur’s bands from -25% to 100% are the edges -0.25 to 1.0. This differs on purpose from the percentage tolerance of UpDown, UpDownString and UpDownSum and the thresholdPercent of Pivots and PivotIndices, where 5 means 5%. The difference was flagged for review, and GLE-254 (3 October 2026) kept both conventions: the unit follows the method family. RateOfChange(1), the outcome of mean1, is in percent.
st10 := c.DirectionalChange(0.10)
e := c.DirectionalChangeExtension(0.10)
b := e.GTE(-0.25).Add(e.GTE(0.0)).Add(e.GTE(0.25)).Add(e.GTE(0.5)).Add(e.GTE(0.75)).Add(e.GTE(1.0))
bucket := st10.If(func(v float64) bool { return v == 0 }, math.NaN(), b.MaskNonFinite(e))
up1, up12 := c.StateUpProb(bucket, n, 1), c.StateUpProb(bucket, n, 12)
mean1 := c.RateOfChange(1).MaskNonFinite(c.Log().Delta()).StateMean(bucket, n, 1)
y := c.Delta(12).GT(0.0).MaskNonFinite(c, c.Shift(12))
alt := y.StateMean(bucket, n, 13)- Codes:
bucketis 0 below -0.25, 1 from -0.25 to below 0, 2 from 0 to below 0.25, 3, 4 and 5 for the next three bands of 0.25, and 6 from 1.0 on. The six edges are partition edges, each band closed below and open above, so an extension of exactly -0.25 is in band 1.bucketis NaN before the first confirmation, where the state is 0 and the extension a placeholder 0, and on a missing close (NaN, infinite, or not above 0), where the extension is NaN and everyGTEwould give 0. - No shift:
StateUpProbandStateMeanpair the band at anchor month j with the change from j to j+h, which is Vakkur’s one-month lag (he moves the band down one row, against the next month’s change). Shifting the band as well would lag it twice. - Outcomes:
up1andup12are the shares of the current band’s anchor months after which the close rose over one and twelve months, andmean1is the mean one-month percent change after them, masked as in recipe (c) of “Outcomes conditioned on a state” in this category:RateOfChangereads a zero base as 0, andc.Log().Delta()is not finite where either close is missing. Here each such month is also a NaN band, so the mask changes no value; it matters when the state comes from another series. A band with no anchor in the window reads 0, so readStateCountwith each. - The twelve-month alignment:
up12reads Vakkur’s twelve-month column from the close that also starts his one-month column, C[t-1] to C[t+11] for his month t. This is an assumption: he states that every column uses last month’s band, but not whether its twelve months start at that month or the next. The other reading, C[t] to C[t+12], isalt, the share of the anchor months j with c[j+13] above c[j+1];yis masked where c orc.Shift(12)is not finite. - First valid index: n+h-1 for
up1,up12andmean1(n, n+11 and n) and n+12 foralt, with zeros before; the minimum length is one more. From there each is NaN until the months before the first confirmation have left its window, so its first numeric month is the first confirmation plus that index, a start that depends on the data:st10.EQ(0.0)detects the months before the confirmation. On the 480-month index of the tests at n = 240 the first confirmation is month 8, and the first numeric months are 248 forup1andmean1, 259 forup12and 260 foralt. - Masks: a missing close at month p makes
bucketNaN at p only, and the state carries on after it as if the month were absent. For n of at least 12, a NaN or infinite close makesup1andmean1NaN on [p, p+n],up12on [p, p+n+11] andalton [p, p+n+12], and each is numeric again after its span; a close of 0 or below, which is finite, leaves the months p+1 to p+11 ofup12and p+1 to p+12 ofaltnumeric. - Anchors: E:
bucketequals the count of the six edges at or below the extension wherever the state is not 0 and the extension is finite, bit for bit, andup1,up12andaltequal whole-number counts over each row, divided once. On the constructed closes 100, 95, 108, 125, 150, 180, 160, 140, NaN, 135, 120, 95, 100 the bucket is NaN, NaN, 2, 3, 4, 5, 1, 1, NaN, 1, 0, 0, 0, the extension at bar 9 being exactly -0.25. On the 480-month index all seven codes occur, on 55, 21, 56, 144, 84, 45 and 67 months. - Ties:
DirectionalChange(0.10)is strict, like Vakkur’s spreadsheet; his prose is inclusive, which ismath.Nextafter(0.10, 0)in both calls (the table of “Directional change” in the “Regime Detection” category lists both). His own extension is C/|ref| - 1 after product tests, from an assumed upward start, so his bands agree with the recipe’s only away from rounding ties and after the start. - Evidence: Fig 4 is a whole-sample table of 552 months in seven bands, rounded and printed with no inputs: it is illustrative, and the recipe does not reproduce it. The edges are fixed in advance, n = 240 months is the causal recast of the whole sample, and no source shows an edge out of sample.
- Sources: Vakkur, “The 10% Swing Filter”, Stocks & Commodities V15:2 (1997): the extendedness column and the one-month lag (PDF p.3) and Fig 4 (PDF p.6).
- Pinned by
TestRecipeVakkurStrata; runnable exampleExampleSeries_StateUpProb_vakkurStrata.
First valid index of the strata stages
| Stage | First valid index f | Before f |
|---|---|---|
StateUpProb(state, n, h), StateMean(state, n, h) | n + h - 1 | zeros |
RateOfChange(h), Delta(h), Shift(h) | h | zeros |
DirectionalChange(theta), DirectionalChangeExtension(theta) | 0 | nothing |
GTE(x), GT(x), Add(x), If(cond, yes, no), MaskNonFinite(refs) | 0 | nothing |
Log() | 0 | nothing |
The Wonham bull filter
WonhamBull is Dai, Zhang and Zhu’s clipped Euler discretisation of the Wonham filter: the probability that prices are in the bull regime of a two-state model whose annual drift is mu1 in the bull regime and mu2 in the bear regime, with a common annual volatility sigma and annual switching intensities lambda1 (bull to bear) and lambda2 (bear to bull). Each bar takes one explicit Euler step of the filter’s equation from the bar’s log return ln(c[t]/c[t-1]), with the bar length dt in years (1/250 by default), and clips the result to [0, 1]. WonhamDrift is the filtered drift, mu2 + (mu1-mu2)*p, the product rounded before the sum.
Start, gaps and the clip. Bar 0 is the prior p0, which defaults to xi, the probability the filter settles at on constant prices, not to the stationary share lambda2/(lambda1+lambda2). A NaN, infinite, zero or negative price has no observation, so the filter takes its prediction step on that bar and the next; the move across the gap is dropped. Mask a pass-through warm-up (Average and XAverage return their input before bar n-1) with SetN first, because those bars are prices to the filter, while a zero warm-up is already a missing price. A move large enough to overshoot clips the output to exactly 0 or 1, and the bar after a clip ignores its own move, because the filter’s gain is 0 at 0 and 1.
The published sets. The parameters are documentation, not causal settings: Dai, Zhang and Zhu estimate them from a hindsight division of the index histories into bull and bear markets (rallies of 24% and declines of 19%, p.20 of the SSRN working paper 1762118), over the same years their trading tests cover. Sigma is the mean of the two regimes’ volatilities, (sigma1+sigma2)/2, as printed: 0.1835 for DJIA shown as 0.184 and 0.3115 for NASDAQ shown as 0.31.
| Index | lambda1 | lambda2 | mu1 | mu2 | sigma | Sample | Source |
|---|---|---|---|---|---|---|---|
| DJIA | 0.36 | 2.53 | 0.18 | -0.77 | 0.184 | 1962-2008 | Table 1, p.15; second Table 6, p.21 |
| SP500 | 0.353 | 2.208 | 0.196 | -0.616 | 0.173 | 1962-2008 | second Table 6, p.21 |
| NASDAQ | 2.158 | 2.3 | 0.875 | -1.028 | 0.31 | 1991-2008 | second Table 6, p.21 |
The Euler step is accurate while kappa = (mu1-mu2)*sqrt(dt)/sigma stays below about 0.4. At dt = 1/250:
| Index | kappa | (lambda1+lambda2)*dt |
|---|---|---|
| DJIA | 0.327 | 0.0116 |
| SP500 | 0.297 | 0.0102 |
| NASDAQ | 0.388 | 0.0178 |
The published thresholds, written here as (on = buy, off = sell): the paper reads an up trend, a buy, when the probability crosses the buy threshold p*_b and a down trend, a sell, when it crosses the sell threshold p*_s, and it writes the pair in the order sell, buy.
| Index | on (buy, p*_b) | off (sell, p*_s) | Source |
|---|---|---|---|
| DJIA | 0.934 | 0.768 | p.17 text, for the Table 1 set |
| SP500 | 0.91 | 0.74 | Table 7, p.21, bold cells |
| DJIA | 0.94 | 0.78 | Table 7, p.21, bold cells |
| NASDAQ | 0.69 | 0.45 | Table 7, p.21, bold cells |
Three printed tables swap their headers: Table 4 (p.19) prints the DJIA pair of p.17 in its first row, with a discount rate of 0.067, under swapped p*_b and p*_s headers, and Table 5 and the first Table 6 (p.20) head their column of lower thresholds Buy and their column of higher ones Sell. The thresholds are in-sample like the sets. Hysteresis gives a two-threshold latch of the probability; the latch with the paper’s rule is the section “Dai’s rule on the Euler filter” in this category.
(a) The bull probability
p := c.WonhamBull(0.36, 2.53, 0.18, -0.77, 0.184)- Use: the DJIA set with dt = 1/250 and p0 = xi; on the Examples’ path (100exp(0.004t), 6% higher from bar 6) bar 0 is xi, 0.84998, the jump at bar 6 clips to 1, and bar 7 is 1 - lambda1*dt = 0.99856 whatever its move. On the 2023 AAPL closes bar 35, a 4.7% rise, clips to 1 with the DJIA and SP500 sets, and NASDAQ’s set never clips.
- First valid index: 0; the minimum length is 1.
- Pinned by
TestRecipeWonhamPresets; runnable exampleExampleSeries_WonhamBull.
(b) The filtered drift
d := c.WonhamDrift(0.36, 2.53, 0.18, -0.77, 0.184)- Use: an annual drift of the price’s return in the units of mu1 and mu2, from mu2 at p = 0 to (mu1-mu2)+mu2 at p = 1, which can miss mu1 by the roundings of mu1-mu2 and of the sum (0.17999999999999994 for the DJIA set’s 0.18).
- Anchor: it equals
c.WonhamBull(...).Mul(mu1-mu2).Add(mu2)bit for bit for valid parameters. - Pinned by
TestRecipeWonhamPresets; runnable exampleExampleSeries_WonhamDrift.
(c) Masking a pass-through warm-up
a := c.Average(3)
masked := a.SetN(2, math.NaN()).WonhamBull(0.36, 2.53, 0.18, -0.77, 0.184)- Use:
Average(3)returns bars 0 and 1 unchanged, and the filter would read them as prices; masked, bars 1 and 2 are prediction steps, and bar 2 reads 0.85057 against 0.86399 unmasked on the Examples’ path. - Pinned by
TestRecipeWonhamPresets; runnable exampleExampleSeries_WonhamBull.
The h-step state probability
MarkovAhead gives the probability, implied by the transition matrix of the last n transitions, that a state series will be in a given state h bars ahead, and MarkovDirAhead does the same on the direction codes of UpDown(1). The value at bar t is a forecast made at bar t for bar t+h: compare it with the state at t+h and do not shift it back.
(a) The direction chain, generic and twin
codes := c.UpDown(1)
finite := func(_ float64, i int) bool { return i > 0 && c[i]-c[i] == 0 && c[i-1]-c[i-1] == 0 }
z := codes.If(finite, codes, math.NaN())
generic := z.MarkovAhead(n, 3, h, up)
dir := c.MarkovDirAhead(n, h, up)- Use:
zholds the codes ofUpDown(1), 0 flat, 1 down and 2 up (upis 2), NaN at bar 0 and wherever a price of the change is not finite: the twin’s own direction series, masked as in the direction-chain recipes. Each step multiplies the probability vector by the window’s matrix in a fixed order, so the value is the same on every platform; as h grows it approaches the long-run share ofMarkovStationaryon an aperiodic window, and direction chains are close to it by h = 2 or 3. - First valid index: n for
generic, which reads NaN at bar n because its window holds the masked bar 0; n+1 fordir, which reads 0 there. From bar n+1 on the two agree bit for bit, missing prices included. - Empty row: where the window holds no transition from the current state the value is 0 for every target and horizon, as for an unreachable target;
MarkovCount(n, 3, i)at the current state i tells the two apart. - Anchor: E:
direqualsgenericbit for bit on every bar from n+1 on, missing prices included (the twin against the generic call on the masked codes). - Pinned by
TestRecipeMarkovAhead_directionChain; runnable exampleExampleSeries_MarkovAhead_directionChain.
Long-run share and expected spell length
MarkovStationary gives the long-run share of a state under the transition matrix of the last n transitions, and MarkovDuration the expected total spell length of a state, 1/(1-p_ii), counting the current bar; the Dir twins do the same on the direction codes of UpDown(1). Both rest on the window’s integer counts, so each output is a ratio of whole numbers rounded once, and three exact identities with existing methods hold.
(a) The occupancy identity
z := c.UpDown(1).SetN(1, math.NaN())
share := z.MarkovStationary(n, 3, up)
occupancy := z.EQ(float64(up)).Average(n)- Use:
zholds the codes ofUpDown(1), 0 flat, 1 down and 2 up (upis 2), with bar 0 masked. Where the window’s first and last states agree, or the current row is empty, the share is the occupancy ofupamong the later states of the n transitions, bit for bit; elsewhere the share is the stationary distribution on the closed class the current state reaches, and it can be far from the occupancy (on persistent states it pins at 0 or 1). - First valid index: n for both; the minimum length is n+1. The share reads 0 on the warm-up, and NaN on [max(p, n), p+n] for an invalid state at bar p, where the occupancy reads the bad bar as not in state.
- Anchor: E, on every bar from n on whose window holds only valid states and has equal endpoints or an empty current row.
- Pinned by
TestRecipeMarkovDuration; runnable exampleExampleSeries_MarkovStationary_occupancy.
(b) The expected spell length from counts
d := z.MarkovDuration(n, 3, up)
e := z.EQ(float64(up))
ePrev := e.Shift(1)
ratio := ePrev.Sum(n).Ratio(ePrev.Mul(e.Sub(1.0).Mul(-1.0)).Sum(n).Max(1.0))
dir := c.MarkovDirDuration(n, up)- Use:
ePrev.Sum(n)counts the transitions leavingupand the second sum those that change state;Max(1.0)makes a state with no exit read its count, a censored value, asMarkovDurationdoes, where a plainRatiowould give 0. The remaining life is the spell length minus 1. - First valid index: n for
dandratio, n+1 fordir.ratioequalsdbit for bit at every bar from n on whose window holds only valid states, anddirfrom bar n+1 on finite prices; before thatratioreads the masked bar 0 as not up. - Pinned by
TestRecipeMarkovDuration; runnable exampleExampleSeries_MarkovDuration_ratio.
(c) The support of a zero share
seen := z.MarkovCount(n, 3, up).GT(0)- Use: a share of 0 reads the same for a state that does not occur in the window and for one the window holds but its long-run chain leaves out: a transient state on a closed-class bar, or the first state of an empty-row window when it occurs at the window’s first bar alone.
seenis 1 where the window holds a transition fromup: a 0 share there marks a state outside the long-run chain, and a 0 share whereseenis 0 a state that does not occur in the window. - Pinned by
TestRecipeMarkovDuration; runnable exampleExampleSeries_MarkovStationary_occupancy.
The entropy rate and the mutual information
MarkovEntropyRate and MarkovMutualInfo measure, in bits, how uncertain the next state of a state series is given the current one, and how much the current state tells about the next, over the last n transitions. PatternEntropy and PatternMutualInfo do the same for the up and not-up bars of any series, read as w-bar words. All four are plug-in estimates: biased on short windows, and 0 in the warm-up, where 0 also reads as perfect order or independence, so drop the warm-up before ranking or thresholding.
(a) The normalised entropy rate
z := c.UpDown(1).SetN(1, math.NaN())
norm := z.MarkovEntropyRate(n, k).Window(-n).Div(math.Log2(float64(k))).Min(1)- Use:
zholds the codes ofUpDown(1), 0 flat, 1 down and 2 up, with the artificial bar 0 masked; k is 3.Window(-n)drops the n warm-up bars, so element i ofnormis bar i+n; dividing by log2(k) puts the rate on a 0 to 1 scale, andMin(1)caps it, because rounding can leave a uniform table slightly above log2(k). k sizes the table and does not scale the output, so the division is the caller’s. - First valid index: n, which here reads NaN because its window holds the masked bar 0; bar n+1 is the first number.
- Bias: the estimate is low on short windows; a table of kk cells wants about 10k*k transitions, 90 at k = 3.
- Anchor: E: at k = 2, on the up bit of a price series, the entropy rate equals a composition of
EQ,Shift,Sum,Mul,Ratio,Max,Log2,AddandDivbit for bit. - Pinned by
TestRecipeMarkovEntropyRate_normalised; runnable exampleExampleSeries_MarkovEntropyRate_normalised.
(b) The entropy per bar of up and not-up words
first := w + n - 1
perBit := c.PatternEntropy(w, n).Window(-first).Div(float64(w))- Use: the block entropy of the w-bar words over the last n words, divided by w: 1 when every word is equally frequent, 0 when one word repeats. A flat bar is not-up, and there is no tolerance. With n omitted the window is 10*2^w words.
- First valid index: w+n-1;
Window(-first)drops the warm-up, so element i ofperBitis bar i+first. - Bias: low when n is small beside 2^w.
- Anchor: E: at w = 1 the entropy equals a composition of
Delta,GT,Sum,Mul,Sub,Ratio,Max,Log2,AddandDivbit for bit. - Pinned by
TestRecipePatternEntropy_perBit; runnable exampleExampleSeries_PatternEntropy_perBit.
The up/down and continuation presets
MarkovSwitchProbUpDown(p11, p22, q1, q2, p0...) and MarkovSwitchProbContinuation(p11, p22, q1, q2, p0...) are the filtered probability of regime 1 of the two-state chain of MarkovSwitchProbLikelihood, with a Bernoulli observation built from the prices: whether each price rose above the previous price, and whether each price change kept the sign of the previous change. q1 and q2 are the probabilities of an up bar, or of a continuation, in regimes 1 and 2; the stay probabilities and p0 have MarkovSwitchProb’s meanings, and nothing is estimated. For q1 not -0 each method equals MarkovSwitchProbLikelihood bit for bit on the Bernoulli ratio of its code; recipe (b) of the likelihood-ratio Markov-switching filter’s section builds that ratio for any 0/1 code, and its example is Chan’s own up code, which counts a flat bar as up, the form these methods do not build.
The flat rule. In MarkovSwitchProbUpDown a flat bar is not-up evidence; in MarkovSwitchProbContinuation it has no direction, so its own bar and the next are missing. Bar 0 is missing in both, and bar 1 in the continuation filter; a bar whose change is NaN or infinite is missing too, and a missing bar takes the prediction only while the chain still advances. A warm-up of zeros upstream is a run of flat bars: mask it with SetN before the call.
The presets. The presets are float64 literals in the caller’s code, not defaults, and no source shows an edge out of sample for either.
| Preset | p11 | p22 | q1 | q2 | p0 | Source and status |
|---|---|---|---|---|---|---|
Chan, MarkovSwitchProbUpDown | 0.60 | 0.25 | 0.81 | 0.03 | 1 | daily SPY, 22 December 2004 to 15 September 2009, best of 10 expectation-maximisation runs; in sample |
Barberis, Shleifer and Vishny, MarkovSwitchProbContinuation | 0.9 | 0.7 | 1/3 | 0.75 | 1.0/3 | illustrative values for annual earnings shocks, not estimates |
The next observation. The probability that the next code is 1 is g*q1 + (1-g)*q2 for the prediction g, which the recipe forms from the filtered output with a = 1-p22 and L = (p11+p22)-1 as run-time values; written as constant expressions they fold exactly and can differ.
(a) Chan’s up or not-up filter
c := Series{100, 101, 102, 101, 102, 101, 100, 101, 102, 103, 102, 103}
p11, p22, q1, q2, p0 := 0.60, 0.25, 0.81, 0.03, 1.0
P := c.MarkovSwitchProbUpDown(p11, p22, q1, q2, p0)
a, L := 1-p22, (p11+p22)-1
g := P.Mul(L).Add(a).Clamp(0, 1)
next := g.Mul(q1).Add(g.Mul(-1.0).Add(1.0).Mul(q2))
long := next.GT(0.5)- c is Chan’s derived path U, U, D, U, D, D, U, U, U, D, U; regime 1 is the bull state. g equals the filter’s own prediction bit for bit, and the next-up probability lies between 0.498 and 0.615.
- Chan’s rule is long when the next-up probability is above 0.5. With no flat bar it is short exactly where
UpDown(2)is 6, a down bar then an up bar; under this method’s flat rule it is short whereUpDown(2)is 2 or 6, and under his own flat-as-up rule where it is 4 or 6, from bar 2 on, for any p0, wherever the last two changes are finite. - His values are an in-sample fit: a filter using them over that span is an illustration, not a causal indicator.
- Pinned by
TestRecipeMarkovSwitchBernoulliChan; runnable exampleExampleSeries_MarkovSwitchProbUpDown_chan.
(b) Barberis, Shleifer and Vishny’s continuation filter
c := Series{100, 101, 100, 101, 100, 101, 102, 101, 100, 101, 100, 101, 102, 103, 104, 105, 104, 105, 106, 105, 106, 107}
p11, p22, q1, q2, p0 := 0.9, 0.7, 1.0/3, 0.75, 1.0/3
P := c.MarkovSwitchProbContinuation(p11, p22, q1, q2, p0)- The prices start at 100 and step by 1 with the signs of their Table 1, so bar t+1’s change has the sign of their period t’s shock. Regime 1 is their mean-reverting model and regime 2 their trending model; the journal article and the working paper before it swap the letters, so read them by role.
- Bars 0 and 1 have no continuation, so p0 = 1.0/3 makes bar 1 their belief of 0.5 before the first observation, and bar k+1 is their period k: the output reproduces their 21 printed beliefs to two decimals.
- Pinned by
TestRecipeMarkovSwitchBernoulliBSV; runnable exampleExampleSeries_MarkovSwitchProbContinuation_bsv.
The likelihood-ratio Markov-switching filter
MarkovSwitchProbLikelihood(p11, p22, p0...) is the filtered probability of regime 1 of the same two-state chain as MarkovSwitchProb, but its receiver is the per-bar likelihood ratio r = f2/f1 that the caller builds: the density of each bar’s observation under regime 2 divided by its density under regime 1. MarkovSwitchPredictLikelihood is the probability of regime 1 for the next bar. Any emission model with a density or a probability in each regime fits: build its ratio from Series operations, then filter. The stay probabilities and p0 have MarkovSwitchProb’s meanings, and nothing is estimated.
Building the ratio. A ratio of 0 or more, 0 and +Inf included, is an observation; a NaN or negative ratio, -Inf included, is a missing bar that takes the prediction only, while the chain still advances, so the filter steps in bar time. A ratio of 0 is decisive evidence for regime 1 and +Inf for regime 2. Put NaN on every bar where the ratio is undefined: Ratio and Div’s zero rule give 0 there, and the upstream warm-up and invalid-parameter zeros of other methods are 0 too, each read as regime 1 with certainty. Mask an upstream warm-up with SetN before the call, and cut inputs of different lengths to their overlap with Overlap first.
Validate the emission parameters. The ratio carries no parameters, so the method cannot check them, and a bad one gives a confident answer rather than zeros. With a standard deviation sigma1 of 0, Div’s zero rule makes z1 zero and the Gaussian ratio 0, so the output is 1 on every observed bar; with sigma2 of 0 the ratio is +Inf and the output 0. MarkovSwitchProb gives aligned zeros for both. Check that means are finite, standard deviations are above 0 and finite, Bernoulli probabilities are in [0, 1] and a standardised Student t has more than 2 degrees of freedom before building the ratio.
(a) The Gaussian ratio
x := c.Log().Delta().SetN(1, math.NaN())
z1 := x.Sub(mu1).Div(sigma1)
z2 := x.Sub(mu2).Div(sigma2)
R := z1.Sub(z2).Mul(z1.Add(z2)).Mul(0.5).Exp().Mul(sigma1 / sigma2)
prob := R.MarkovSwitchProbLikelihood(p11, p22, p0)- The ratio of two normal densities is exp((z1^2 - z2^2)/2)*sigma1/sigma2; writing the difference of squares as (z1 - z2)(z1 + z2) avoids Inf - Inf, a NaN, where both squares overflow; the product can still overflow, which gives a decisive ratio of 0 or +Inf.
- On this ratio the output equals
MarkovSwitchProbwith the same parameters bit for bit. Masking bar 0 matters: without it,Delta’s 0 at bar 0 is an observation of a flat return, and on AAPL’s 2023 returns with Jansen’s toy set the masked and unmasked outputs differ on 42 of 200 bars (bar 0 is 0.8 against 0.8917). - Pinned by
TestRecipeMarkovSwitchLikelihoodGaussian; runnable exampleExampleSeries_MarkovSwitchProbLikelihood_gaussian.
(b) The Bernoulli ratio and the next observation
r1, r0 := q2/q1, (1-q2)/(1-q1)
R := o.If(func(v float64) bool { return v == 1 }, r1, o.If(func(v float64) bool { return v == 0 }, r0, math.NaN()))
prob := R.MarkovSwitchProbLikelihood(p11, p22, p0)
g := R.MarkovSwitchPredictLikelihood(p11, p22, p0)
next := g.Mul(q1).Add(g.Mul(-1.0).Add(1.0).Mul(q2))
d := closes.Delta()
up := d.GTE(0).Add(d.Mul(0)).SetN(1, math.NaN())- o is a 0/1 code and q_k the probability of a 1 in regime k. Build the ratio with
If, so that a masked or any other code is NaN and reads as missing. The formo.EQ(1.0).Mul(q2 / q1).Add(o.EQ(0.0).Mul((1 - q2) / (1 - q1)))is not a substitute: it gives a decisive ratio of 0 on a masked or non-binary code, and NaN from 0*Inf where q1 or q2 is 0 or 1. - next is the probability that the next code is 1, from the prediction g.
- With Barberis, Shleifer and Vishny’s parameters (p11 = 0.9, p22 = 0.7, q1 = 1/3, q2 = 0.75, p0 = 0.5) on their Table 1 continuations, the output reproduces their 21 printed beliefs to two decimals.
- Chan’s up/down codes count a flat bar as up;
d.Mul(0)keeps a bar whose close is NaN missing, andSetNmasks bar 0. - Pinned by
TestRecipeMarkovSwitchLikelihoodBernoulli; runnable exampleExampleSeries_MarkovSwitchProbLikelihood_bernoulli.
(c) The Student t ratio
s := math.Sqrt((nu - 2) / nu)
u1 := x.Sub(mu1).Div(sigma1 * s)
u2 := x.Sub(mu2).Div(sigma2 * s)
q := u1.Mul(u1).Div(nu).Add(1).Div(u2.Mul(u2).Div(nu).Add(1))
R := q.Mul(q).Mul(q).Mul(sigma1 / sigma2)- A standardised Student t with nu degrees of freedom has scale sigmasqrt((nu-2)/nu), so that sigma is its standard deviation; the ratio is (sigma1/sigma2)(w1/w2)^((nu+1)/2) with w = 1 + u*u/nu, and with nu = 5 the power is a cube, formed by products.
- For another nu,
w1.Div(w2).Pow((nu + 1) / 2).Mul(sigma1 / sigma2)is a tolerance recipe:Powis Go’s power function, not libm’s, so compare it within a relative tolerance (it agrees with the density quotient within 1e-12 at nu = 7), not bit for bit. - Far out in either tail the ratio tends to (sigma2/sigma1)^nu, 243 at sigma1 = 0.01 and sigma2 = 0.03 with nu = 5, so one extreme bar is bounded evidence; where u*u overflows the ratio is NaN and the bar reads as missing.
- Pinned by
TestRecipeMarkovSwitchLikelihoodStudentT; runnable exampleExampleSeries_MarkovSwitchProbLikelihood_studentT.
(d) Daniel, Jagannathan and Kim’s momentum model
m, k = m.Overlap(k)
s := math.Sqrt((nu - 2) / nu)
kp := k.Max(0)
eT := m.Sub(k.Mul(b0T)).Sub(kp.Mul(bpT)).Sub(alphaT).Div(smomT)
eC := m.Sub(k.Mul(b0C)).Sub(kp.Mul(bpC)).Sub(alphaC).Div(smomC)
RN := eT.Sub(eC).Mul(eT.Add(eC)).Mul(0.5).Exp().Mul(smomT / smomC)
uT := k.Sub(muT).Div(smktT * s)
uC := k.Sub(muC).Div(smktC * s)
q := uT.Mul(uT).Div(nu).Add(1).Div(uC.Mul(uC).Div(nu).Add(1))
R := RN.Mul(q.Mul(q).Mul(q).Mul(smktT / smktC))
PT := R.MarkovSwitchProbLikelihood(p11, p22)
a, L := 1-p22, (p11+p22)-1
predT := PT.Mul(L).Add(a).Clamp(0, 1)
calm := PT.Mul(-1.0).Add(1.0)
pred := R.MarkovSwitchPredictLikelihood(p11, p22)- m is the monthly momentum return and k the market’s excess return. In each regime the momentum return is a normal regression on k and its positive part, and k a standardised Student t with 5 degrees of freedom; the ratio of the calm regime 2 to the turbulent regime 1 multiplies the two factors. The residuals subtract the slopes first and the intercept last, in this order.
- PT is the probability that the month is turbulent; predT, the turbulent probability for the next month, equals
MarkovSwitchPredictLikelihoodbit for bit with a and L run-time values (written as constant expressions they fold exactly and differ); calm is the regime-2 view. - Cut m and k to their overlap first. Series operations pair two inputs from their most recent bars and give 0 on the receiver’s bars before the overlap: on 360 simulated months, a market series 12 months shorter than m gives R = 0 and PT = 1 on the first 12 months, and the later months move by up to 0.75. Masking those months with
R.SetN(12, math.NaN())gives the same later months on that data, which does not hold in general. - The regression on the market return and its positive part that Daniel, Jagannathan and Kim fit within each regime is “Hinge beta (Henriksson and Merton)” in the “Relative: Regression and Spread” category, cross-referenced here only.
- Pinned by
TestRecipeMarkovSwitchLikelihoodDJK; runnable exampleExampleSeries_MarkovSwitchProbLikelihood_djk.
The preset below is documentation, not a default. It is Daniel, Jagannathan and Kim’s maximum-likelihood fit (working paper, 2019, Table 9) of monthly momentum and market excess returns, in decimals per month (the paper’s percentages divided by 100), on January 1927 to December 2017. A filter using it is an in-sample illustration over that span, not a causal indicator, and no source gives out-of-sample evidence of an edge for it with fixed parameters; the doc comment of MarkovSwitchProbLikelihood lists the paper’s other caveats.
| Monthly, decimals per month | Turbulent, regime 1 | Calm, regime 2 |
|---|---|---|
| stay probability | p11 = 0.95 | p22 = 0.99 |
| momentum intercept alpha | 0.0362 | 0.0186 |
| market slope b0 | -0.40 | 0.32 |
| slope on the market’s positive part bp | -1.07 | -0.41 |
| momentum residual sigma smom | 0.1068 | 0.0442 |
| market mean mu | -0.0050 | 0.0113 |
| market standard deviation smkt | 0.0833 | 0.0401 |
With these stay probabilities a = 0.010000000000000009 and L = 0.94, the default p0 is 0.16666666666666666, and the one-step prediction is at most 0.95.
(e) The market-only variant
F := q.Mul(q).Mul(q).Mul(smktT / smktC)
R := RN.Mul(F)
RM := m.If(func(v float64) bool { return v == v }, R, F)- A month with the momentum return missing and the market present makes R NaN, so the whole month is dropped. Selecting the market factor F alone on such months keeps the market’s evidence; it is a documented alternative, not the default.
- Pinned by
TestRecipeMarkovSwitchLikelihoodMarketOnly; runnable exampleExampleSeries_MarkovSwitchProbLikelihood_marketOnly.
(f) The predictive log score
lnf1 := z1.Mul(z1).Mul(-0.5).Sub(math.Log(sigma1) + 0.5*math.Log(2*math.Pi))
r := z1.Sub(z2).Mul(z1.Add(z2)).Mul(0.5).Exp().Mul(sigma1 / sigma2)
pred := r.MarkovSwitchPredictLikelihood(p11, p22, p0).Shift(1).SetN(1, p0)
ls := lnf1.Add(pred.Add(pred.Mul(-1.0).Add(1.0).Mul(r)).Log())- ls_t = ln f1 + ln(pred + (1 - pred)*r) is the log density of bar t’s observation under the model’s forecast from bar t-1. The log density ln f1 of regime 1 is the caller’s, here the normal one; with it, the same line scores any emission model whose ratio is r.
- Pinned by
TestRecipeMarkovSwitchLikelihoodLogScore; runnable exampleExampleSeries_MarkovSwitchProbLikelihood_logScore.
(g) The prediction
pred := R.MarkovSwitchPredictLikelihood(p11, p22, p0)
recipe := prob.Mul(L).Add(a).Clamp(0, 1)
gauss := x.MarkovSwitchPredict(p11, p22, mu1, sigma1, mu2, sigma2, p0)- At bar t the output is the probability of regime 1 for bar t+1, so its value at bar t-1 is the forecast a decision at the close of bar t-1 acts on. It equals the recipe on the filtered output bit for bit, and on the Gaussian ratio
MarkovSwitchPredict. - Pinned by
TestRecipeMarkovSwitchLikelihoodPredict; runnable exampleExampleSeries_MarkovSwitchPredictLikelihood.
Runs test
RunsZ and RunsZVince split each of the last n changes of c, which span n+1 prices, into up and not-up, count the runs of equal bits and return the Wald-Wolfowitz z-score of the number of runs given the number of bits of each kind. A change is up when it exceeds the tolerance, a percentage of the previous price as in UpDown, and a flat change is not-up. The z-score is negative when the window is streakier than chance (fewer runs) and positive when it alternates (more runs), the opposite sign to MarkovDirPhi; at tolerance 0, RunsZ(n) and MarkovDirPhi(n-1) read the same n bits. RunsZVince adds half a run to the numerator, the form that MultiCharts and DeAmicis-Roberts report, so it leans towards alternation; the recipes below use RunsZ.
Warm-up, degenerate windows and the footprint. Bars 0 to n-1 read +0, not NaN, and so does a window with bits of one kind only, or with n at most 2, where the statistic is undefined: there 0 means undefined, not random, and the strongest trends read it. A NaN or infinite price at bar p gives NaN on bars max(p, n) to p+n.
The p-value. Under independence, given the counts of each kind, z is close to a standard normal variable, and its two-sided p-value is erfc(|z|/sqrt(2)). Compute it as recipe “(a) The p-value of phi” under “Testing a transition table for dependence” does, with |z|/sqrt(2) as the argument of Erfc in place of |phi|*sqrt(n/2).
The evidence. Most published uses compute one z over a whole trade history or backtest, from winning and losing trades, and choose and judge a money-management rule on the same trades. Bryant’s rolling window over the last n trades is the causal reading, but he tests no rule on it, and no source shows a trading edge. Read at every bar, the test is repeated on overlapping windows: under independence with equal chances at n = 30, |z| exceeds 1.96 on 4.8 % of bars, and those bars come in clusters.
(a) Bryant’s scale and the confidence limit
z := c.RunsZ(n)
display := z.Div(-math.Sqrt2).Erf().Add(0.0)
confidence := z.Abs().Div(math.Sqrt2).Erf()- Use: Bryant shows the z-score on a -1 to +1 scale, erf(-z/sqrt(2)), positive when wins and losses cluster, so its sign is the reverse of
RunsZ’s; the confidence limit erf(|z|/sqrt(2)) is the chance that a standard normal variable lies within |z| of 0, one minus the two-sided p-value. On Bryant’s 15 trades (7 wins, 8 runs, n = 15) z is -0.2513 and the display and the confidence limit 0.1984; on Sherry’s 63 signs (n = 63) z is 0.7432, the display -0.5426 and the confidence limit 0.5426. The warm-up’s +0 divided by -sqrt(2) is -0, and.Add(0.0)makes the display +0 there. - First valid index: n; the minimum length is n+1.
- Pinned by
TestRecipeRunsZDisplay; runnable exampleExampleSeries_RunsZ_display.
(b) The minimum-count guard
up := c.UpDownSum(1).GT(0.0)
n1 := up.Sum(n)
guarded := z.Mul(n1.GTE(float64(m))).Mul(n1.LTE(float64(n - m))).Add(0.0)- Use: the normal reading overstates significance when one kind is rare: a single not-up bit at the edge of a window of 30 reads -3.74, although the chance of two runs or fewer, given that bit, is 2/30. The guard keeps z only when the window holds at least m bits of each kind, and reads +0 elsewhere; m = 5 is the minimum Bryant asks of his proportion test.
up.Sum(n)is the number of up bits ofRunsZ’s window wherever its prices are finite; with a tolerance, pass the same one toUpDownSumand toRunsZ. A negative z times 0 is -0, which.Add(0.0)makes +0. On a walk of one down change and then 30 up changes, with n = 30 and m = 5, bar 30 reads -3.742 unguarded and 0 guarded; Bryant’s window keeps its z at m = 5. - First valid index: n, as for (a); before it z is +0, so the guard is +0 whatever the partial sums of
Sumread. - Pinned by
TestRecipeRunsZGuard; runnable exampleExampleSeries_RunsZ_guard.
First valid index of the runs-test stages
| Stage | First valid index f | Before f |
|---|---|---|
RunsZ(n, tol), RunsZVince(n, tol) | n | zeros |
UpDownSum(1, tol) | 1 | zeros |
Sum(n) | n - 1 | partial sums |
GT, GTE, LTE, Mul, Div, Abs, Erf, Add | 0 | nothing |
Empirical spell durations
StateHazard, StateSurvival, StateResidualLife and StateAtRisk compare the age of the current spell of a state series with the lengths of earlier finished spells of the same value, without a model: the hazard is the share of the spells that reached the current age and ended there, the survival the share of all counted spells that lasted longer, the residual life the mean number of further bars, and the at-risk count the support behind them. The window is anchored at the first bar of the current spell, and every n of at least 2 that is at or above the length counts every earlier spell.
(a) The share that reached the current age
surv := z.StateSurvival(n)
first := func(a float64) bool { return a == 1 }
reached := age.If(first, z.StateAtRisk(n).GT(0.0), surv.Shift(1)).Add(surv.Mul(0.0))- Use:
ageis the age of the current spell, fromStateAge.StateSurvivalis strict: it counts the spells longer than the current age. The share that reached the age, ties included, is the survival of the bar before, and on a spell’s first bar it is 1 where any spell is counted. A table of the kind “30 of 88 corrections lasted at least 58 days” isreached;survreads 29 of 88 there. - First valid index: 0.
reachedis NaN whereversurvis. - Anchor: E:
reachedequalsStateAtRiskdivided by the size of the counted set, formed from the same whole numbers. - Pinned by
TestRecipeStateDuration_reached; runnable exampleExampleSeries_StateSurvival_reached.
(b) Recurrence of an event
flag := x.EQ(3.0).MaskNonFinite(x)
hazard := flag.StateHazard(n)
atRisk := flag.StateAtRisk(n)- Use: on the bars between two events the state is 0 and its age is the time since the last event, so
hazardis the share of earlier quiet stretches that ended at this age, andatRisksays how many reached it.MaskNonFinitekeeps a missing symbol missing; the comparison alone would read it as 0 and lengthen the stretch. - Window:
n := 1 << 30counts every earlier stretch; a smaller n keeps those whose length became known within n bars of the stretch’s start. - Read with the support: a hazard of 0 with a small
atRiskis want of evidence; mask withatRiskof 5 or more. - Pinned by
TestRecipeStateDuration_sherryRecurrence; runnable exampleExampleSeries_StateHazard_sherryRecurrence.
(c) A hazard pooled over several ages
ar := z.StateAtRisk(n)
old := func(a float64) bool { return a > float64(b) }
binned := age.If(old, ar.Shift(b).Sub(ar).Ratio(ar.Shift(b)), 0.0).Add(ar.Mul(0.0))- Use:
ageis the age of the current spell, fromStateAge. At single ages the support is thin and the hazard jumps between 0 and large values.binnedis the share of the spells that reached age a-b and did not reach age a, a hazard over b ages. Within a spell the at-risk count of b bars earlier is the count at age a-b, because the counted set does not change during a spell. - Select, do not multiply: the bars of age b or less are set to 0 with
If; a mask by multiplication would print a negative zero there.Ratioreads a missing count as 0, so the last term puts the NaN bars back. - Pinned by
TestRecipeStateDuration_binned; runnable exampleExampleSeries_StateHazard_binned.
(d) Masking a state builder’s warm-up
raw := c.GT(c.Average(3))
masked := raw.SetN(2, math.NaN())- Use: a state built from an indicator carries the indicator’s warm-up: here the average is not valid on its first two bars, and
rawreads 0 there whatever the prices did. Those bars look like a real first spell, and the spell after them is then counted although its start was not seen. Setting the warm-up to NaN makes the first real spell the first spell of the data, which is left out of every set. - First valid index: 0 for both; on
maskedthe four methods read NaN on the first two bars and 0 over the first spell. - Pinned by
TestRecipeStateDuration_maskedBuilder; runnable exampleExampleSeries_StateAtRisk_maskedBuilder.
Significance of a state’s up rate
StateUpZScore, StateUpZScoreFixed and StateUpChiSquareYates ask whether the current state has been followed by an up bar more or less often than chance over the trailing n bars. At bar t the anchors are the n bars j from t-n to t-1; an anchor is up when c[j+1] exceeds c[j] by more than the tolerance, a percentage as in UpDown, and m and u count the anchors in the current bar’s state and the up ones among them. StateUpZScore tests u against the window’s own up rate, U/n with U the window’s up anchors (Haberman’s adjusted residual); StateUpZScoreFixed tests it against an up probability p0 fixed in advance (the binomial z); and StateUpChiSquareYates is Merrill’s Yates-corrected chi-square against p0, clamped at 0. The state is right-aligned with the receiver at the most recent bar.
Warm-up, unseen states and masks. The bars before n read 0, and so does a state the window has not seen (m = 0): read StateCount(state, n, 1) beside the statistic, which reads 0 there. A builder’s warm-up values are valid codes (the first k bars of UpDown(k) are 0), so mask them with SetN; a mask of k bars makes bars n to n+k-1 NaN, and bar n+k is the first numeric one.
The evidence. Merrill’s weekday and price-pattern tables, Weiderman’s coin tosses and Sherry’s soymeal days are whole-sample tests. The methods recast them on a rolling, causal window; with the window as long as the table they read the table’s own counts, which the recipes below set beside Merrill’s printed figures, and no source shows that filtering on them improves trading. Read at every bar, the test is repeated, so a nominal 5 % signal fires by chance on many bars.
The Examples realise Merrill’s day-of-week table of 1952 to 1983: one anchor for each of its 7,912 days on a walk of +1 and -1 steps, each weekday’s rising days first, the weekday code 1 to 5 as the state, and one bar more whose code selects the weekday read; n = 7,912, so the last bar’s window is the whole table.
(a) Merrill’s one-sample z
z := c.StateUpZScore(state, n)
m := c.StateCount(state, n, 1)
oneSample := z.Mul(m.Div(float64(n)).Mul(-1.0).Add(1.0).Sqrt())- Use: Merrill tests each weekday’s rising share against the table’s own, 52.1 %, as a one-sample proportion, z*sqrt(1 - m/n): it treats the table’s share as a known rate, although the weekday’s own days are part of it, so it is smaller in magnitude than the pooled z and so conservative. Monday gives -7.3996 pooled and -6.6437 one-sample over 1,534 days, and Friday 4.9519 and 4.4292 over 1,582.
- First valid index: n, the last bar here.
- Anchor:
oneSampleequals (un - mU)/sqrt(mU(n-U)) within 1e-12 wherever m and U are neither 0 nor n. - Pinned by
TestRecipeStateUpZScoreMerrill; runnable exampleExampleSeries_StateUpZScore_merrillOneSample.
(b) Merrill’s printed chi-square
total := c.StateCount(state, n, 1)
rising := c.StateUpProb(state, n, 1).Mul(total).Round()
yates := c.StateUpChiSquareYates(state, n, 0.521)
er := math.Round(0.521 * total[n])
x := math.Abs(rising[n]-er) - 0.5
printed := math.Floor((x*x/er+x*x/(total[n]-er))*10) / 10- Use: Merrill’s table prints (D-0.5)^2/Er + (D-0.5)^2/Ed with D = |R - Er|, his expected rising days Er = 0.521T rounded to a whole day and Ed = T - Er, truncated to one decimal: 43.8, 1.6, 6.1, 0.7 and 19.3 from Monday to Friday (rounding would print 0.8 and 19.4 for Thursday and Friday). The method keeps E1 = 0.521m and E2 = m*(1-0.521) unrounded and reads 43.95, 1.65, 6.10, 0.74 and 19.29; both forms exceed 3.84, the 5 % point with one degree of freedom, on Monday, Wednesday and Friday. His form has no clamp, so it stays positive as D falls below 0.5, where the method reads 0. The 52.1 % is the whole table’s rising share, so a rolling use of it looks ahead: take p0 from data that ends before the series starts.
- First valid index: n, as for (a).
- Pinned by
TestRecipeStateUpZScoreMerrill; runnable exampleExampleSeries_StateUpChiSquareYates_merrillLiteral.
First valid index of the significance stages
A state masked for its first k bars makes the three methods NaN from bar n to bar n+k-1, after the zeros.
| Stage | First valid index f | Before f |
|---|---|---|
StateUpZScore(state, n), StateUpZScoreFixed(state, n, p0), StateUpChiSquareYates(state, n, p0) | n | zeros |
StateCount(state, n, h), StateUpProb(state, n, h, tol) | n + h - 1 | zeros |
UpDown(k, tol) | k | zeros |
Mul, Div, Add, Sqrt, Round | 0 | nothing |
Hurst Exponent
Hurst
func (s Series) Hurst(n int) Series
Hurst estimates the Hurst exponent from the rescaled range (R/S) of each trailing window of n values.
For each window it takes the deviations of the n values from the window mean and forms their cumulative sums. R is the range of those cumulative sums (maximum minus minimum), S is the population standard deviation of the window (divisor n, not n−1), and the result is H = ln(R / (S·√(π/2))) / ln n. Indices 0 to n−2 are 0, as are windows where S is 0 or R/S is not a positive number (a flat window, for example, or one containing a NaN or an infinity), and every index is 0 when n <= 1, n > len(s) or len(s) <= 1.
A window whose n values are all equal and finite gives exactly 0, whatever the rounding in its mean: the test is exact equality (==) with the latest value, never a tolerance, so -0 and +0 count as equal, and a window holding a NaN or an infinity is never flat. A window whose values differ by one ulp, or a genuine walk at a tiny magnitude, is not flat and is computed as above. Releases before this change gave about 0.86 to 0.94 on a flat window at most price levels (n = 10 to 50): the computed mean of ten copies of 0.1 is just below 0.1, so every deviation was the same tiny number and R/S came out near n−1.
The factor √(π/2) is the large-sample (Feller/Hurst) constant: for independent data, E[R/S] ≈ √(nπ/2) as n grows. It is not an Anis-Lloyd correction; HurstCorrected uses Anis and Lloyd’s exact expected value instead.
This is a single-scale estimate at window n only. The classical method computes R/S at several window sizes and takes H as the slope of the regression of log(R/S) on log(n); that regression is not provided.
Because the large-sample constant overstates E[R/S] at small n, Hurst is biased low on independent data: in simulation, white noise gives a mean H of about 0.373 at n = 10, 0.427 at n = 20, 0.461 at n = 50, 0.475 at n = 100 and 0.482 at n = 200, where 0.5 is expected. Use HurstCorrected for an estimate centred near 0.5.
R/S analysis is normally applied to increments rather than to levels: for prices, apply Hurst to returns, not to the prices themselves.
HurstCorrected
func (s Series) HurstCorrected(n int) Series
HurstCorrected estimates the Hurst exponent like Hurst but compares R/S with its exact expected value under independence (Anis and Lloyd, 1976) rather than the large-sample constant, which removes most of Hurst’s downward bias on independent data.
For each trailing window of n values, R (the range of the cumulative deviations from the window mean) and S (the population standard deviation, divisor n, as Hurst uses) are computed exactly as in Hurst, and the result is H = 0.5 + ln((R/S) / E(n)) / ln n, where E(n) = Γ((n−1)/2) / (√π·Γ(n/2)) · Σ √((n−r)/r), summed over r = 1 to n−1, is Anis and Lloyd’s (1976) exact expected R/S for independent normal values, as given by Peters, Fractal Market Analysis (1994), eq. 5.4. The gamma ratio is computed by its recurrence in steps of two, not from the gamma function (which overflows near n = 343), so E(n) is finite for every n. E(n) is computed once per call.
Where both are non-zero, HurstCorrected(n) − Hurst(n) at the same index equals, to rounding, the constant 0.5 + (ln √(π/2) − ln E(n)) / ln n: about 0.117574 at n = 10, 0.065156 at n = 20, 0.032202 at n = 50 and 0.012129 at n = 200.
On white noise HurstCorrected averages about 0.491 at n = 10, rising to 0.495 at n = 200. The small negative bias that remains comes from centring R/S rather than ln(R/S): by Jensen’s inequality, the mean of ln(R/S) is below ln E(n).
Peters’s Table A2.1 prints E(n)·(n − 0.5)/n: the factor (n − 0.5)/n is his empirical correction for the sample standard deviation, so the table’s values are E(n) times that factor, not E(n) itself.
The flat-window rule is Hurst’s too: a window whose n values are all equal and finite gives exactly 0, whatever the rounding in its mean. Releases before this change gave about 0.97 on such a window at most price levels (n = 10 to 50), for example ten copies of 0.1.
Guards, warm-up and zero cases are those of Hurst: indices 0 to n−2 are 0, as are windows where S is 0 or R/S is not a positive number, and every index is 0 when n <= 1, n > len(s) or len(s) <= 1. As with Hurst, this is a single-scale estimate at window n only, and R/S analysis is normally applied to increments (returns, for prices) rather than to levels.
Structural Breaks
DickeyFuller
func (s Series) DickeyFuller(n int) Series
DickeyFuller returns the rolling Dickey-Fuller t-statistic of the lagged level in a regression of each change on a constant and the previous value over the last n lag pairs.
At bar t the n lag pairs are the regression rows i = t-n+1 .. t. Row i regresses the change s[i] - s[i-1] on a constant and the lagged level s[i-1], so a window of n pairs reads the n + 1 values s[t-n .. t]. With b the coefficient of the lagged level, Sxx the centred sum of squares of the lagged level and SSR the residual sum of squares, the statistic is t = b sqrt((n-2) Sxx/SSR), the multiplicative form of b/se with se = sqrt(SSR/(n-2)/Sxx). The statistic has n - 2 degrees of freedom: n rows less two coefficients. The coefficient b is OUTheta(n), bit for bit, and b + 1 is the slope of the level on its lag, so the statistic is also the t-statistic of that slope tested against 1. Its sign is the sign of OUTheta(n) wherever neither is 0. On the residuals of a pair’s regression window it is the second step of EngleGranger.
DickeyFuller is built on the shared co-moment kernel behind OUTheta and SScore, with the residuals formed explicitly rather than by subtracting co-moments, which cancels near a perfect fit. The source is Dickey and Fuller (1979), Journal of the American Statistical Association 74, pages 427 to 431. The value at bar t is, in exact arithmetic, the test statistic of statsmodels adfuller(window, maxlag=0, regression=‘c’, autolag=None) on the n + 1 values s[t-n .. t]; the two agree to rounding on ordinary windows, while statsmodels, which fits the uncentred design, loses digits where the level is large against the moves (a level of 1e9 with unit moves) and this method does not. There are no lagged differences and no trend: the augmented and trend forms are not built. AFML picks the order d of FracDiff as the smallest d whose output passes its ADF test, which has one lagged difference, so this method does not reproduce that choice.
Pass log prices, c.Log().DickeyFuller(n). On raw prices a rejection of the unit root would imply stationary prices of finite variance, so return volatility would have to shrink as prices rise, while on log prices a rescaling of the price only shifts the series, which the constant absorbs (AFML, section 17.4.2.1, on raw and log prices). The method takes no logarithm and uses the receiver as given. Levels are legitimate input too (a spread, a yield): there is then no dependence on a logarithm and no NaN for non-positive values.
The warm-up reads 0, not NaN: bars 0 to n-1 are 0 and the first valid index is n. Because 0 is also a legitimate value, mask the warm-up where it matters with DickeyFuller(n).SetN(n, math.NaN()). An n below 3 (three pairs leave one residual degree of freedom) or of at least len(s) gives len(s) zeros, and the minimum length of a series with a valid bar is n + 1.
A NaN or an infinity at bar p gives NaN from the later of p and n to the earlier of p+n and len(s)-1, exactly the windows s[t-n .. t] that hold it; later bars recover. The method forms no difference of input values, so a finite pair whose difference would overflow is not a NaN case. The kernel scales each window by a power of two first, so there is no limit on the magnitudes, upper or lower, but there is one on the dynamic range of a window s[t-n .. t], the ratio of the largest to the smallest nonzero difference between two of its values: finite inputs give finite, accurate outputs while that ratio stays below about 2^1000 (about 1e301). Beyond it the slope, rebuilt from the kernel’s scaled units, can overflow while the power of two that scales the root underflows, with no special rule, so the result can be NaN or an infinity: the series 0, 2^-700, 0, 2^400 gives NaN from DickeyFuller(3) at bar 3, where the statistic is about -0.577.
A window whose residual sum of squares is at most 1e-24 times the centred sum of squares of the levels it regresses (a perfect fit, or flat levels) gives 0, and so does a flat lagged level. Just outside that guard the value can be huge, far beyond any critical value, which marks a nearly deterministic window rather than a signal: a path converging geometrically to a level is a perfect fit up to the rounding of the stored values. While the largest move of a window exceeds about 1e6 times that rounding, the statistic here is very large, above 1e5, while SupADF gives 0; below about 1e5 times that rounding, SupADF gives nearly the same values as this method, and they shrink with the moves to ordinary sizes as the moves reach the rounding, where both methods read the noise.
The value at bar t reads only s[t-n .. t], so the method is causal, does not repaint and does not depend on where the history starts: a suffix s[k:] gives at bar t-k the full series’ value at bar t, for every t >= k + n, and a prefix gives the first values of the full series’ result, bit for bit. Scaling the series by a power of two, 2^k, for every k that keeps the values normal and finite, or negating it, leaves the result unchanged bit for bit (negation leaves every ADF-type statistic with a constant unchanged), and adding a constant changes it only by rounding. Inside SupADF’s narrower domain, SupADF(n, n) agrees with it to rounding, not bit for bit, except near a perfect fit, where the two guards differ. The bits are the same on every platform.
The period-4 pattern +1, +1, -1, -1 (repeating, in any phase, also scaled by a power of two) with n a multiple of 4 gives -sqrt(n-2) exactly at every valid bar, because the lagged level and the level both have mean 0 over whole periods, so their co-moment is 0 and b = -1. The powers of two s[i] = 2^-i are a perfect fit and give 0, as do a flat series and a strictly alternating two-price series.
In the bubble literature (see SupADF) the test is right-tailed: large positive values reject the unit root in favour of explosiveness. In the classical unit-root test the alternative is stationarity and the test is left-tailed: large negative values reject. Critical values depend on n, and none is quoted here.
The cost is O(n) per valid bar, one kernel fit and one residual pass. A call makes two allocations, the result and the kernel, for every length with a valid bar; an invalid n makes one, the result, and an empty series none. The result is a new series; the method reads s only, so concurrent calls on a shared input are safe.
Verification: two clean-room references implement the contract in testdata/gle257-wp32 on its 27 input series. A Python reference computes each window’s statistic exactly, in rational arithmetic with the square root to 50 digits (mpmath), and gives an error bound per bar; a Julia reference fits each window by direct least squares in binary64. The Julia fit and this method both lie within the Python bound at every compared bar (the knife edges of the guard and the bars beyond the domain are not compared), and match its zeros and NaN bars exactly. The identity with OUTheta, the period-4 anchor and the scaling and negation identities hold as stated, and the outputs are the same bytes natively (arm64) and as amd64 code. The adfuller of statsmodels is a cross-check only: it agrees to rounding on ordinary windows, but its uncentred design loses digits where the level is large against the moves.
SupADF
func (s Series) SupADF(minPairs, maxPairs int) Series
SupADF returns, at each bar, the largest Dickey-Fuller t-statistic over the windows of minPairs to maxPairs lag pairs that end at that bar, the bounded backward supremum ADF sequence.
A window of m lag pairs ending at bar t reads the m + 1 values s[t-m .. t] and has the statistic of DickeyFuller, t = b sqrt((m-2) Sxx/SSR), with b the coefficient of the lagged level in the regression of the change on a constant and the lagged level. Each window has m - 2 degrees of freedom: m rows less two coefficients. SupADF takes the largest of these statistics over m = minPairs .. maxPairs; the windows are visited from the shortest, the first defined value is kept on a tie, and the winning window is not returned (no argmax). A window with a flat lagged level or a perfect fit is undefined and is skipped, and the bar reads 0 when no window is defined. When minPairs and maxPairs both equal n there is one window, and inside the domain below SupADF agrees with DickeyFuller(n) to rounding, not bit for bit, except near a perfect fit, because the supremum accumulates each window in O(1) per row and its guard differs from that of DickeyFuller.
In the terms of Phillips, Shi and Yu (2015), PSY below, this is the backward SADF (BSADF) sequence, bounded to the last maxPairs pairs. It is AFML’s SADF_t (Advances in Financial Machine Learning, chapter 17, section 17.4.2), which follows Phillips, Wu and Yu (2011), PWY below, International Economic Review 52(1), with the start points t0 running from t - maxPairs to t - minPairs as price indices. AFML’s get_bsadf returns the key ‘gsadf’ for what PSY call the BSADF sequence. PWY’s SADF (a fixed start and an expanding end) and PSY’s GSADF (the supremum of BSADF over the end points) depend on where the history starts and are not methods. A rolling GSADF is the recipe SupADF(a, b).Highest(k), valid from bar b + k - 1; Highest carries a NaN for k bars, so a NaN of SupADF at bar j makes the recipe NaN from bar j to j+k-1.
minPairs and maxPairs count regression rows (lag pairs), so a window of m pairs uses m + 1 values. This is the unit of exuber’s minw and of AFML’s minSL at lag 0; psymonitor’s swindow0 counts prices, one more.
Pass log prices, c.Log().SupADF(minPairs, maxPairs). On raw prices a rejection of the unit root would imply stationary prices of finite variance, so return volatility would have to shrink as prices rise, while on log prices a rescaling of the price only shifts the series, which the constant absorbs (AFML, section 17.4.2.1, on raw and log prices). The method takes no logarithm and uses the receiver as given; levels (a spread, a yield) are legitimate input.
The statistic is right-tailed: large positive values mark explosive behaviour. It is unchanged by negation, so it responds to explosive falls as to rises.
A minPairs below 3, a maxPairs below minPairs, or a maxPairs of at least len(s) gives len(s) zeros; minPairs equal to maxPairs is valid and gives one window. The minimum length of a series with a valid bar is maxPairs + 1.
The warm-up reads 0, not NaN: bars 0 to maxPairs-1 are 0 and the first valid index is maxPairs. A partial supremum over the early bars, from minPairs, would depend on where the history starts and is not given. Because 0 is also a legitimate value, mask the warm-up where it matters with SupADF(minPairs, maxPairs).SetN(maxPairs, math.NaN()).
Row i of the regression is bad when s[i] - s[i-1] is not finite, which covers a non-finite s[i-1] or s[i] and a finite pair whose difference overflows. A bad row among the rows t-maxPairs+1 .. t gives NaN at bar t, so a shorter clean window does not win past a NaN. A non-finite s[p] makes rows p and p+1 bad and gives NaN from the later of p and maxPairs to the earlier of p+maxPairs and len(s)-1. A finite pair whose difference overflows makes row p bad only, with NaN from the later of p and maxPairs to the earlier of p+maxPairs-1 and len(s)-1. The bars p-1 and p+maxPairs, which read one huge value without a bad row, lie beyond the domain below and can be NaN or finite. Two adjacent non-finite values, at p and p+1, make three rows bad, with NaN up to the earlier of p+1+maxPairs and len(s)-1. Warm-up bars stay 0 even where the input is bad, and bars whose windows do not read the value are unchanged.
Finite inputs whose magnitudes (and so window ranges) stay below about 1e150 give finite outputs; beyond that the arithmetic decides, with no special rule. SupADF also has a lower end: it multiplies unscaled differences, so where some value of s[t-maxPairs+1 .. t] differs from s[t-maxPairs] by a nonzero amount below about 2^-500 its accuracy is not assured. DickeyFuller scales each window by a power of two first and does not need that limit. SupADF is also accurate only while the dynamic range of each window s[t-maxPairs .. t], the ratio of the largest to the smallest nonzero difference between two of its values, stays below about 2^500 (about 3e150), against about 2^1000 for DickeyFuller. Beyond it the ratio Sxx/SSR under the square root becomes subnormal and then 0, again with no special rule, so a bar can read 0 or a wrong value: the series 0, 2^-300, 0, 2^300 gives 0 from SupADF(3, 3) at bar 3, where the statistic is about -0.577.
A window is undefined when its lagged level is flat or when its residual sum of squares, formed as Sdd - b Sxd, is at most 1e-10 times Sdd, the centred sum of squares of the changes (a perfect fit, a flat change, or a negative value from rounding). This is far looser than the 1e-24 of DickeyFuller, whose guard is relative to the levels and uses explicit residuals. The subtraction form has a rounding floor that grows with the window length and lies far above that of explicit residuals, so a threshold as tight as 1e-24 would let a perfect fit through as an enormous statistic, and a strictly alternating two-price window (a bid-ask bounce on illiquid ticks) is exactly such a fit. The two guards differ, so a window can lie inside one and outside the other.
The windows at bar t share one anchor, the lagged level s[t-1] of the last row, and the rows are added from t backwards, one Welford step each, so after m rows the accumulator holds the window of the m pairs ending at t. The value of a window therefore does not depend on minPairs, maxPairs or the bars before s[t-maxPairs], and these identities hold bit for bit. For any j from minPairs to maxPairs-1, SupADF(minPairs, maxPairs) at a bar t >= maxPairs is the larger of SupADF(minPairs, j) and SupADF(j+1, maxPairs), and NaN where either is NaN, provided each part has at least one defined window. Where the narrower range has a defined window, the value does not fall as maxPairs grows and does not rise as minPairs grows. A part in which every window is undefined (a stretch of strictly alternating prices, say) reads 0 and contributes nothing to the whole, so a longer range that reaches back past the stretch can be negative where the shorter one reads 0.
The value at bar t reads only s[t-maxPairs .. t]. It is window-local and start-invariant: a suffix s[k:] gives at bar t-k the full series’ value at bar t, for every t >= k + maxPairs; a prefix gives the first values of the full series’ result; and the method is causal and does not repaint. Scaling the series by a power of two, 2^k, for every k that keeps the values and the products of their differences normal and finite (the domain above), or negating it, leaves the result unchanged bit for bit, and adding a constant changes it only by rounding. The period-4 pattern +1, +1, -1, -1, with minPairs and maxPairs both equal to a multiple n of 4, gives values within 1e-12 of -sqrt(n-2). The powers of two s[i] = 2^-i, a flat series and a strictly alternating two-price series have only undefined or perfect-fit windows, which SupADF skips, so they give 0.
No critical values are shipped: they depend on minPairs, maxPairs and the null. To simulate them, generate many series, each the cumulative sum of maxPairs + 1 independent N(0, 1) draws (the shortest series with a valid bar; the starting level does not matter, because the constant absorbs it), take the last value of SupADF(minPairs, maxPairs) for each series and read the percentile you need, for example the 95th. The Monte Carlo critical values of exuber and the bootstrap of psymonitor are the published tools. For minPairs, the minimum-window rule of Phillips, Shi and Yu, floor((0.01 + 1.8/sqrt(T))*T) with T the sample length, is guidance: T = 252 gives 31, so SupADF(31, 252) on daily log prices (exuber’s psy_minw computes the same rule).
The cost is O(maxPairs) per bar: maxPairs accumulator steps and up to maxPairs - minPairs + 1 square roots, which is 252 steps a bar at maxPairs = 252, instead of a fresh fit of every window. A call allocates only the result, a new series; the method reads s only, so concurrent calls on a shared input are safe. The bits are the same on every platform, because every product that meets an addition is rounded on its own. Not built: lagged differences (lag 0 only), trends, the QADF and CADF views, and PWY’s SADF and the GSADF as methods.
Verification: the two clean-room references of DickeyFuller (testdata/gle257-wp32) cover SupADF too. The Julia reference also transcribes line by line the binary64 program the contract pins for SupADF, and this method equals that transcription at every cell, bit for bit, NaN matching NaN. The transcription, the Julia direct least squares and this method all lie within the Python reference’s error bound at every compared bar (the knife edges of the guard and the bars beyond the domain at either end are not compared). The decomposition, the period-4 anchor and the scaling and negation identities hold as stated, and the outputs are the same bytes natively (arm64) and as amd64 code.