Series Functions Reference

Series Functions Reference

The nseries.Series type provides over 500 chained operations for technical analysis, statistical computation, and data transformation. All functions operate on Series values and return new Series, enabling fluent method chaining:

rs.Close(0).Average(20).Shift(1).CrossesAbove(rs.Close(0).Average(50))

The complete function reference below is organised by category. Each entry shows the function signature and a description of its behaviour.

Core

Append

func (s Series) Append(s2 Series) Series

Append appends a series.

At

func (s Series) At(n int) Series

At is an alias for Lookback

Bool

func (s Series) Bool(lookback ...int) bool

Bool is an alias for ValueBool

Copy

func (s Series) Copy() Series

Copy makes a copy of a series.

LookBack

func (s Series) LookBack(n int) Series

LookBack removes the last n values from the series.

New

func New(in []float64) Series

New creates a new Series from a slice of float64 values.

Ratio

func (s Series) Ratio(s2 Series) Series

Ratio returns a series where the specified series s is divided by the series s2. If the length of s and s2 are not the same, a series of length s is returned with all values set to zero.

SAverage

func (s Series) SAverage(ss ...Series) Series

SAverage returns a series where the specified series is averaged with an abritrary number of provided series. It relies on all series being the same length.

SetN

func (s Series) SetN(n int, val float64) Series

SetN sets the first n values of a series to the specified value.

Shift

func (s Series) Shift(n int) Series

Shift shifts a series by the specified number of elements. Where the shift amount is a positive number, that many entries are removed from the right-hand end of the series, and the start of the series is padded with zeros to maintain the same length as the input. Where the shift amount is a negative number, that many entries are removed from the left-hand end of the series, and the end of the series is passed with zeros to maintain the same length as the input.

Sum

func (s Series) Sum(n int) Series

Sum returns a series comprising the summation of the last n values in the provided series.

Value

func (s Series) Value(lookback ...int) float64

Value returns the last value in the series (or zero if the series is empty).

ValueAverage

func (s Series) ValueAverage(n ...int) float64

ValueAverage returns the average of the values in the series. Optionally, a value n may be provided, in which case only the last n values will be averaged (unless n == 0, in which case all values will be averaged).

ValueBool

func (s Series) ValueBool(lookback ...int) bool

ValueBool returns a boolean based on whether the last value in the series is greater than zero.

ValueSum

func (s Series) ValueSum(n ...int) float64

ValueSum returns the sum of the values in the series. Optionally, a value n may be provided, in which case only the last n values will be summed (unless n == 0, in which case all values will be summed).

Window

func (s Series) Window(n int) Series

Window returns the last n values from the series if n is positive or all but the first n values if n is negative.

Arithmetic

Add

func (s Series) Add(y any) Series

Add adds the provided value to each value in the series.

Div

func (s Series) Div(y any) Series

Div divides each value in the series by the provided value. In the case where divisor is zero, the returned value will be zero.

Mul

func (s Series) Mul(y any) Series

Mul multiples the provided value by each value in the series.

Sub

func (s Series) Sub(y any) Series

Sub subtracts the provided value from each value in the series.

Comparison

EQ

func (s Series) EQ(y any) Series

EQ is an alias for Equal

Equal

func (s Series) Equal(y any) Series

Equal tests a provided value or series to see if it is equal to each entry in the receiver series.

GreaterThan

func (s Series) GreaterThan(y any) Series

GreaterThan tests a provided value or series to see if it is greater than each entry in the receiver series.

GreaterThanOrEqual

func (s Series) GreaterThanOrEqual(y any) Series

GreaterThanOrEqual tests a provided value or series to see if it is greater than or equal to each entry in the receiver series.

GT

func (s Series) GT(y any) Series

GT is an alias for GreaterThan

GTE

func (s Series) GTE(y any) Series

GTE is an alias for GreaterThanOrEqual

LessThan

func (s Series) LessThan(y any) Series

LessThan tests a provided value or series to see if it is less than each entry in the receiver series.

LessThanOrEqual

func (s Series) LessThanOrEqual(y any) Series

LessThanOrEqual tests a provided value or series to see if it is less or equal to than each entry in the receiver series.

LT

func (s Series) LT(y any) Series

LT is an alias for LessThan

LTE

func (s Series) LTE(y any) Series

LTE is an alias for LessThanOrEqual

Conditional

If

func (s Series) If(cond any, yes any, no any) Series

If takes a function that acts on each element of a series and returns a boolean that is used to determine whether the “yes” or “no” values passed will be used in the corresponding positions in the returned series. The condition function can take either a single float64 (the series value at each position in the series) or a float64 and an int, which will be the series value and its position in the series. The “yes” and “no” values can be either a scalar, another series, or a function. If a function is passed as the “yes” or “no” value, it should accept either a single float64 (the series value) or a float64 and an int (the series value and its position in the series).

Function Application

Func

func (s Series) Func(fn any, args ...any) Series

Func applies a function to a Series. It can be used to apply a function that is not part of the nseries package. Func can be called with a function of the form “func() Series” or “func(Series) Series”. The first form is useful for generating a series that is not dependent on any input data. The second form is useful for generating a new series created by applying a function to the input series. It will usually be useful to create a closure function that can take any required parameters and return a function that can be passed to Func. For example:

func addN(n float64) func(Series) Series {
   return func(s Series) Series {
       result := make(Series, len(s), len(s))
       for i := 0; i < len(s); i++ {
           result[i] = s[i] + n
       }
       return result
   }
}

which could then be used as:

s.Func(addN(10.0))

to add 10.0 to each value in the series.

Map

Map

func (s Series) Map(f func(x float64) float64) Series

Map applies an arbitrary func to each element of the series s and returns a series with the resulting computed values.

Slice Operations

Left

func (s Series) Left(n int) Series

Left returns a series of the n left-most values from a series.

Right

func (s Series) Right(n int) Series

Right returns a series of the n right-most values from a series.

Sorting

Reverse

func (s Series) Reverse() Series

Reverse returns a copy of the series with the element order reversed.

Sort

func (s Series) Sort(direction ...int) Series

Sort returns a copy of the series sorted in ascending order. An optional direction parameter can be provided; a negative value sorts in descending order.

Math

Abs

func (s Series) Abs() Series

Abs returns the absolute value of each value in the series.

Special cases are:

Abs(±Inf) = +Inf
Abs(NaN) = NaN

Acos

func (s Series) Acos() Series

Acos returns the arccosine, in radians, of each value in the series.

Special case is:

Acos(x) = NaN if x < -1 or x > 1

Acosh

func (s Series) Acosh() Series

Acosh returns the inverse hyperbolic cosine of each value in the series.

Special cases are:

Acosh(+Inf) = +Inf
Acosh(x) = NaN if x < 1
Acosh(NaN) = NaN

Asin

func (s Series) Asin() Series

Asin returns the arcsine, in radians, of each value in the series.

Special cases are:

Asin(±0) = ±0
Asin(x) = NaN if x < -1 or x > 1

Asinh

func (s Series) Asinh() Series

Asinh returns the inverse hyperbolic sine of each value in the series.

Special cases are:

