Navigation: Realtest Script Language > Formula Syntax > Formula Evaluation

The RealTest formula evaluator works like a "virtual machine". Each formula in the script is compiled to a binary format and pre-processed. The repeated evaluation that occurs during a test is therefore as efficient as possible.

One way in which evaluation is optimized is known as "short circuit". If it becomes known before evaluation is finished that there is only one possible result, the remainder of the evaluation process is skipped.

For example, in the pseudo-expression "0 and this and that and the other thing", nothing after the 0 would be evaluated, because it is logically impossible for an expression (or sub-expression) with "0 and …" to be anything other than 0. Ditto with "1 or …", "0 * …", "0 / …", etc.

You can see this short-circuit in action if you experiment with some formulas in Debug Panel with "show evaluation" checked.

You can then use this knowledge of how formulas are evaluated to make your tests run even faster, by putting the most-likely-to-be-false terms at the beginning of your conditional formulas.

The best place to take advantage of short-circuit efficiency is in the Data section and in your EntrySetup formula.

For example, say you have a multi-part EntrySetup concept, such as:

price between 10 and 80

20-day average volume at least 100K

price above its 200-day moving average

price down 3 days in a row

You could write this as:

C > MA(C,200) and MA(V,20) >= 100000 and CountTrue(C < C[1], 3) == 3 and C > 10 and C < 80

or you could write the same logic as:

C > 10 and C < 80 and CountTrue(C < C[1], 3) == 3 and MA(V,20) >= 100000 and C > MA(C,200)

In the first example, the 200-day moving average will have to be calculated for every stock in your database for every date in your backtest. Each of these calculations will require going back 200 bars from the current bar, adding all the closes, and then dividing the sum by 200. RealTest can actually perform these millions of lookups and calculations remarkably quickly, but your tests will run a lot faster if you write your formulas like the second example.

In the second example, formula elements are written in order of calculation speed. Because of short-circuit optimization, all of the preceding comparisons will have to be true in order for it to remain necessary to calculate the 200-day moving average. You can make an educated guess about which formula elements take the longest to calculate from the lookback length - how many bars back it must go to calculate its value for each bar.