Get startedGet started for free

sigFormula

1. sigFormula

2. About sigFormula

The last signal function to introduce is sigFormula. Simply, this is a function that uses string evaluation to mix and match existing indicators and signals in order to form ensemble signals. For instance, in many trading systems, a signal (such as an oscillator signaling that the price has seen a sufficient pullback) will only be acted upon if it occurs in a favorable market environment (such as a 50-day simple moving average being above a 200-day simple moving average). For instance, in a market with falling prices, such as the U.S. equity market in 2008, prices were not simply seeing a temporary dip, but were in the process of a 55% drawdown. For those unaware, a drawdown is the largest peak to trough one has suffered. For instance, a strategy that starts off with a hundred dollars, makes fifty dollars, and then sinks back down to seventy five dollars would have a max drawdown of fifty percent. In such a massive market drawdown, when a long term trend is highly negative, entering into a contrarian position could risk large losses. In short, a contrarian trade should make sure it is buying a temporary pullback, and not a large decline.

3. Structure

To this end, the sigFormula function allows for exceptional flexibility in creating signals that are combinations of other signals. The way to use a sigFormula function is through calling it in the same way as sigComparison, sigCrossover, and sigThreshold functions. However, rather than having the arguments explicitly stated as arguments to the signal function, one passes in a logical string to the formula argument of sigFormula. If this seems daunting, it actually isn't. The statement passed to the formula argument of sigFormula is nothing more than the kind of argument one would write inside an if statement. For instance, if both statement 1 and statement 2 need to be true, then in base R, one would write if(statement_1 & statement_2). It's no different for the formula argument, aside from the text being a quote, and not needing the if statement and parentheses. I personally use it to combine signals, rather than indicators.

4. Example

In the example, you can see a very simple use case in that when longThreshold and longFilter both become TRUE, a signal called longEntry will display a TRUE output. Finally, sigFormula is one reason among others that it is so vital to have unique and descriptive labeling for your indicators and signals. In order to truly get the most flexibility out of features like sigFormula, quantstrat needs to be able to quickly find the indicator and/or signal columns you refer to.

5. Let's practice!

In the following exercises, you will build up your intuition about sigFormula, and then apply the sigFormula function itself. Good luck!