Asinh(±0) = ±0
Asinh(±Inf) = ±Inf
Asinh(NaN) = NaN

Atan

func (s Series) Atan() Series

Atan returns the arctangent, in radians, of each value in the series.

Special cases are:

Atan(±0) = ±0
Atan(±Inf) = ±Pi/2

Atan2

func (s Series) Atan2(y float64) Series

Atan2 returns the arc tangent of y/x, using the signs of the two to determine the quadrant of the return value.

Special cases are (in order):

Atan2(y, NaN) = NaN
Atan2(NaN, x) = NaN
Atan2(+0, x>=0) = +0
Atan2(-0, x>=0) = -0
Atan2(+0, x<=-0) = +Pi
Atan2(-0, x<=-0) = -Pi
Atan2(y>0, 0) = +Pi/2
Atan2(y<0, 0) = -Pi/2
Atan2(+Inf, +Inf) = +Pi/4
Atan2(-Inf, +Inf) = -Pi/4
Atan2(+Inf, -Inf) = 3Pi/4
Atan2(-Inf, -Inf) = -3Pi/4
Atan2(y, +Inf) = 0
Atan2(y>0, -Inf) = +Pi
Atan2(y<0, -Inf) = -Pi
Atan2(+Inf, x) = +Pi/2
Atan2(-Inf, x) = -Pi/2

Atanh

func (s Series) Atanh() Series

Atanh returns the inverse hyperbolic tangent of each value in the series.

Special cases are:

Atanh(1) = +Inf
Atanh(±0) = ±0
Atanh(-1) = -Inf
Atanh(x) = NaN if x < -1 or x > 1
Atanh(NaN) = NaN

Cbrt

func (s Series) Cbrt() Series

Cbrt returns the cube root of each value in the series.

Special cases are:

Cbrt(±0) = ±0
Cbrt(±Inf) = ±Inf
Cbrt(NaN) = NaN

Ceil

func (s Series) Ceil() Series

Ceil returns the least integer value greater than or equal to x.

Special cases are:

Ceil(±0) = ±0
Ceil(±Inf) = ±Inf
Ceil(NaN) = NaN

Copysign

func (s Series) Copysign(sign float64) Series

Copysign returns a value with the magnitude of f and the sign of sign.

Cos

func (s Series) Cos() Series

Cos returns the cosine of the radian argument x.

Special cases are:

Cos(±Inf) = NaN
Cos(NaN) = NaN

Cosh

func (s Series) Cosh() Series

Cosh returns the hyperbolic cosine of each value in the series.

Special cases are:

Cosh(±0) = 1
Cosh(±Inf) = +Inf
Cosh(NaN) = NaN

Dim

func (s Series) Dim(y float64) Series

Dim returns the maximum of x-y or 0.

Special cases are:

Dim(+Inf, +Inf) = NaN
Dim(-Inf, -Inf) = NaN
Dim(x, NaN) = Dim(NaN, x) = NaN

Erf

func (s Series) Erf() Series

Erf returns the error function of each value in the series.

Special cases are:

Erf(+Inf) = 1
Erf(-Inf) = -1
Erf(NaN) = NaN

Erfc

func (s Series) Erfc() Series

Erfc returns the complementary error function of each value in the series.

Special cases are:

Erfc(+Inf) = 0
Erfc(-Inf) = 2
Erfc(NaN) = NaN

Erfcinv

func (s Series) Erfcinv() Series

Erfcinv returns the inverse of Erfc(x).

Special cases are:

Erfcinv(0) = +Inf
Erfcinv(2) = -Inf
Erfcinv(x) = NaN if x < 0 or x > 2
Erfcinv(NaN) = NaN

Erfinv

func (s Series) Erfinv() Series

Erfinv returns the inverse error function of each value in the series.

Special cases are:

Erfinv(1) = +Inf
Erfinv(-1) = -Inf
Erfinv(x) = NaN if x < -1 or x > 1
Erfinv(NaN) = NaN

Exp

func (s Series) Exp() Series

Exp returns e**x, the base-e exponential of each value in the series.

Special cases are:

Exp(+Inf) = +Inf
Exp(NaN) = NaN

Very large values overflow to 0 or +Inf. Very small values underflow to 1.

Exp2

func (s Series) Exp2() Series

Exp2 returns 2**x, the base-2 exponential of each value in the series.

Special cases are the same as Exp.

Expm1

func (s Series) Expm1() Series

Expm1 returns e**x - 1, the base-e exponential of x minus 1. It is more accurate than Exp(x) - 1 when x is near zero.

Special cases are:

Expm1(+Inf) = +Inf
Expm1(-Inf) = -1
Expm1(NaN) = NaN

Very large values overflow to -1 or +Inf.

Floor

func (s Series) Floor() Series

Floor returns the greatest integer value less than or equal to x.

Special cases are:

Floor(±0) = ±0
Floor(±Inf) = ±Inf
Floor(NaN) = NaN

FMA

func (s Series) FMA(y, z float64) Series

FMA returns x * y + z, computed with only one rounding. (That is, FMA returns the fused multiply-add of x, y, and z.)

Gamma

func (s Series) Gamma() Series

Gamma returns the Gamma function of each value in the series.

Special cases are:

Gamma(+Inf) = +Inf
Gamma(+0) = +Inf
Gamma(-0) = -Inf
Gamma(x) = NaN for integer x < 0
Gamma(-Inf) = NaN
Gamma(NaN) = NaN

Hypot

func (s Series) Hypot(y float64) Series

Hypot returns Sqrt(xx + yy), taking care to avoid unnecessary overflow and underflow.

Special cases are:

Hypot(±Inf, y) = +Inf
Hypot(y, ±Inf) = +Inf
Hypot(NaN, y) = NaN
Hypot(px, NaN) = NaN

J0

func (s Series) J0() Series

J0 returns the order-zero Bessel function of the first kind.

Special cases are:

J0(±Inf) = 0
J0(0) = 1
J0(NaN) = NaN

J1

func (s Series) J1() Series

J1 returns the order-one Bessel function of the first kind.

Special cases are:

J1(±Inf) = 0
J1(NaN) = NaN

Jn

func (s Series) Jn(n int) Series

Jn returns the order-n Bessel function of the first kind.

Special cases are:

Jn(n, ±Inf) = 0
Jn(n, NaN) = NaN

Ldexp

func (s Series) Ldexp(exp int) Series

Ldexp is the inverse of Frexp. It returns frac × 2**exp.

Special cases are:

Ldexp(±0, exp) = ±0
Ldexp(±Inf, exp) = ±Inf
Ldexp(NaN, exp) = NaN

Log

func (s Series) Log() Series

Log returns the natural logarithm of each value in the series.

Special cases are:

Log(+Inf) = +Inf
Log(0) = -Inf
Log(x < 0) = NaN
Log(NaN) = NaN

Log10

func (s Series) Log10() Series

Log10 returns the decimal logarithm of each value in the series. The special cases are the same as for Log.

Log1p

func (s Series) Log1p() Series

Log1p returns the natural logarithm of 1 plus its argument x. It is more accurate than Log(1 + x) when x is near zero.

