Linear Regression

Technical Analysis Indicator: linreg

Fork me on GitHub

Function Prototype

/* Linear Regression */
/* Type: overlay */
/* Input arrays: 1    Options: 1    Output arrays: 1 */
/* Inputs: real */
/* Options: period */
/* Outputs: linreg */
int ti_linreg_start(TI_REAL const *options);
int ti_linreg(int size,
      TI_REAL const *const *inputs,
      TI_REAL const *options,
      TI_REAL *const *outputs);

Description

This documentation is still a work in progress. It has omissions, and it probably has errors too. If you see any issues, or have any general feedback, please get in touch.

The Linear Regression is a smoothing functions that works by preforming linear least squares regression over a moving window. It then uses the linear model to predict the value for the current bar.

It takes one parameter, the period n. Larger values for n will have a greater smoothing effect on the input data but will also create more lag.

It is calculated as:

$$\overline{x} = \frac{1}{n} \sum_{i=1}^{n} i$$
$$\overline{y}_{t} = \frac{1}{n} \sum_{i=0}^{n-1} in_{t-i}$$
$$\widehat{\beta}_{t} = \frac {\sum_{i=1}^{n}(i-\overline{x})(in_{(t-n+i)}-\overline{y}_{t})} {\sum_{i=1}^{n}(i-\overline{x})^{2}}$$
$$\widehat{\alpha}_{t} = \overline{y}_{t} - \widehat{\beta}_{t}\overline{x}$$
$$linreg_{t} = \widehat{\alpha}_{t} + \widehat{\beta}_{t} n$$

See Also

References

Example Usage

Calling From C

/* Example usage of Linear Regression */
/* Assuming that 'input' is a pre-loaded array of size 'in_size'. */
TI_REAL *inputs[] = {input};
TI_REAL options[] = {5}; /* period */
TI_REAL *outputs[1]; /* linreg */

/* Determine how large the output size is for our options. */
const int out_size = in_size - ti_linreg_start(options);

/* Allocate memory for output. */
outputs[0] = malloc(sizeof(TI_REAL) * out_size); assert(outputs[0] != 0); /* linreg */

/* Run the actual calculation. */
const int ret = ti_linreg(in_size, inputs, options, outputs);
assert(ret == TI_OKAY);

Calling From Lua (with Tulip Chart bindings)

-- Example usage of Linear Regression
linreg = ti.linreg(input, 5)

Example Calculation

period = 5

dateinputlinreg
2005-11-0181.59
2005-11-0281.06
2005-11-0382.87
2005-11-0483.00
2005-11-0783.6183.62
2005-11-0883.1583.72
2005-11-0982.8483.11
2005-11-1083.9983.56
2005-11-1184.5584.17
2005-11-1484.3684.60
2005-11-1585.5385.40
2005-11-1686.5486.21
2005-11-1786.8986.95
2005-11-1887.7787.85
2005-11-2187.2987.75

Chart

 

Other Indicators

Previous indicator: Lag

Next indicator: Linear Regression Intercept

Random indicator: Fisher Transform