BarsSince Function in EasyLanguage
Have you ever wondered how many bars have transpired since a certain condition was met? Some platforms provide this capability:
If ExitFlag and (c crosses above average within 3 bars) then
TradeStation provides the MRO (Most Recent Occurrence) function that provides a very similar capability. The only problem with this function is that it returns a -1 if the criteria are not met within the user provided lookback window. If you say:
myBarsSinceCond = MRO(c crosses average(c,200),20,1) < 3
And c hasn’t crossed the 200-day moving average within the past twenty days the condition is still set to true because the function returns a -1.
I have created a function named BarsSince and you can set the false value to any value you wish. In the aforementioned example, you would want the function to return a large number so the function would provide the correct solution. Here’s how I did it:
And here’s a strategy that uses the function:
The function requires four arguments:
- The condition that is being tested [e.g. rsi > crosses above 30]
- The lookback window [rsiLen – 14 bars in this case]
- Which occurrence [1 – most recent; 2- next most recent; etc…]
- False return value [999 in this case; if condition is not met in time]
A Simple Mean Reversion Using the Function:
Here are the results of this simple system utilizing the function.
Optimization Results:
I came up with this curve through a Genetic Optimization:
The BarsSince function adds flexibility or fuzziness when you want to test a condition but want to allow it to have a day (bar) or two tolerance. In a more in-depth analysis, the best results very rarely occurred on the day the RSI crossed a boundary. Email me with questions of course.
Discover more from George Pruitt
Subscribe to get the latest posts sent to your email.