Special cases are:

Log1p(+Inf) = +Inf
Log1p(±0) = ±0
Log1p(-1) = -Inf
Log1p(x < -1) = NaN
Log1p(NaN) = NaN

Log2

func (s Series) Log2() Series

Log2 returns the binary logarithm of each value in the series. The special cases are the same as for Log.

Logb

func (s Series) Logb() Series

Logb returns the binary exponent of each value in the series.

Special cases are:

Logb(±Inf) = +Inf
Logb(0) = -Inf
Logb(NaN) = NaN

Max

func (s Series) Max(y float64) Series

Max returns the larger of x or y.

Special cases are:

Max(x, +Inf) = Max(+Inf, x) = +Inf
Max(x, NaN) = Max(NaN, x) = NaN
Max(+0, ±0) = Max(±0, +0) = +0
Max(-0, -0) = -0

Note that this differs from the built-in function max when called with NaN and +Inf.

Min

func (s Series) Min(y float64) Series

Min returns the smaller of x or y.

Special cases are:

Min(x, -Inf) = Min(-Inf, x) = -Inf
Min(x, NaN) = Min(NaN, x) = NaN
Min(-0, ±0) = Min(±0, -0) = -0

Note that this differs from the built-in function min when called with NaN and -Inf.

Mod

func (s Series) Mod(y float64) Series

Mod returns the floating-point remainder of x/y. The magnitude of the result is less than y and its sign agrees with that of each value in the series.

Special cases are:

Mod(±Inf, y) = NaN
Mod(NaN, y) = NaN
Mod(x, 0) = NaN
Mod(x, ±Inf) = x
Mod(x, NaN) = NaN

Pow

func (s Series) Pow(y float64) Series

Pow returns x**y, the base-x exponential of y.

Special cases are (in order):

Pow(x, ±0) = 1 for any x
Pow(1, y) = 1 for any y
Pow(x, 1) = x for any x
Pow(NaN, y) = NaN
Pow(x, NaN) = NaN
Pow(±0, y) = ±Inf for y an odd integer < 0
Pow(±0, -Inf) = +Inf
Pow(±0, +Inf) = +0
Pow(±0, y) = +Inf for finite y < 0 and not an odd integer
Pow(±0, y) = ±0 for y an odd integer > 0
Pow(±0, y) = +0 for finite y > 0 and not an odd integer
Pow(-1, ±Inf) = 1
Pow(x, +Inf) = +Inf for |x| > 1
Pow(x, -Inf) = +0 for |x| > 1
Pow(x, +Inf) = +0 for |x| < 1
Pow(x, -Inf) = +Inf for |x| < 1
Pow(+Inf, y) = +Inf for y > 0
Pow(+Inf, y) = +0 for y < 0
Pow(-Inf, y) = Pow(-0, -y)
Pow(x, y) = NaN for finite x < 0 and finite non-integer y

Remainder

func (s Series) Remainder(y float64) Series

Remainder returns the IEEE 754 floating-point remainder of x/y.

Special cases are:

Remainder(±Inf, y) = NaN
Remainder(NaN, y) = NaN
Remainder(x, 0) = NaN
Remainder(x, ±Inf) = x
Remainder(x, NaN) = NaN

Round

func (s Series) Round() Series

Round returns the nearest integer, rounding half away from zero.

Special cases are:

Round(±0) = ±0
Round(±Inf) = ±Inf
Round(NaN) = NaN

RoundToEven

func (s Series) RoundToEven() Series

RoundToEven returns the nearest integer, rounding ties to even.

Special cases are:

RoundToEven(±0) = ±0
RoundToEven(±Inf) = ±Inf
RoundToEven(NaN) = NaN

Sin

func (s Series) Sin() Series

Sin returns the sine of the radian argument x.

Special cases are:

Sin(±0) = ±0
Sin(±Inf) = NaN
Sin(NaN) = NaN

Sinh

func (s Series) Sinh() Series

Sinh returns the hyperbolic sine of each value in the series.

Special cases are:

Sinh(±0) = ±0
Sinh(±Inf) = ±Inf
Sinh(NaN) = NaN

Sqrt

func (s Series) Sqrt() Series

Sqrt returns the square root of each value in the series.

Special cases are:

Sqrt(+Inf) = +Inf
Sqrt(±0) = ±0
Sqrt(x < 0) = NaN
Sqrt(NaN) = NaN

Squared

func (s Series) Squared() Series

Squared returns the squared of each value in the series.

Tan

func (s Series) Tan() Series

Tan returns the tangent of the radian argument x.

Special cases are:

Tan(±0) = ±0
Tan(±Inf) = NaN
Tan(NaN) = NaN

Tanh

func (s Series) Tanh() Series

Tanh returns the hyperbolic tangent of each value in the series.

Special cases are:

Tanh(±0) = ±0
Tanh(±Inf) = ±1
Tanh(NaN) = NaN

Trunc

func (s Series) Trunc() Series

Trunc returns the integer value of each value in the series.

Special cases are:

Trunc(±0) = ±0
Trunc(±Inf) = ±Inf
Trunc(NaN) = NaN

Y0

func (s Series) Y0() Series

Y0 returns the order-zero Bessel function of the second kind.

Special cases are:

Y0(+Inf) = 0
Y0(0) = -Inf
Y0(x < 0) = NaN
Y0(NaN) = NaN

Y1

func (s Series) Y1() Series

Y1 returns the order-one Bessel function of the second kind.

Special cases are:

Y1(+Inf) = 0
Y1(0) = -Inf
Y1(x < 0) = NaN
Y1(NaN) = NaN

Yn

func (s Series) Yn(n int) Series

Yn returns the order-n Bessel function of the second kind.

Special cases are:

Yn(n, +Inf) = 0
Yn(n ≥ 0, 0) = -Inf
Yn(n < 0, 0) = +Inf if n is odd, -Inf if n is even
Yn(n, x < 0) = NaN
Yn(n, NaN) = NaN

Moving Averages

Average

func (s Series) Average(n int) Series

Average returns a simple moving average over the last values in the provided Series. If there is insufficient input to provide an average over values, the original Series is returned.

EMA

func (s Series) EMA(n int) Series

EMA is an alias for XAverage.

HMA

func HMA(s Series, n int) Series

HMA is an alias for HullAverage.

HullAverage

func (s Series) HullAverage(n int) Series

HullAverage returns the Hull moving average over the last values in the provided Series. If there is insufficient input to provide an average over values, the original Series is returned.

Mean

func (s Series) Mean(n int) Series

Mean is an alias for Average.

SMA

func (s Series) SMA(n int) Series

SMA is an alias for Average.

TEMA

func (s Series) TEMA(n int) Series

TEMA returns the triple-exponential moving average.

WAverage

func (s Series) WAverage(n int) Series

WAverage returns a weighted moving average over the last values in the provided Series. If there is insufficient input to provide an average over values, the original Series is returned.

WMA

func (s Series) WMA(n int) Series

WMA is an alias for WAverage.

XAverage

func (s Series) XAverage(n int) Series

XAverage returns an exponential moving average over the last values in the provided Series. If there is insufficient input to provide an average over values, the original Series is returned.

