HighTick

A Faster Linear Regression Algorithm - LinearRegFast

Tradestation provides built-in linear regression functions LinearReg and LinearRegFC, which both use identical calculation algorithms except for the inclusion of the ExecOffset feature in the later function.

The FC suffix after a function name normally implies a fast calculation algorithm is being used. However, in the case of LinearReg and LinearRegFC, both are using same same algorithm, which has not been optimized for execution speed.

LinearRegFC contains the following code:

Fig 1. Original LinearRegFC Code

The area highlighted in yellow contains a loop and a summation that is performed with every new bar processed.

It is possible to optimize this section, replacing the loop and summation code with a simple addition/subtraction forumula, as shown in the optimized code:

Fig. 2. Improved LinearRegFaster Code

The loop and summation is only required for the initial bar processed, and also if the Length changes between calls to the function.

The improvement in execution speed of the LinearRegFaster code increases as the Length of the linear regression calculation becomes larger. A method version of the function extracts additional execution speed, as the method version bypasses the need to pass variables with each function call. The method version is similar to the speed of inline code, with the exception of a single branch and return instruction generated by the call to the Method. This call and return branch instruction results in negligible processesing overhead, while the Method structure keeps the code separate from the main program code and easier to maintain.

Code execution speed testing reveals the following relative speed of method LinearRegFast and function LinearRegFast compared to function LinearRegFC:

 Length LinearRegFC LinearRegFaster LinearRegFaster Method 20 1 2.5X 15X 200 1 16X 102X 1000 1 75X 987X

Table 1. Relative execution speeds of LinearRegFaster compared to LinearRegFC

Function LinearRegFast produces output identical to TS function LinearRegFC under all conditions.

Initial posted version: 11/03/12

Latest Update: 11/03/12

*.ELD files are compiled for TS 9.0 or later

All ELD and code text files packaged here:

LinearRegFaster.zip

The code may be visualized here:

Function LinearRegFaster

Method LinearRegFaster

Original TS Function LinearRegFC