> ## Documentation Index
> Fetch the complete documentation index at: https://docs.0xarchive.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Statistics and machine learning (stats, ml)

> Rolling statistics, regression that learns bar by bar, Kalman filters, PCA, walk-forward PCA regression and forward labels, matching pandas, numpy and statsmodels.

Instances like `ta.*`: create at the top level, update once per bar, and they roll back with the forming bar. A bar with `na` in an input returns `na` and leaves the window or model as it was. The oracle is pandas, numpy and statsmodels, so variance divides by n − 1 (pandas' default), where `ta.stdev` divides by n as TradingView does.

## stats

**zscore()** `(length: number, options?: \{ clip?: number \}): Average`

(value − mean) / standard deviation over the last `length` values; `clip` caps it either way.

**corr()** `(length: number): Indicator\<[a: number, b: number], number\>`

Pearson correlation of `a` and `b` over the last `length` pairs, −1 to 1.

**cov()** `(length: number): Indicator\<[a: number, b: number], number\>`

Sample covariance (n − 1) of `a` and `b` over the last `length` pairs.

**beta()** `(length: number): Indicator\<[y: number, x: number], number\>`

Slope of `y` on `x` over the window: cov(y, x) / var(x).

**skew()** `(length: number): Average`

Skew, pandas' adjusted Fisher-Pearson: 0 for a symmetric window.

**kurt()** `(length: number): Average`

Excess kurtosis, pandas' unbiased: 0 for a normal distribution.

**quantile()** `(length: number, q: number): Average`

The `q` quantile (0 to 1) of the window, interpolated linearly as pandas does.

**median()** `(length: number): Average`

**autocorr()** `(length: number, lag?: number): Average`

Correlation of the window with itself `lag` values back (default 1), as pandas' `Series.autocorr`.

**ewmVar()** `(halfLife: number): Average`

Exponentially weighted variance by half-life in bars, as pandas' `ewm(halflife).var()`.

**ewmCov()** `(halfLife: number): Indicator\<[a: number, b: number], number\>`

**ewmCorr()** `(halfLife: number): Indicator\<[a: number, b: number], number\>`

**vol()** `(length: number, estimator?: VolEstimator, options?: \{ annualize?: boolean \}): Indicator\<[bar: BarView], number\>`

Volatility per bar over `length` bars from each bar's prices: `close` (log returns, the
default), `parkinson` (high and low), `garmanKlass`, `rogersSatchell` or `yangZhang` (with
the gap from the previous close). `annualize` scales by the bars in a 365-day year.

## VolEstimator

```ts theme={"theme":"github-dark"}
type VolEstimator = 'close' | 'parkinson' | 'garmanKlass' | 'rogersSatchell' | 'yangZhang';
```

## ml

**ols()** `(length: number, inputs: number, options?: \{ intercept?: boolean; ridge?: number \}): Regression`

Least squares over the last `length` bars, from `inputs` x values per bar. `ridge` penalises
the coefficients (not the intercept) to keep the fit stable when inputs move together.

**rls()** `(inputs: number, options?: \{ forget?: number; intercept?: boolean; ridge?: number \}): Regression`

Recursive least squares: every bar so far, each older bar weighted `forget` times less (1, the
default, weighs all alike). The same estimates as the closed-form weighted ridge solution.

**kalman()** `(options?: \{ processVar?: number; noiseVar?: number \}): Indicator\<[z: number], LevelValue\>`

A Kalman local-level filter: a smoothed value with its uncertainty. Only the ratio of the two
variances moves the level; set `noiseVar` to the noise in the data to read `variance` in its units.

**kalmanBeta()** `(options?: \{ delta?: number; noiseVar?: number \}): Indicator\<[y: number, x: number], HedgeValue\>`

A hedge ratio that drifts with time, y = α + βx: the standard pairs-trading filter, by default `delta` 1e-4 and `noiseVar` 1e-3.

**forward()** `(horizon: number, inputs: number): Indicator\<[x: readonly number[], price: number], ForwardValue | null\>`