XMA

func (s Series) XMA(n int) Series

XMA is an alias for XAverage.

ZLEMA

func (s Series) ZLEMA(n int) Series

ZLEMA returns the Ehlers/Way zero-lag EMA.

ZLEMAGain

func (s Series) ZLEMAGain(n int, gainMax int) Series

ZLEMAGain implements a gain-adjusted moving average. Based on code from Robert Pardo.

Ehlers Indicators

Angle

func (s Series) Angle() Series

Angle implements the angle function according to the translation of the TradeStation algorithm provided by John Ehlers.

BandPass

func (s Series) BandPass(n int, bandwidth float64) Series

BandPass implements the band-pass filter according to the translation of the TradeStation algorithm provided by John Ehlers.

ContinuationIndex

func (s Series) ContinuationIndex(n int, gamma float64, order int) Series

ContinuationIndex implements Ehlers’ continuation index from TASC Sep 2025. A good starting point for the length (n) is to use the desired number of bars to be in a trade.

DSMA

func (s Series) DSMA(n int) Series

DSMA calculates the deviation-scaled moving average according to the translation of the TradeStation algorithm provided by John Ehlers. TODO – Revisit this to deal with de-gapping (which we have left out).

DSSS

func (s Series) DSSS(n int) Series

DSSS calculates the deviation-scaled super smoother according to the translation of the TradeStation algorithm provided by John Ehlers. TODO – Revisit this to deal with de-gapping (which we have left out).

EMAT

func (s Series) EMAT(n int) Series

EMAT calculates the truncated EMA according to the translation of the TradeStation algorithm provided by John Ehlers.

FRAMA

func (s Series) FRAMA(h, l, c Series, n int) Series

FRAMA calculates the fractal EMA according to the translation of the TradeStation algorithm provided by John Ehlers.

Hann

func (s Series) Hann(n int) Series

Hann calculates the Hann windowed low-pass FIR filter according to the translation of the TradeStation algorithm provided by John Ehlers.

HighPass

func (s Series) HighPass(n int) Series

HighPass implements the high-pass filter according to the translation of the TradeStation algorithm provided by John Ehlers.

Laguerre

func (s Series) Laguerre(n int, gamma float64, order int) Series

Laguerre implements Ehlers’ Laguerre filter code from TASC Sep 2025.

LaguerreRSI

func (s Series) LaguerreRSI(gamma float64) Series

LaguerreRSI implements John Ehlers’ Laguerre Relative Strength Index.

Phase

func (s Series) Phase(n int) Series

Phase implements the phase function according to the translation of the TradeStation algorithm provided by John Ehlers.

PMA

func (s Series) PMA(n int) Series

PMA implements John Ehlers’ Projected Moving Average (as described in TASC Mar 2025).

PMAPredict

func (s Series) PMAPredict(n int) Series

PMAPredict implements John Ehlers’ prediction based on the predicted moving average (see TASC Mar 2025, p. 11)

RocketRSI

func (s Series) RocketRSI(nSmooth, n int) Series

Slope

func (s Series) Slope(n int) Series

Slope calculates the slope over “n” points at each point in the series (see TASC Mar 2025, p. 11).

SuperSmoother

func (s Series) SuperSmoother(n int) Series

SuperSmoother implements the super-smoother function according to the translation of the TradeStation algorithm provided by John Ehlers.

UltimateOscillator

func (s Series) UltimateOscillator(bandEdge int, bandWidth int, rmsLength ...int) Series

UltimateOscillator implements the ultimate-oscillator function according to the translation of the TradeStation algorithm provided by John Ehlers (in TASC April 2025). Optionally, the TMS lngth can be defined. If not defined, it will default to 100. This is done because hard-coding it to 100 it as Ehlers has done implies MaxBardBack will have to be at least 100, which will not be true by default.

UltimateSmoother

func (s Series) UltimateSmoother(n int) Series

UltimateSmoother implements the ultimate-smoother function according to the translation of the TradeStation algorithm provided by John Ehlers (in TASC April 2024). Note that the Sep 2025 TASC has different code for the UltimateSmoother, but we have stuck with the previous version here (for the moment, at least).

USI

func (s Series) USI(n int) Series

USI implements John Ehlers’ Ultimate Strength Index (as described in TASC Nov 2024).

VIDYA

func (s Series) VIDYA(short int, long int) Series

VIDYA implements Chande/Kroll’s variable dynamic average according to the translation of the TradeStation algorithm provided by John Ehlers.

Voss

func (s Series) Voss(lead int) Series

Voss implements the Voss predictor function according to the translation of the TradeStation algorithm provided by John Ehlers.

ZeroLag

func (s Series) ZeroLag(n int) Series

ZeroLag implements John Ehlers’ zero-lag indicator.

KAMA

KAMA

func (s Series) KAMA(n int, speeds ...int) Series

KAMA implements Kaufman’s Adaptive Moving Average across the provided series. Not that Kaufman recommends that the fast value be only 2 or 3, and the slow value be fixed at 30, which are the defaults.

Cong Adaptive MA

CongAdaptiveMA

func (s Series) CongAdaptiveMA(h, l, c Series, n int) Series

CongAdaptiveMA implements Scott Cong’s Adaptive Moving Average (as described in TASC March 2023).

Casey Percent C

CaseyPercentC

func (s Series) CaseyPercentC(lookback int, smoothLen int) Series

CaseyPercentC implements Ali Casey’s C% oscillator.

CaseyPercentCSuperSmoother

func (s Series) CaseyPercentCSuperSmoother(lookback int, smoothLen int) Series

CaseyPercentCSuperSmoother implements Ali Casey’s C% oscillator but with Ehlers' Super Smoother rather than SMA.

CaseyPercentCUltimateSmoother

func (s Series) CaseyPercentCUltimateSmoother(lookback int, smoothLen int) Series

CaseyPercentCUltimateSmoother implements Ali Casey’s C% oscillator but with Ehlers' Ultimate Smoother rather than SMA.

CaseyPercentCXAverage

func (s Series) CaseyPercentCXAverage(lookback int, smoothLen int) Series

CaseyPercentCXAverage implements Ali Casey’s C% oscillator but with an EMA rather than SMA.

Kalman Filter

Kalman

func (s Series) Kalman(k1 float64) Series

Kalman implements the Kalman filter on a data series. Based on the article by Vince Banes in Stocks & Commodities in October 2010.

One Euro Filter

OneEuroFilter

func (s Series) OneEuroFilter(periodMin float64, beta float64) Series

OneEuroFilter applies the 1-Euro adaptive low-pass filter. It adapts its cutoff frequency based on the rate of change of the input, providing strong smoothing during slow movements and minimal lag during fast movements. The periodMin parameter sets the minimum cutoff period and beta controls the speed adaptation.

Bollinger Bands

Bollinger

func (s Series) Bollinger(length int, nbrStdDevs float64) Series

Bollinger returns a smoothed series adjusted by a specified number of standard deviations (which could be negative) determined from the specified previous number of bars.

BollingerX

func (s Series) BollingerX(length int, nbrStdDevs float64) Series

