These are notes complied from Howard B. Bandy’s excellent book: Mean Reversion Trading Systems.
The notes here are based on what is relevant to me and does not cover everything that is discussed in the book. In addition, I did not copy all the code examples (aka listings) in the book. If you are interested in any of the listings stated below and it is not hyperlinked, please refer to the book itself.
Chapter 1 – Introduction
- Create long only and short only systems. The parameters for long and short are not necessarily reverse of each other.
Chapter 2 – Development and Analysis
- Drawdown increases in proportion to the square root of holding period for individual trades and in proportion to the square root of the forecast period for system performance estimates
- Do not continue to trade a system that has entered a serious drawdown expecting that it will recover. It may recover on its own; it may require readjustment; or it may be permanently broken and never work again. Take it offline and either observe it until recent paper-trade results demonstrate that it is healthy again, or send it back to development.
Chapter 5 – Transformations
- The ideal indicator has a low value when percentage change ahead is negative and a high value when percentage change is positive. The relationship should be as linear as possible
- Bell curve = PDF of a normal distribution = derivative of the CDF
Transformation
Rescaling
- a linear transformation that keeps the proportional distance between any two data points unchanged, but changes the range of the input data to a different desired range
- (inputPt – inputMin)/(inputMax – inputMin) = (outputPt – outputMin)/(outputMax – outputMin)
- Listing 5.1
z transformation
- data are rescaled to a new mean and standard deviation
- new_value = [(old value – old mean) / (old SD)]* (new mean) + (new SD)
- Listing 5.2
out-of-range values
- to transform dataset with values outside an expected range
- can be done using one of the sigmoid functions below:
Logistic Function
y=\frac{1}{1+e^{-x}}
Softmax Function
y=\frac{1}{1+e^{-\alpha}}, \alpha=\frac{(x-\mu)*2\pi}{\lambda\sigma}
- lambda is user selected and reflects the number of standard deviations to be kept linear, lower lambda values leave more space for out of range values)
- Listing 5.3
Hyperbolic Tangent Function
y=\frac{e^{2x}-1}{e^{2x}+1}
Fisher Transformation
Stationarity
- Removing non-stationarities eases analysis and improves usefulness as an indicator
- Two transformations that improve stationarity
- Differencing
- a transformation whose output is the difference between data points
- if the magnitude of the data changes significantly through its range, dividing the difference by the price to produce a percent change is often useful
- Detrending
- compute a moving average of the raw data, then subtract that moving average from the raw data itself
- Listing 5.5 – Detrended Price Oscillator
- Listing 5.6 – Position In Range of Detrended Oscillator
- Listing 5.7 – Trading System based on PIRDPO
- Differencing
Performance of An Indicator
In order to examine the performance of an indicator, we compute the value of the indicator as of the close for every daily bar, and also the change in price ahead 1, 2, and 3 days.
- Use the PercentRank transformation function to linearize the distribution of the indicator (suppose this rank is called PRDV)
- Create a table using the Amibroker Explore functionality
- Sort the data elements by PRDV value.
- Create 20 equal size groups (known as vigintiles)
- For each vigintile, compute the average change in closing price 1, 2, and 3 days ahead
- For each number of days ahead, plot the % change for the entire period against the vigintile number
Does the line of best fit show the indicator working correctly as described by point 1 above regarding the ideal indicator.
That is: The ideal indicator has a low value when percentage change ahead is negative and a high value when percentage change is positive. The relationship should be as linear as possible
Miscellaneous
- Listing 5.9 – Program to compute an advance decline diffusion index and compute future performance (Very useful for exploration)
- DV2
- This is an indicator that compares the close with the average of the high and low
- y = (C / (0.5*(H+L)) – 1 DV(2) = MA(y, 2)
- Listing 5.8 – Generate DV2 Table based on steps described above
- Two potential trading systems
- Buy at the close of every day when the score of DV2 is in the bottom 20%, sell by the end of the third day
- Short at the close of everyday when the score of DV2 is in the top 30%, cover by the end of the third day
- Diffusion Index
- Composites formed from many individual results.
- A common diffusion index is the advance-decline index, where
DiffIndex = (AdvIss / (AdvIss + DecIss))
- Stochastic
- An indicator of the position of a single data point in relation to the range of values of that data
- Listing 5.10 – Replicate RSI using Two Series
- Listing 5.11 – Replicate using EMA
- Listing 5.12 – Demonstrate EMA’s Lambda
- Listing 5.13 – Allow Fractional Lookback Periods
- Listing 5.14 – Custom RSI Function
- Listing 5.15 – Trading System using Custom RSI
- Lambda is not linear. Valid range is 0.01 to 1.00.
- Values of lambda corresponding to short lookback RSI systems, such as RSI(2) are around 0.6 to 0.8.
- Lambda equal to 1.00 uses no smoothing
- Values above 1.00 are not meaningful.
- To replicate RSI(2) using Wilder’s moving average, use RSI(3) using exponential moving average, which corresponds corresponds to lambda of 0.5.
- Lambda is not linear. Valid range is 0.01 to 1.00.
Chapter 6 – Exits
AFL: https://smarttradingstrategies.com/afl-code-examples/#Testing_Exit_Strategies
The template for testing does the following
- Use a zig zag indicator to determine the ideal bottom to buy. Buy at the close of the day the ZZ indicator makes a bottom
- Also test what happens if the entry is early or late (e.g. 2 days before the indicator makes a bottom or 3 days after)
Exit using Indicators
Moving Average
Exit when C crosses above moving average
- best exit is a simple moving average with a lookback length between 5 and 8 days
- use longer lookback when the entry is early or late, shorter when it is accurate
- exponential moving average worked about as well as simple. Adaptive moving average performed poorly
RSI
Exit when RSI crosses above a predetermined level
- If you are three days early, RSI exit does not work well
- From 2 days early to 3 days late, a generally good exit is signalled when the 2 period RSI crosses up through 65 to 75, or when the 3 period RSI crosses up through about 60.
z-score
Exit when z score crosses above a predetermined level
- From 3 days early to 3 days late, a lookback length of 8 or 9 with z score crossing upward through 0 works well
- A lookback of 8 or 9 with a level about 1 works as well or better than crossing 0. In other words, hold the long position until the closing price has risen above the mean by 1 standard deviations.
Exit using holding period
- Can exit on first open, second open, second close, nth open, nth close, first profitable open, first profitable close etc
Profit Target
- If you are looking for a system that has a high percentage of winning trades, choose patterns that lead to trades that if allowed to exit at their maximum favourable excursion, MFE, would have profits about two times the profit target.
- If used at all, the profit target exit must be the reason for the exit enough times to be testable on its own
- Use profit targets when the potential trade is relatively small – less than about 2%
- Be as accurate on entry day as possible – the profit from hitting the exact bottom returns 4 to 10 times the profit from being one day early or late, and 10 or more times the profit of being two days early or late
- Size the profit target to the magnitude of the trade, trying to exit before the point of highest profit
- Be aware of intraday drawdown. Intraday drawdown increases as trades are held longer or as higher percentage gains are sought. For example, a 5% profit target based on 5% zigzag allow an intraday drawdown of 4.9%.
- Dynamic profit targets based on ATR does not work well
Trailing Exit
- Try using a small multiplier, say 1.5, and a short lookback, say 6 days with ATR trailing stops
- Or a small percentage, say 1%, for the fixed percentage version
Maximum Loss Exit
- Maximum loss exits hurt swing trading systems
Summary
- Set profit target so that it captures a reasonable portion of the profit potential of each trade, providing enough profit to cover commission and slippage and is hit often
- Set holding periods so that it exits trades that are unlikely to increase profit given longer holding
- Set a trailing exit to protect a substantial portion of maximum intra-trade profit
- To avoid maximum losses
- try a trailing exit even if your system uses daily bars. Exiting intraday will improve performance
- Avoid conditions that have high risk. Improve entries and use filters to identify favorable and unfavorable conditions
- set your position size so that you can afford the losses that occur in the tail of the distribution
- rather than trading the underlying, use debit options to take the positions
- If the trade cannot be entered at the exact bottom, it is usually better to be a day late than a day early – particularly try not to be more than two days early for swing trades
- Analyze the effect of taking additional positions. If you are in a long trade and the system gives another buy signal, the new signal is probably of higher quality and you should probably take it
Chapter 7 – Entries
AFL: https://smarttradingstrategies.com/afl-code-examples/#Different_Types_of_Entries
Four types of entry orders – Market on close, market on open, limit order, stop order
Market on Close
- author’s research shows that signals from a good system should be acted upon as soon as possible, about one third of the price change happens in the overnight market
- Many of the signals depend on the closing price, which can lead to a future leak. To overcome this
- use a real time data feed, note the price just before the close, perform the calculations, enter a market order or a limit-on-close order
- wait for the close, perform the calculations, trade in the afterhours market. Many ETFs and surrogates for them trade 15 min longer than regular hours
- Pre compute the price at which a signal will be generated. Place conditional orders to be executed if the closing price satisfies the conditions.
Next Day Open
- If you want to buy at the next day open and allow same bar exit, be certain to check the box “Allow same bar exit” on Backtester Settings > General tab.
Limit Order
- Enter a long position with a limit price below the current price
Stop Order
- Enter a long position with a stop price above the current price
Chapter 8 – Controlling Risk
Three methods of reducing risks
- use filters to help identify and avoid high risk conditions
- Understand the effect of position size and adjust it in accordance with risk and system performance (refer to Modeling Trading System Performance for a more thorough discussion)
- Take positions in options rather than in the futures, index or ETF the system is based on
Using Filters
AFL: https://smarttradingstrategies.com/afl-code-examples/#Filter_Testing
- Using ATR filter
- Use PercentRank to transform ATR into a linear like distribution with values between 0 and 100
- Trades are much less profitable when ATRPR value is in the range of 5 to 45. Reasonable to require ATRPR level to be 50 or higher to permit trades.
- The performance of the filtered system (using ATRPR levels) is superior to that of the unfiltered system
- Mean reversion systems work best in periods of high volatility
- Using Moving average filter
- The author concludes that longer length moving averages keep the system flat for very long periods and forgo many profitable trades. There are better filters than moving averages.
Options
- A test was done using the first ITM strike, closest option with at least 10 days before expiration. If the trade would be held past expiration, it would be either closed early or rolled to the next month (not applicable for the test results below)
- Losing trades. Although there were not many losing trades, those that did lost lost a high percentage, particularly when using options.
- Time to expiration. There was little decay for those trades held one or two days, but significant decay for those held ten or more days.
- Conclusion
- Use of first strike ITM option with 10 to 40 DTE increases beta by a factor of 15
- Limit the holding period to one or two days to limit premium
- When using debit option positions, your maximum loss is known at trade entry
- The number and size of losing trades continues to be the most significant factor in account growth
- Inconsistency in the profit and loss of individual trades limits position size and consequently limits growth of the account
Chapter 9 – Systems
Trading System Simulator
AFL: https://smarttradingstrategies.com/systems/#Three_Days_High_Low_Long
When coding a trading system simulator
- initialize the simulator
- using a loop, process all data bars:
- At the open:
- Process exits
- Process entries
- Update data
- Intra trade
- Process exits, worst first
- Process entries
- Update data
- At the close
- Process exits
- Process entries
- Update data
- At the open:
- decide which signals should be passed to Amibroker
Regime Change
AFL: https://smarttradingstrategies.com/afl-code-examples/#Regime_Change
- The regime change system has two sets of rules and parameters. Each set defines a model.
- At the close of each day, the recent performance of the systems is compared.
- The system whose equity has risen the most is identified as being dominant, and its signals are used as long as it continues to be dominant.
- If there is a new dominant system, exit any open positions unless there is a new buy signal from the new dominant system. If there is a continuing dominant system, follow its signals and ignore all others.
- The overall system, RegimeChange, is in one of three states
- State 0 – flat
- State 2 – Long, from a signal from system S2
- State 3 – Long, from a signal from system S3
Connors RSI Pullback
AFL: https://smarttradingstrategies.com/systems/#Connors_RSI_Pullback
- The system illustrates the following points:
- Define new indicators.
Streak Duration is defined as the umber of consecutive closes in the same direction. Individual days are given a score of -1, 0, or +1 depending on whether the close is lower, equal to, or higher than the previous close. Form a series that increments each day the close is in the same direction. When the direction changes, reset to -1, 0, or +1. - Apply transformations to indicators.
Computer the 2 period RSI of Streak Duration. - Combine indicators.
Compute the average of three indicators that are each bounded in the range 0 to 100. The three are RSI of close, RSI of Streak Duration, and Percent Rank of one day price change. The result is the ConnorsRSI indicator. - Use a limit order to enter a long position at a significant discount from the previous close.
- Define new indicators.
- When parameter values are set at the levels recommended by Connors, trading is very infrequent (less than one trade per issue per year). The accuracy is very high and the average gain per trade is very high. (I was not able to get any trade using the ETFs in my database)
- Due to the very high correlation among trades, you cannot use trades to determine risk, position size and profit potential. Instead, use changes in daily equity. When you do that, you will mark your equity to market every day, exposing intra-trade drawdown.
Dual Time Frame
AFL: https://smarttradingstrategies.com/systems/#Dual_Time_Frame
- The concept is to enter long trades when price is oversold on a short term basis, but not oversold on a longer time basis
- The system computes two indicators – RSI of daily bars and RSI of weekly bars
- To enter a long trade, require weekly RSI to be higher than some limit, suggesting that the issue is not oversold on a weekly basis, and daily RSI to be lower than some other limit, suggesting that it is oversold on a daily basis.
VIX
AFL: https://smarttradingstrategies.com/systems/#Trade_SPY_from_VIX
- Earlier, we had applied a zigzag indicator to the SPY price series and adjusted the percentage until we found the change that produced about 24 bottoms per year. We found that it ranged between 0.7% and 2.1% over the 13 year test period. Using the same technique on the VIX price series, we find that a zigzag with changes of about 7% result in about 24 bottoms per year.
- VIX is very mean reverting. Rises in VIX are associated with drops in SPY and vice versa.
Chapter 11 – It Doesn’t Work Anymore
To restore profitability when your system stops working:
- Rerun the validation – probably the walk forward runs. It will bring the logic and parameter values of the model back into sync with the data. If the out-of-sample results, particularly those of the most recent period, are profitable, the system can be returned to trading.
- Redesign the system to use finer resolution data. If you had been using only closing prices for daily bars, consider using daily open, high and low. OR perhaps prices for shorter time periods, say hourly bars.
- Redesign the system to enter and/or exit intra day. If the system had been trading on the close, consider pre-computing the price at which an intra-day signal would be generated, then use a limit order for execution. The action price can be pre-computed using root finding techniques (refer to QTS book)
- Redesign the system to use non-standard parameter values.
- Redesign the system using adaptive parameters (e.g. ATR instead of fixed percentage profit targets)
- Redesign the system to use non standard indicators.
- Redesign the system using different transformations. If an indicator has been ordinary position in range, such as the stochastic oscillator, consider using a different position in range indicator, such as percent rank.
- Redesign the system using more sophisticated ideas. Try consolidating indicators using PCA.
- Look for trading efficiencies, such as using limit orders instead of stop orders.
- Reduce frictional costs of slippage and commission
- Trade other markets, especially emerging markets that have more pricing inefficiencies.
- Closely monitor system health and adjust position size accordingly. Lower position size to reduce the size of the losses and do not increase leverage
- Use multiple time frames. Use longer time frames as filters to help distinguish between good and poor entries.
- Use auxiliary data. Use other data series, such as interest rate, volatility or commodity series as filters.
- Use diffusion index. Let the wisdom of the crowds help. Tally the number of advancing and declining issues from among the constituents of an index as an indicator.
- Use different models. If your system has been based on patterns of prices, look into models based on indicators, or seasonality.
- Prepare for the time when trading is no longer profitable.
Leave a Reply