Inputs held `horizon` bars and handed back with the log return of `price` since, once it
exists; `null` until then. Train on what it returns, and a model never sees the future.

**pca()** `(inputs: number, options?: \{ window?: number; components?: number; standardize?: boolean; refit?: number | 'auto' \}): Indicator\<[x: readonly number[]], PcaValue\>`

Principal components of the last `window` (default 500) lists of `inputs` numbers, exact,
recomputed every `refit` closed bars and held in between. `'auto'`, the default, refits every
bar up to 20 inputs and less often above, to keep the cost near 20 inputs'. `components`
defaults to 3; `standardize` works on correlations instead of covariances.

**pcr()** `(inputs: number, options?: \{ window?: number; components?: number; standardize?: boolean; refit?: number | 'auto'; intercept?: boolean; quantiles?: readonly number[] \}): PcaRegression`

Principal component regression, walk-forward: every `refit` labelled pairs on closed bars,
once `window` (default 500) are in, the components of x and the regression of y on them are
fitted together on the window, then frozen until the next refit, centre and scale included.
Feed it pairs from `ml.forward`. `quantiles` (up to 8, 0 to 1) asks for quantiles of the fit's
in-sample predictions. Other options as `ml.pca` and `ml.ols`.

## RegressionValue

**coef** `readonly number[]`

**intercept** `number`

`na` for a model made with `intercept: false`.

**r2** `number`

**fitted** `number`

The estimate of y from this bar's x, by what the model had learned before this bar.

**residual** `number`

y less `fitted`: an out-of-sample error.

**t** `readonly number[]`

t-statistics of the coefficients, assuming independent errors. They overstate significance
when labels overlap, such as 12-bar forward returns sampled every bar.

**n** `number`

Bars learned: the window's count for `ols`, every bar so far for `rls`.

## Regression

**predict()** `(x: readonly number[]): number`

The estimate of y for `x` from what the model has learned so far. Doesn't learn.

## LevelValue

**level** `number`

**variance** `number`

**innovation** `number`

This bar's value less the level before it.

**z** `number`

The innovation in standard deviations.

## HedgeValue

**alpha** `number`

**beta** `number`

**spread** `number`

y less α + βx, by the estimates before this bar: the spread a pairs trade watches.

**spreadZ** `number`

## ForwardValue

**x** `readonly number[]`

The inputs from `horizon` bars ago.

**ret** `number`

The log return of `price` since then.

## PcaValue

**explained** `readonly number[]`

Share of variance each component explains, largest first.

**scores** `readonly number[]`

This bar's input on each component, by the components as of the last refit. What a model learns from.

**loadings()** `(c: number): readonly number[]`

Loadings of component `c` (0 is the first), one per input; each component's largest loading is positive.

**residual()** `(i: number): number`

The part of input `i` this bar the components don't explain, in the units PCA works in (standardised with `standardize`).

**residualZ()** `(i: number): number`

The residual over its standard deviation in the window, as of the last refit.

## PcrValue

**coef** `readonly number[]`

**intercept** `number`

The mean of y in the window; `na` for a model made with `intercept: false`.

**r2** `number`

In-sample R² of the last fit.

**explained** `readonly number[]`

Share of the inputs' variance each component explains, largest first.

**quantiles** `readonly number[]`

The `quantiles` asked for, of the last fit's predictions over its own window: thresholds the forecast is judged against.

**n** `number`

Pairs in the last fit.

**refitted** `boolean`

True on the bar the model refit.

**loadings()** `(c: number): readonly number[]`

Loadings of component `c` (0 is the first), one per input; each component's largest loading is positive.

## PcaRegression

**predict()** `(x: readonly number[]): number`

The estimate of y for `x` from the last fit; `na` before the first. Doesn't learn.

**scores()** `(x: readonly number[]): readonly number[]`

`x` on each component of the last fit, centred and scaled as the fit was.

## Next step

Continue with [Matrices (linalg)](https://docs.0xarchive.io/terminal/reference/linalg.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.