BollingerX returns a smooth series (where the smoothing function is an exponential moving average rather than the standard simple moving average) adjusted by a specified number of standard deviations (which could be negative) determined from the specified previous number of bars.

Donchian Channels

DonchianLower

func (s Series) DonchianLower(n int) Series

DonchianLower returns a series representing the lower Donchian channel measured over n bars.

DonchianMiddle

func (s Series) DonchianMiddle(n int) Series

DonchianMiddle returns a series representing the middle Donchian channel measured over n bars.

DonchianUpper

func (s Series) DonchianUpper(n int) Series

DonchianUpper returns a series representing the upper Donchian channel measured over n bars.

Keltner Channels

Keltner

func (s Series) Keltner(h, l, c Series, priceLen int, trLen int, atrFactor float64) Series

Keltner is an alias for KeltnerSS. This calculation is the one used by TradeStation.

KeltnerSS

func (s Series) KeltnerSS(h, l, c Series, priceLen int, trLen int, atrFactor float64) Series

KeltnerSS returns a simple smoothed series adjusted by the simple moving average of a specified number of true ranges (which could be negative) determined from the specified previous number of true range bars. This calculation is the one used by TradeStation.

KeltnerSX

func (s Series) KeltnerSX(h, l, c Series, priceLen int, trLen int, atrFactor float64) Series

KeltnerSX returns a simple smoothed series adjusted by the exponential moving average of a specified number of true ranges (which could be negative) determined from the specified previous number of true range bars.

KeltnerXS

func (s Series) KeltnerXS(h, l, c Series, priceLen int, trLen int, atrFactor float64) Series

KeltnerXS returns an exponentially smoothed series adjusted by the simple moving average of a specified number of true ranges (which could be negative) determined from the specified previous number of true range bars.

KeltnerXX

func (s Series) KeltnerXX(h, l, c Series, priceLen int, trLen int, atrFactor float64) Series

KeltnerXX returns an exponential mple smoothed series adjusted by the exponential moving average of a specified number of true ranges (which could be negative) determined from the specified previous number of true range bars.

RSI

RSI

func (s Series) RSI(n int) Series

RSI implements Wilder’s Relative Strength Index using a slightly more efficient algorithm than Wilder used.

RSIWilderOriginal

func (s Series) RSIWilderOriginal(n int) Series

RSIWilderOriginal calculates the n-period Relative Strength Index (using Wilder’s formula).

Connors RSI

ConnorsRSI

func (s Series) ConnorsRSI(rsiPeriod, streakRSIPeriod, rocPeriod int) Series

ConnorsRSI computes the Connors RSI composite oscillator. Developed by Larry Connors, it combines three components: a standard RSI, an RSI of the up/down streak length, and a percentile rank of the rate of change. The result is the average of these three values.

Stochastic

Stochastic

func (s Series) Stochastic(h, l Series, n int) Series

Stochastic calculates the percentage value of each input value across the range determined by looking back at the last n values. Until n values have been seen, the default values is set to 50 (i.e. the middle).

Williams %R

WilliamsR

func (s Series) WilliamsR(h, l, c Series, n int) Series

WilliamsR calculates the Williams %R values over an n-period term. Until n values have been seen, the default values are set to zero.

Percent R

PercentR

func (s Series) PercentR(h, l, c Series, n int) Series

PercentR returns series whereby each value represents the percentage in the range (of the last n bars) of the closing price. It is effectively the Williams %R calculation but with a return value range of 0 - 100.

Percent Rank

PercentRank

func (s Series) PercentRank(val float64, n int) Series

PercentRank computes the percentile rank of a value within a rolling window of n bars. Returns a value between 0 and 1 indicating where the given value falls within the sorted window, or -1 if the value is outside the window’s range. Consistent with TradeStation’s PercentRank function.

MACD

MACD

func (s Series) MACD(fastLen, slowLen int) Series

MACD returns the Moving Average Convergence/ Divergence of a fast and slow EMA.

TRIX

TRIX

func (s Series) TRIX(n int) Series

TRIX calculates the TRIX indicator but using the more recent approach of percentage gains of E3(t) compared with E3(t-1), rather than the older approach that used the log of the price.

TRIXTS

func (s Series) TRIXTS(n int) Series

TRIXTS calculates the TRIX indicator using the same formula as TradeStation.

Commodity Channel Index

CCI

func (s Series) CCI(h, l, c Series, n int) Series

CCI computes the Commodity Channel Index over a period of n bars. Developed by Donald Lambert, CCI measures how far the typical price deviates from its average, scaled by the mean absolute deviation. Values above +100 suggest overbought conditions; below -100 suggest oversold.

Aroon

AroonDown

func (s Series) AroonDown(n int) Series

AroonDown returns a series that represents the percentage of previous bars back in a range back to the previous lowest bar in that range. Note: The input series should always be the lows for this calculation.

AroonUp

func (s Series) AroonUp(n int) Series

AroonUp returns a series that represents the percentage of previous bars back in a range back to the previous highest bar in that range. Note: The input series should always be the highs for this calculation.

Momentum

Momentum

func (s Series) Momentum(n int) Series

Momentum returns a series calculated as the difference between the current price and the price n bars ago,

Rate of Change

RateOfChange

func (s Series) RateOfChange(n int) Series

RateOfChange computes the percentage rate of change over n bars. The result is ((current / n-bars-ago) - 1) * 100.

Delta / Change

Delta

func (s Series) Delta(n ...int) Series

Delta computes the difference between each value and the value n entries back. By default, n is one.

DeltaPercent

func (s Series) DeltaPercent(n ...int) Series

DeltaPercent computes the percentage difference between series elements.

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.

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.

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.

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.

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.

True Range

ATR

func (s Series) ATR(h, l, c Series, n int) Series

ATR is an alias for AvgTrueRange()

AvgTrueRange

func (s Series) AvgTrueRange(h, l, c Series, n int) Series

AvgTrueRange computes the average true range over n bars.

TrueRange

func (s Series) TrueRange(h, l, c Series) Series

TrueRange computes the true range for each bar as max(previous close, high) minus min(previous close, low).

SuperTrend

SuperTrend

func (s Series) SuperTrend(h, l, c Series, mult float64, trLen int) Series

SuperTrend returns a series based on Olivier Seban’s Super Trend indicator. The indicator returns a series that is adjusted (up or down depending on the sign of the factor) by factor x ATR(n).

Choppiness Index

Chop

func (s Series) Chop(h, l, c Series, n int) Series

Chop implements the Choppiness Index oscillator developed by Bill Dreiss to help determine whether a market is trending or ranging. The Choppiness Index measures the volatility and directionality of price movements. It oscillates between 0 and 100, with lower values indicating a trending market and higher values signalling a choppy or ranging market. Values below 38.2 typically suggest a strong trend (either upward or downward). Values above 61.8 indicate a choppy or consolidating market. The middle range between 38.2 and 61.8 suggests an uncertain market condition. Consider using this indicator in preference to ADX. See the article titled “Fractal Energies” in TASC May 2012 for an example of how to use the Choppiness Index oscillator.

Accumulation / Distribution

AccumDist

func (s Series) AccumDist(h, l, c, v Series) Series

AccumDist implements Chaikin’s Accumulation/Distribution (A/D) line. Developed by Marc Chaikin in the 1970s, it measures the flow of money into and out of a security. This volume-based indicator helps to identify the underlying buying or selling pressure that may not be immediately apparent from price action alone.

The A/D line examines where the closing price falls within a trading range. When prices close in the upper portion of the range, this indicates buying pressure. When prices close in the lower portion of the range, this indicates selling pressure. When prices close around the midpoint, this indicates neutral pressure.

The indicator becomes more significant when accompanied by high volume. A strong close near the high with high volume results in a substantial A/D line increase, while low volume or mid-range closes produce smaller movements.

A rising A/D line confirms an uptrend and a falling A/D line confirms a downtrend.

When the A/D line moves in the opposite direction of price, it can signal potential reversals. A bullish divergence occurs when prices makes a new low and the A/D line shows strength (potential capitulation). A bearish divergence occurs when price make a new high but the A/D line fails to follow (potential exhaustion).

  • Bearish divergence: Price makes new highs while A/D line fails to follow
  • Bullish divergence: Price makes new lows while A/D line shows strength

Note that this is a lagging indicator, and it may generate false signals during periods of consolidation.

Note that this differs from the TradeStation implementation, which uses (C-O)/(H-L) * V.

On-Balance Volume

OBV

func (s Series) OBV(c, v Series) Series

OBV implements Joe Granville’s On-Balance Volume indicator.

Money Flow Index

MFI

func (s Series) MFI(h, l, c, v Series, period int) Series

MFI implements the Money Flow Index.

MoneyFlowIndex

func (s Series) MoneyFlowIndex(h, l, c, v Series, period int) Series

Chaikin Oscillator

ChaikinOsc

func (s Series) ChaikinOsc(h, l, c, v Series, speeds ...int) Series

ChaikinOsc implements Marc Chaikin’s momentum indicator that measures the flow of money into and out of a security by analysing volume and price movements. It aims to identify buying and selling pressure.

Positive values indicate buying pressure and potential bullish conditions, while negative values suggest selling pressure and potential bearish conditions.

This indicator is three steps removed from price action:

  1. price and volume form the ADL;
  2. two EMAs are applied to the ADL; and
  3. the difference between EMAs forms the oscillator.

This separation can sometimes lead to disconnects between the indicator and the underlying price movement.

It seems that values of 3 and 10 are the most commonly used for the two EMAs, so we default to these if no speeds are provided.

Volume Profile

VolumeProfileHistogram

func (s Series) VolumeProfileHistogram(h, l, c, v Series, n int, bins ...int) (mins Series, widths Series, hist [][]float64)

VolumeProfileHistogram exposes the per-bin volume histogram for each rolling window of length n. It returns three aligned outputs of length len(c):

  • mins[i]: the minimum price (window low) for window [i-n+1, i], or 0 for i < n-1
  • widths[i]: the bin width for that window (may be 0 for degenerate ranges), or 0 for i < n-1
  • hist[i]: the per-bin volumes slice of length k for that window; nil for i < n-1 or invalid inputs

Parameters are identical to the other Volume Profile functions. The optional bins parameter selects the number of bins (default 40; must be >0).

VolumeProfileHVNCount

func (s Series) VolumeProfileHVNCount(h, l, c, v Series, n int, bins ...int) Series

VolumeProfileHVNCount computes, for each rolling window of length n, the number of high-volume bins (HVNs) in the volume profile histogram.

Definition: a bin is considered a high-volume node if its volume is a strict local maximum relative to its immediate neighbors; edge bins are compared to their single neighbor. Tied highs are not counted.

Parameters mirror the other Volume Profile functions. If bins is omitted or <= 0, the number of bins is auto-inferred per window and clamped to 40.

Returns a Series aligned to the input length; entries before the first full window (i < n-1) are zero.

VolumeProfileIsAtHVN

func (s Series) VolumeProfileIsAtHVN(h, l, c, v Series, n int, price Series, bins ...int) Series

VolumeProfileIsAtHVN returns a binary Series indicating whether a provided price Series lies at a High-Volume Node (HVN) for each rolling window of length n. For index i, it builds the volume profile over [i-n+1, i], finds the bin containing price[i], and sets result[i]=1 if that bin is a strict local maximum in the histogram (edge bins compare to their single neighbor). Ties are not counted. Indices i < n-1 yield 0.

If bins is omitted or <= 0, the number of bins is auto-inferred per window (default/clamped to 40). If inputs are invalid or the window is degenerate, the result is 0 at that index.

VolumeProfileIsAtLVN

func (s Series) VolumeProfileIsAtLVN(h, l, c, v Series, n int, price Series, bins ...int) Series

VolumeProfileIsAtLVN returns a binary Series indicating whether a provided price Series lies at a Low-Volume Node (LVN) for each rolling window of length n. For index i, it builds the volume profile over [i-n+1, i], finds the bin containing price[i], and sets result[i]=1 if that bin is a strict local minimum in the histogram (edge bins compare to their single neighbor). Ties are not counted. Indices i < n-1 yield 0.

If bins is omitted or <= 0, the number of bins is auto-inferred per window (default/clamped to 40). If inputs are invalid or the window is degenerate, the result is 0 at that index.

VolumeProfilePOC

func (s Series) VolumeProfilePOC(h, l, c, v Series, n int, bins ...int) Series

VolumeProfilePOC computes the rolling Point of Control (price at the highest volume bin) from a Volume Profile built over the last n bars, using H/L/C and distributing each bar’s volume evenly across its price range.

Parameters:

  • h, l, c, v: High, Low, Close, Volume series (must be the same length)
  • n: lookback window (number of bars)
  • bins: optional number of price bins. If omitted or <=0, the bin count is inferred from the window using the smallest non-zero price delta (tick), clamped to a maximum of 40 bins; if the tick cannot be determined, it defaults to 40.

Returns a Series of the same length. For indices < n-1 (insufficient history), the value is 0.

VolumeProfileVAH

func (s Series) VolumeProfileVAH(h, l, c, v Series, n int, valueAreaPct float64, bins ...int) Series

VolumeProfileVAH computes the rolling Value Area High (upper bound) price that, together with VAL, encloses approximately valueAreaPct (default 0.70) of the total volume in the profile, expanding outwards from the POC.

valueAreaPct must be in the range 0 to 1; if 0 is provided, it defaults to 0.70.

VolumeProfileVAL

func (s Series) VolumeProfileVAL(h, l, c, v Series, n int, valueAreaPct float64, bins ...int) Series

VolumeProfileVAL computes the rolling Value Area Low (lower bound) price that, together with VAH, encloses approximately valueAreaPct (default 0.70) of the total volume in the profile, expanding outwards from the POC.

valueAreaPct must be in (0, 1]; if 0 is provided, it defaults to 0.70.

Pivots

PivotIndices

func (s Series) PivotIndices(level int, thresholdPercent float64, filter ...[]bool) []int

PivotIndices returns a slice of integers that represents pivot highs and lows in a series, where a high is a value with a lower value either side, and a low is a value with a higher value either side. A specified threshold represents a percentage price movement to be observed to qualify as a pivot. An optional extra slice of booleans can be provided, indicating whether a bar should be considered (which is useful if, for example, inside bars were to be ignored in the determination of a pivot point).

The specified level determines the number of times the price series is processed. When the level is 1, the pivots of the raw prices (which could be thought of as the short-term pivots) will be returned. When the level is 2, the pivots of the short-term pivots (which could be thought of as the medium-term pivots) will be returned. When the level is 3, the pivots of the medium-term pivots (which could be thought of as the long-term pivots) will be returned.

The slice of indices returned will contain positive values for pivot highs and negative values for pivot lows. Non-pivots are excluded from the results.

Pivots

func (s Series) Pivots(level int, thresholdPercent float64, filter ...[]bool) []int

Pivots returns a slice of integers that represents pivot highs and lows in a series, where a high is a value with a lower value either side, and a low is a value with a higher value either side. A specified threshold represents a percentage price movement to be observed to qualify as a pivot. An optional extra slice of booleans can be provided, indicating whether a bar should be considered (which is useful if, for example, inside bars were to be ignored in the determination of a pivot point).

The specified level determines the number of times the price series is processed. When the level is 1, the pivots of the raw prices (which could be thought of as the short-term pivots) will be returned. When the level is 2, the pivots of the short-term pivots (which could be thought of as the medium-term pivots) will be returned. When the level is 3, the pivots of the medium-term pivots (which could be thought of as the long-term pivots) will be returned.

The slice of indices returned will contain lookback offsets from the end of the slice (positive for pivot highs, negative for pivot lows, zero for non-pivots). For example, if the latest pivot high occurred four bars from the end of the input series, the returned slice would contain a value of 4 for that pivot high in the position four back from the end of the returned slice.

Floor Trader Pivots

FloorTraderPivot

func (s Series) FloorTraderPivot(h, l, c Series) Series

FloorTraderPivot computes the floor trader pivot point as (H+L+C)/3.

FloorTraderR1

func (s Series) FloorTraderR1(h, l, c Series) Series

FloorTraderR1 computes the first floor trader resistance level.

FloorTraderR2

func (s Series) FloorTraderR2(h, l, c Series) Series

FloorTraderR2 computes the second floor trader resistance level.

FloorTraderR3

func (s Series) FloorTraderR3(h, l, c Series) Series

FloorTraderR3 computes the third floor trader resistance level.

FloorTraderS1

func (s Series) FloorTraderS1(h, l, c Series) Series

FloorTraderS1 computes the first floor trader support level.

FloorTraderS2

func (s Series) FloorTraderS2(h, l, c Series) Series

FloorTraderS2 computes the second floor trader support level.

FloorTraderS3

func (s Series) FloorTraderS3(h, l, c Series) Series

FloorTraderS3 computes the third floor trader support level.

Swings

Swings

func (s Series) Swings(opn Series, high Series, low Series, cls Series, hint ...int) []int

Swings returns a slice of integers that represents swing highs and lows in a series, where zero indicates no swing, a positive value indicates a swing high, and a negative value indicates a swing low. The magnitude of the value indicates how many values back in the series the high/low occurred. Unlike SwingsHL, outside bars are treated as directional bars based on whether the open is greater than the close (down bar) or less than the close (up bar). Inside bars are handled the same way as in SwingsHL. An optional hint parameter can be provided to specify the first known swing.

SwingsHL

func (s Series) SwingsHL(high Series, low Series, hint ...int) []int

SwingsHL returns a slice of integers that represents swing highs and lows in a series, where zero indicates no swing, a positive value indicates a swing high, and a negative value indicates a swing low. The magnitude of the value indicates how many values back in the series the high/low occurred. For example, for a series of 10 bars with a swing high on the 3rd bar, a low on the 5th bar, and a high on the 9th bar, the returned series would be: [0, 0, 7, 0, 0, -4, 0, 0, 1, 0]. The swings are calculated according to Brent Penfold’s algorithm. An optional hint parameter can be provided to specify the first known swing. If positive, it indicates a swing high at that bar index; if negative, it indicates a swing low at the absolute value of that index. Bars before the hint are ignored.

SwingsPath

func (s Series) SwingsPath(highs Series, lows Series, paths []float64) []int

Highest / Lowest

Highest

func (s Series) Highest(n int) Series

Highest returns the highest value from the last values. For the first values, the highest along the series to that point is returned.

Lowest

func (s Series) Lowest(n int) Series

Lowest returns the lowest value from the last values. For the first values, the lowest along the series to that point is returned.

Index Of

IndexOfHighest

func (s Series) IndexOfHighest(n int) int

IndexOfHighest returns the index (zero-based) of the highest value in last “n” values in a series. Where the highest value occurs more than once in the series, the index of the most recent (latest) one is returned. For example, the index returned for { 4, 6, 8, 10, 12, 10 } would be 4, since 12 is the fifth (i.e. index = 4) value in the series.

IndexOfHighestS

func (s Series) IndexOfHighestS(n int) Series

IndexOfHighestS returns a series of indices (zero-based) of the highest value in “n”-length windows in a series. Where the highest value occurs more than once in the series, the index of the most recent (latest) one is returned.

IndexOfLowest

func (s Series) IndexOfLowest(n int) int

IndexOfLowest returns the index (zero-based) of the lowest value in last “n” values in a series. Where the lowest value occurs more than once in the series, the index of the most recent (latest) one is returned. For example, the index returned for { 12, 4, 6, 8, 10, 12 } would be 1, since 4 is the second (i.e. index = 1) value in the series.

IndexOfLowestS

func (s Series) IndexOfLowestS(n int) Series

IndexOfLowestS returns a series of indices (zero-based) of the lowest value in “n”-length windows in a series. Where the lowest value occurs more than once in the series, the index of the most recent (latest) one is returned.

Crossover Detection

CrossesAbove

func (s Series) CrossesAbove(val any) bool

CrossesAbove returns a boolean to indicate whether the second-last series value was less than or equal to the provided value/series and the last series value is greater than the provided value/value.

CrossesAboveS

func (s Series) CrossesAboveS(val any) Series

CrossesAboveS returns a series to indicate whether the prior series value was less than or equal to the provided value/series and the current series value is greater than the provided value/series. The series returned will contain 1.0 where the test is true and 0.0 where it is false.

CrossesBelow

func (s Series) CrossesBelow(val any) bool

CrossesBelow returns a boolean to indicate whether the second-last series value was greater than or equal to the provided value/series and the last series value is less than the provided value/series.

CrossesBelowS

func (s Series) CrossesBelowS(val any) Series

CrossesBelowS returns a series to indicate whether the prior series value was greater than or equal to the provided value/series and the current series value is less than the provided value/series. The series returned will contain 1.0 where the test is true and 0.0 where it is false.

Consecutive

ConsecDown

func (s Series) ConsecDown() Series

ConsecDown returns a series of the counts of bars that are consecutively down.

ConsecDownOrEqual

func (s Series) ConsecDownOrEqual() Series

ConsecDownOrEqual returns a series of the counts of bars that are consecutively down or equal.

ConsecUp

func (s Series) ConsecUp() Series

ConsecUp returns a series of the counts of bars that are consecutively up.

ConsecUpOrEqual

func (s Series) ConsecUpOrEqual() Series

ConsecUpOrEqual returns a series of the counts of bars that are consecutively up or equal.

N of M

NofDown

func (s Series) NofDown(n, m int) bool

NofDown returns a boolean to indicate whether n of the last m values were lower than their preceding value.

NofDownS

func (s Series) NofDownS(n, m int) Series

NofDownS returns a series indicating whether n of the last m values were lower than their preceding value. At each position in the input series where this is true, the returned series will have the value 1.0 and where false will have the value 0.0.

NofUp

func (s Series) NofUp(n, m int) bool

NofUp returns a boolean to indicate whether n of the last m values were higher than their preceding value.

NofUpS

func (s Series) NofUpS(n, m int) Series

NofUpS returns a series indicating whether n of the last m values were higher than their preceding value. At each position in the input series where this is true, the returned series will have the value 1.0 and where false will have the value 0.0.

Up / Down

UpDown

func (s Series) UpDown(n int, tolerance ...float64) Series

UpDown returns a series of numbers where each 2 bits represents an up bar (2), a down bar (1), or a flat bar (0), for the preceding n bars. Optionally, a tolerance (in the form of value that represents a percentage) may be provided. For example, a tolerance of 5 dictates that a value must be 5% higher/lower than its predecessor to register as an up/down. The maximum number of values to look back to is 24.

UpDownString

func (s Series) UpDownString(n int, tolerance ...float64) []string

UpDownString returns a string slice representing whether the last n values, when compared with the previous value, were up (“U”), down (“D”), or flat ("-"). Optionally, a tolerance (in the form of value that represents a percentage) may be provided. For example, a tolerance of 5 dictates that a value must be 5% higher/lower than its predecessor to register as an up/down. The maximum number of values to look back to is 24.

UpDownSum

func (s Series) UpDownSum(n int, tolerance ...float64) Series

UpDownSum returns a series which is a sum of +1 values for each bar that was higher than the previous bar and -1 for each bar that was lower than the previous bar, for n bars. For example, if n is 6 and 4 bars are higher than their previous, 1 is equal, and 1 is lower, the value at that bar would be +3. Optionally, a tolerance (in the form of value that represents a percentage) may be provided. For example, a tolerance of 5 dictates that a value must be 5% higher/lower than its predecessor to register as an up/down.

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”).

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.

NOTE: This is currently too slow to be used. Need to revisit it.

FTIAt

func (s Series) FTIAt(period, halfLength, lookback int, beta, noiseCut float64) Series

FTIAt returns the FTI at a specific fixed period.

FTILog

func (s Series) FTILog(minPeriod, maxPeriod, halfLength, lookback int, beta, noiseCut float64) Series

FTILog is identical to FTI but operates in log-price space.

FTIPeriod

func (s Series) FTIPeriod(minPeriod, maxPeriod, halfLength, lookback int, beta, noiseCut float64) Series

FTIPeriod returns the optimal cycle period at each bar.

Regime Detection

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.

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).

Hurst Exponent

Hurst

func (s Series) Hurst(n int) Series

Hurst calculates the Hurst coefficient. This implementation uses a single-scale R/S calculation at window size n, whereas the traditional Hurst estimation performs R/S analysis across multiple window sizes and derives the Hurst exponent from the slope of a linear regression of log(R/S) vs log(n). Additionally, this implementation includes an Anis-Lloyd correction factor (k = sqrt(pi/2)) which is not part of the classic R/S method and uses population standard deviation instead of sample standard deviation. The single-scale approach provides a computationally efficient rolling estimate but may be less robust than the multi-scale regression method, which better captures the fractal nature of the series by examining how R/S scales across different time horizons.

Efficiency Ratio

EfficiencyRatio

func (s Series) EfficiencyRatio(n int) Series

EfficiencyRatio calculates the Kaufman Efficiency Ratio for a specified length n on a series.

Statistics

RMS

func (s Series) RMS(n int) Series

RMS returns the root-mean-square of n values.

StdDev

func (s Series) StdDev(n int) Series

StdDev returns the standard deviation of each n values.

ZScore

func (s Series) ZScore(avgLen int, val float64) Series

ZScore returns the Z-score of a value. The Z-score is a statistical measure used to determine how many standard deviations a value is from the mean.

R-Squared

R2

func (s Series) R2(n int) Series

R2 computes a least-squares regression on the last values at each point in the series. Where there are insufficient values, the result is zero.

Spearman Rank Correlation

SpearmanRankCorrelation

func (s Series) SpearmanRankCorrelation(n int, s2 ...Series) Series

SpearmanRankCorrelation calculates the Spearman Rank Coefficient (correlation) between two series. If a second series is passed in as a parameter, the first series is ranked against this second one. If no second series is provided, the second series is a sorted (low to high) copy of the first series, which provides an indication of the strength of a trend (since the series is being ranked against itself in ascending order).

Fisher Transform

Fisher

func (s Series) Fisher() Series

Fisher implements the Fisher Transform. It expects its input values to be between -1 and 1.

FisherInverse

func (s Series) FisherInverse() Series

FisherInverse implements the Inverse Fisher Transform, resulting in a series of output values between -1 and 1.

Gaussian Distribution

Gaussian

func (s Series) Gaussian(mean, variance float64) Series

Gaussian implements the Gaussian distribution.

Random

Rand

func (s Series) Rand(factor float64) Series

Rand modifies each element x by a pseudo-random number in the half-open range [-0.5, 0.5) multiplied by the provided factor. It can be used to generate a random walk of values. TODO – Think about whether to leave the first value unchanged?

RandNorm

func (s Series) RandNorm(n int, factor float64) Series

RandNorm modifies each element x by a normally-distributed pseudo-random amount based on the distribution of the previous n values. If n > 0, the first n-1 values in the series will be unmodified (since we need n values to determine the mean and standard deviation). If n <= 0, we sample the whole range to determine the mean and standard deviation to apply.

Clamp

Clamp

func (s Series) Clamp(low float64, high float64) Series

Clamp returns a value no lower than the specified low value and no higher than the specified high value. If the value provided is between low and high, it is returned unchanged.

Velocity / Acceleration

AvgAcceleration

func (s Series) AvgAcceleration(length int, smoothLength int) Series

AvgAcceleration implements the acceleration component of Scott Cong’s Velocity And Acceleration indicator (as described in TASC September 2023).

AvgVelocity

func (s Series) AvgVelocity(length int, smoothLength int) Series

AvgVelocity implements the velocity component of Scott Cong’s Velocity And Acceleration indicator (as described in TASC September 2023).

QStick

QStick

func (s Series) QStick(o, c Series, length int) Series

QStick implements Tushar Chande’s Qstick momentum indicator.

Ulcer Index

Ulcer

func (s Series) Ulcer(n int) Series

Ulcer calculates the Ulcer Index on the provided series over an n-period term.