Quantcast
Channel: Indicators – System Trader Success
Viewing all 40 articles
Browse latest View live

The Internal Bar Strength Indicator

$
0
0

The internal bar strength or (IBS) is an oscillating indicator which measures the relative position of the close price with respect to the low to high range for the same period.

The calculation for Internal Bar Strength is as follows…

IBS =  (Close – Low) / (High – Low) * 100;

For example, on 13/01/2016 the QQQ etf had a high price of $106.23, a low price of $101.74 and a close price of $101.90.

The value of IBS would be calculated as …

(101.90 – 101.74) / (106.23 – 101.74) * 100 = 3.56

Low IBS readings show that a market has closed near the lows of the day, high IBS readings show that a market has closed near the highs of the day.

The following image shows the IBS indicator plotted beneath the price series.

IBS-1-630x315

Testing the Internal Bar Strength Indicator

The test period is between 01/01/2005 and today. $100,000 hypothetical starting balance, with 100% of available equity invested per position. Commissions are $0.01 per share and there is a minimum cost per trade of $1.00.

Tests are carried out using Amibroker and the data is provided by Norgate Premium.

These are the Strategy rules:

  • If IBS < 10
  • Buy the close
  • Exit at close if price > previous day high.

QQQ Results

  • No. of trades = 199
  • % of Winners = 72.36%
  • Average P/L% per trade = 0.62%
  • Average hold time = 4 days
  • Annualized return = 11.32%
  • Maximum draw-down = -16.14%
  • CAR/MDD = 0.70
  • Exposure = 28.47%

The monthly breakdown of returns is as follows…

Internal-Bar-Strength-QQQ-Performance-1

One common trait among many of these types of mean-reversion systems is that they seem to perform best during volatile markets.

To illustrate the point, I added a filter to the above strategy which only allows us to buy QQQ if the VIX has closed above the value of it’s previous 10-day MA.

Adding the VIX filter improved the win-rate %, average profit % per trade, and annual % return of the strategy.

Here are the results…

  • No. of trades = 158
  • % of Winners  = 75.32%
  • Average P/L% per trade = 0.85%
  • Average hold time = 4 days
  • Annualized return = 12.46%
  • Maximum draw-down = -14.83%
  • CAR/MDD = 0.84
  • Exposure = 22.3%

The Equity curve and monthly breakdown of returns are as follows…

Internal-Bar-Strength-and-VIX

Combining the Internal Bar Strength Strategy with a Trend-Following Strategy

Finally, I wanted to see whether combining a trend-following strategy with the Internal Bar Strategy could improve the risk-adjusted returns of either stand-alone strategy.

The trend following strategy is as follows…

  • Buy the SPY when the Close > upper Bollinger Band (C,200,1);
  • Sell the SPY when the Close < lower Bollinger Band (C,200,1);

Since 2005, this strategy has the following performance metrics:

  • No. of trades = 5
  • % of Winners  = 80%
  • Average P/L% per trade = 19.17%
  • Average hold time = 425 days
  • Annualized return = 7.37%
  • Maximum draw-down = -14.17%
  • CAR/MDD = 0.52
  • Exposure = 76.25%

The Equity Curve and monthly breakdown of returns are as follows…

SPY-trend-Following

For the Final test, QQQ is traded using the Internal Bar Strength (IBS) strategy and SPY is traded using the above trend-following (TF) strategy.

The first test will allocate 70% of available equity to the SPY strategy and 30% of available equity to the QQQ strategy. Further tests will use different capital allocations.

Because the SPY can sometimes be held for a long period, it is necessary to periodically rebalance the size of open SPY positions. For the following tests the rebalance frequency will be monthly and the rebalance threshold will be 2%.

70%TF / 30%IBS. Results

  • No. of trades = 163
  • % of Winners  = 75.46%
  • Average P/L% per trade = 1.39%
  • Average hold time = 18 days
  • Annualized return = 9.01%
  • Maximum draw-down = -11.45%
  • CAR/MDD = 0.86
  • Exposure = 60.23%

60%TF / 40%IBS. Results

  • Annualized return = 9.53%
  • Maximum draw-down = -11.09%
  • CAR/MDD = 0.86
  • Exposure = 54.76%

50%TF / 50%IBS. Results

  • Annualized return = 10.04%
  • Maximum draw-down = -10.98%
  • CAR/MDD = 0.91
  • Exposure = 49.35%

40%TF / 60%IBS. Results

  • Annualized return = 10.55%
  • Maximum draw-down = -10.93%
  • CAR/MDD = 0.97
  • Exposure = 43.95%

30%TF / 70%IBS. Results

  • Annualized return = 11.05%
  • Maximum draw-down = -10.87%
  • CAR/MDD = 1.02
  • Exposure = 38.51%

The above results illustrate that combining both a trend-following strategy and a mean-reversion strategy within your portfolio has been a useful method for improving risk-adjusted returns.

For context, the IBS strategy when traded alone produced a maximum draw-down of 14.83% and a CAR/MDD of 0.86.

The Trend-following strategy produced a maximum draw-down of 14.17% and a CAR/MDD of 0.52.

The combined strategy portfolio with a 30% TF and 70% IBS allocation produced a maximum draw-down of 10.87% and a CAR/MDD of 1.02.  This is superior to either strategy if traded alone.

The equity curve and monthly breakdown of returns for the 30% TF / 70% IBS portfolio are as follows…

Combining-trend-folloiwng-with-Mean-Reversion-2

*Update: As some readers have correctly pointed out, trading on the close when an indicator requires the closing price to be calculated is not necessarily straight forward. With that said, I have included further tests below whereby the trades are executed on the open of the day which follows the signal.

The IBS strategy does not perform as well, but the main point of the article (that combining mean-reversion with trend-following can be beneficial) is still valid.

QQQ Results (Enter on open of day which follows signal)

  • No. of trades = 197
  • % of Winners  = 70.05%
  • Average P/L% per trade = 0.49%
  • Average hold time = 4 days
  • Annualized return = 8.69%
  • Maximum draw-down = -15.99%
  • CAR/MDD = 0.54
  • Exposure = 22.04%

QQQ Results with VIX Filter (Enter on open of day which follows signal)

  • No. of trades = 157
  • % of Winners  = 73.89%
  • Average P/L% per trade = 0.64%
  • Average hold time = 4 days
  • Annualized return = 9.15%
  • Maximum draw-down = -16.10%
  • CAR/MDD = 0.57
  • Exposure = 17.26%

SPY Trend-Following Results  (Enter on open of day which follows signal)

  • No. of trades = 5
  • % of Winners  = 80%
  • Average P/L% per trade = 18.87%
  • Average hold time = 425 days
  • Annualized return = 7.24%
  • Maximum draw-down = -14.15%
  • CAR/MDD = 0.51
  • Exposure = 76.06%

Combined Portfolio (70%IBS / 30%TF)  (Enter on open of day which follows signal)

  • No. of trades = 162
  • % of Winners  = 74.07%
  • Average P/L% per trade = 1.19%
  • Average hold time = 17 days
  • Annualized return = 9.90%
  • Maximum draw-down = -11.47%
  • CAR/MDD = 0.86
  • Exposure = 35.47%

The equity curve and monthly breakdown of returns for the 70% IBS / 30% TF portfolio are as follows…

Combining-trend-folloiwng-with-Mean-Reversion-3

— By Llewelyn of Backtest Wizard

The post The Internal Bar Strength Indicator appeared first on System Trader Success.


The MVCI (Whatever That Means) Indicator

$
0
0

Some people tell me that I have “too much time on my hands” because I spend so much time “crunching numbers”. I tell them, “That’s ridiculous, I don’t have any time on my hands because I am so busy crunching numbers”. (That usually shuts them up. At least for a little while).

In any event it is true that I am something of an “indicator junkie”. And it is also true that sometimes I multiply two numbers together (or divide two numbers) just “because I can”. And every once in awhile something potentially valuable seems to surface (see Applying VIX(like) Indicators to Stocks).

But in the most recent case I am hoping that someone can help me here. Not so long ago, I came across an indicator referred to by the acronym of MVCI – or at least that’s what I recorded it as. I just can’t remember where I read about it. In fact I don’t even recall what MVCI stands for.

But I like what I’ve seen of it so far.

The MVCI Indicator Calculations

OK, what follows is a list of a fairly lengthy set of calculations. If you are not a “numbers geek” you might consider skipping down to the actual results.

A = Daily High

B = Daily Low

C  = Daily Close

D = 200-day moving average of daily closing prices

E = Daily True High (Today’s high or yesterday’s low, whichever is greater)

F = Daily True Low (Today’s low or yesterday’s high, whichever is lower)

G = Daily True Range (E-F)

H = Average Daily Price (A + B) / 2

I  = 15-day Average of H

J = 15-day Average of G

K = MVCI = (C-I) / (J * Square Root of 2))

L = Buy Signal Cutoff Value

M = # days to hold a long position

Figure 1 displays an Excel spreadsheet with these calculations.

Figure 1 – Excel spreadsheet for MVCI (whatever that means) Indicator

Figure 1 – Excel spreadsheet for MVCI (whatever that means) Indicator

Hmmm, maybe I do have too much time on my hands. But I digress. In (slightly long-winded) English, the indicator is calculated by:

1) Subtracting the 15-day average of the average daily price (defined as ([high]+[low]/2)) from today’s closing price, and dividing that result by;

2) The 15-day average of the Average True Range times the square root of 2

Don’t ask me how someone came up with multiplying something by the square root of 2 because, well, heck I don’t even know what MVCI stands for, so how would I know?

The default value for variable L is -0.51. The default value for M is 22 days.

A “Buy Signal” occurs when:

1) The closing price for SPY is above its 200-day simple moving average AND;

2) The MVCI value for that day is -0.51 or less. So when a buy signal occurs the trader buys SPY and holds it for 22 trading days.

If MVCI drops below -0.51 during these 22 days then the 22-day holding period starts again at 22, i.e., positions can be held for longer than 22 days.

Figure 2 displays the fluctuations of the MVCI since 12/31/2012 with the -0.51 level highlighted in red.

Figure 2 – The MVCI (whatever that means) indicator in action

Figure 2 – The MVCI (whatever that means) indicator in action

So in a nutshell, anytime SPY is above its 200-day moving average each day the MVCI is below -0.51 starts a 22-day holding period.

Crazy, right?

Well, maybe we should consider the results first.

The Results

OK, so SPY started trading in 1997, to get a 200-day moving average we can start testing in June of 1998. If we start with $1,000 and invest in SPY for 22 trading days following any day where MVCI drops to -0.51 or below, we get the equity curve that appears in Figure 3. No interest is earned while out of the market and buying and holding SPY is also plotted in red.

Figure 3 – Growth of $1,000 using MVCI (blue) versus Buying and Holding SPY (red); 1998-2015

Figure 3 – Growth of $1,000 using MVCI (blue) versus Buying and Holding SPY (red); 1998-2015

For the record:

-$1,000 invested in SPY using MVCI in the manner described here grew to $4,417 (+342%)

-$1,000 invested in SPY on a buy-and-hold basis grew to $1,848 (+84.8%)

Maybe not so crazy, right?

Summary

For the record, please note that I do not actually use this indicator at the moment in any of my trading, nor am I recommending that you start using it either. I have this rule – well, OK in the immortal words of Bill  Murray, “it’s more like a guideline” – that I don’t use indicators when I don’t even know what they’re freaking called.

But the purpose of this blog is not to offer “advice” or to tell you what to do. Its purpose is simply to educate you and give you something to think about that you might not otherwise.

Like for instance, “What the heck does MVCI mean?”

–by Jay Kaeppel from blog Jay On The Markets

The post The MVCI (Whatever That Means) Indicator appeared first on System Trader Success.

Looking Into The Ulcer Index

$
0
0

Investors utilize a variety of performance and risk metrics to evaluate strategies. These numbers provide a summary of what happened to the strategy historically and can be useful to quickly compare different strategies. To use these statistics effectively, it is helpful to look at some of the nuances of those frequently cited and cases where the information they provide could be misleading.

Many of the common metrics can be classified in ways that are similar to quantities we use to describe the world around us: temperature, speed, weight, voltage, etc. These classifications add context to what is being described based on how it is calculated and the information it contains.

In finance, one typical summary statistic is the annualized return of a strategy. To calculate this, all we need is the starting and ending point; what happened in between is irrelevant. Much like average speed simply uses the total time and distance traveled, annualized return smooths over any intermediate details. This is somewhat similar to a state variable in physics, such as temperature change, entropy, and internal energy, which depends only on the initial and final states.

If it were as simple as that, the two strategies shown below would be equivalent, but even a novice investor would likely choose to have owned strategy A.[1]
Equal-Return

 

Therefore, we look at metrics like annualized volatility, which incorporates the individual realized returns over a time period. We could call volatility a path dependent metric, much like mechanical work is in thermodynamics. It is a quantity that is likely to change if your “route” changes. However, annualized volatility only depends on what returns were realized, not in what order they came. This also applies to the Sharpe and Sortino ratios. To illustrate this concept, the following simulated paths both have the same realized volatility.

Same-Vol

To differentiate between these two strategies using summaries statistics, we must capture the sequence of the returns. Maximum drawdown does this by measuring the worst loss from peak to trough over the time period. Still, maximum drawdown lacks information about the length of the drawdown, which can have a substantial impact on investors’ perception of a strategy. In fact, Strategies B and C shown previously have the same maximum drawdown of 25%.[2]

Enter the Ulcer Index. It not only factors in the severity of the drawdowns but also their duration. It is calculated using the following formula:

Ulcer-Index1

where N is the total number of data points and each Ri is the fractional retracement from the highest price seen thus far. Whereas, the maximum drawdown is only the largest Ri, which can only increase through time, the Ulcer Index encapsulates every drawdown into one summary statistic that adapts to new data as it is realized.[3] Using the Ulcer Index, we can finally distinguish between strategies that have the same annualized return, annualized volatility, and maximum drawdown: Strategies B and C have Ulcer Indices of 11.2% and 12.8%, respectively.

As a case study, the following chart shows the return of a 60/40 portfolio of SPY and AGG rebalanced at the beginning of each year from 01/2004 to 12/2013. Along with the true realized path, I have included the path with the returns reversed and five paths with random permutations of the true returns.

60-40

The metrics for each path are shown in the table below:

Table

Only the Ulcer Index can fully differentiate among these paths. Even in cases where the maximum drawdown is similar (e.g. the true path and Random 1), the Ulcer Index shows a sharp contrast between the strategies.

For a more concrete way of picturing the Ulcer Index, imagine driving a car along a 55 mph speed limit road with stoplights spaced every half mile. Traffic is moderately heavy and the lights are poorly timed. As you accelerate, the light down the road turns yellow and then red. Easing off the accelerator will increase the time until you get to that light, perhaps to the point where you won’t have to stop, thus reducing the amount of time spent waiting for the light to change and the subsequent acceleration to approach the speed limit again.

You continue down the road anticipating the lights so that you do not brake when unnecessary or burn needless gas racing toward red lights. This not only reduces the variation in your speed (a volatility) but also the amount you have to slow down (the severity) and the time spent waiting at red lights (the duration). The smoother trip is likely to lead to less stress, not to mention wear and tear on the car, which can cause further headaches.

Ultimately, evaluating a strategy involves more than simple performance metrics since the methodology driving the strategy is key. But when comparing historical performance, it is helpful to have a toolbox equipped with implements able to measure performance on the bases of profitability and risk in ways that are amenable to our inherent, risk-averse inclinations.

— By  Nathan Faber from Flirting With Models. Nathan Faber is an Associate in Newfound’s Product Development and Quantitative Strategies group. Newfound is a Boston-based registered investment advisor and quantitative asset manager focused on rule-based, outcome-oriented investment strategies and specializes in tactical asset and risk management.

[1] One exception is if you owned another strategy that had the correct characteristics relative to strategy B (negative correlation, positive return, and similar volatility) so that the overall return was even smoother than strategy A. Even so, these trends would not have any guarantee of continuing in the future.

[2] In simulations this is easy to do by reversing the order of the returns.

[3] Perhaps another interesting metric would be an exponentially weighted Ulcer Index that places more weight on more recent observations.

 

The post Looking Into The Ulcer Index appeared first on System Trader Success.

Capture The Big Moves!

$
0
0

Wouldn’t it be great to have an indicator to help tell you when we are in a major bull or bear market? Imagine if you had a clear signal to exit the market on January 19, 2008 before the major market crash. Then the same indicator told you when to get back into the market on August 15, 2009. Such an indicator would have also gotten you out of the market during the dot-com crash on November 11, 2000. Well, this indicator I’m going to talk about does just that.

Below you will also find the EasyLanguage code for this indicator. This major trend indicator was inspired by an article entitled “Combining RSI With RSI” by Peter Konner, and it appears in the January 2011 issue of Technical Analysis of Stocks and Commodities.

How It Works

We are going to start with a well-known indicator: the Relative Strength Indicator (RSI). The goal is to identify major bull market and bear market regimes. In his article, Peter does this by simply using an RSI indicator on a weekly chart and identifying two unique thresholds. Peter noticed that during bull markets the RSI rarely goes below the value 40. On the other hand, during a bear market the RSI rarely rises above the value of 60. Thus, you can determine the beginning and ending of bull/bear markets when the RSI crosses these thresholds. For example, in the bear market during the financial crisis of 2008 the weekly RSI indicator did not rise above 60 until August of 2009.  This signaled the start of a new bull trend. The next bear trend will be signaled when the weekly RSI falls below 40. This is clear in the images just below. With these simple rules you are able to determine bull and bear markets with a surprising amount of accuracy given the S&P futures market.

The two images below show the SPY ETF on a weekly chart. Below the price is a second pane with a 12-period RSI. Why a 12-period RSI? I simply chose that number because it represents a quarter of a year of trading, if you figure four weeks in a month. There was nothing optimized about this number, it just seemed to be a logical starting point. Other lookback values will produce very similar results.

In the image below (click to enlarge) you will see the RSI signal stays above the 40 level during the strong bull market of the 1990’s.

RSI In Bull Market Does Not Go Below 40 Often - Relative Strength Indicator

RSI In Bull Market Does Not Go Below 40 Often.

In the image below (click to enlarge) you will see the RSI signal stays below the 60 level during the strong bear market in the financial crisis of 2007-2009.

RSI In Bear Market Does Not Often Rise Above 60

RSI In A Bear Market The Does Not Often Rise Above 60

As you can see the RSI appears to do a fairly decent job of dividing the market into bull and bear regimes. You will also notice the RSI indicator paints red when it goes below 40 and only returns to a light blue when it rises above 60. It is these critical thresholds which highlight a significant turning point in the market that may be occurring.

Modifying RSI

I personally found the RSI signal a little choppy. I decided to make two modifications to help smooth the raw RSI signal. First, the input into the RSI indicator was modified by taking the average of the high, low, and close. The RSI value is also smoothed with a 3-period exponential moving average. The resulting EasyLanguage code looks like this:

RSI_Mod = RSI( (c+h+l)/3, RSI_Period );
Signal = Xaverage( RSI_Mod, 3 );

These two modifications will smooth out our RSI signal line. Next, I want to test the RSI lookback period. To do this I create a simple strategy using EasyLanguage. I open a long position when the RSI crosses above the 60 value and sell short when it crosses below the 40 value. The strategy is always in the market either going long or short. Just as a side note, the system I’m developing is not necessarily a trading system. Instead it’s an indicator to help determine the market regime: bull or bear. While I use the word “strategy”, it’s not a trading system.

Testing Lookback Periods

I’m curious to see how well this strategy holds up over various lookback periods. Ideally, the a strategy should be robust enough to produce solid results over a range of lookback periods. To test this aspect of the strategy I’m going to use TradeStation’s optimization feature to optimize the lookback period over the values 2-24.

The first chart is the lookback period (x-axis) vs the net profit (y-axis).

Click to see this performance report

Lookback Period vs Net Profit

 

The above chart shows rising profit as the lookback period increased from 5 to 17. Then it begins to fall off. Let’s look at this from a different angle: profit factor. The next chart is the lookback period (x-axis) vs the profit factor (y-axis).

Click here to see performance report - Relative Strength Indicator

Lookback Period vs Profit Factor

 

We see a similar picture but there is more of a stable region between 16-24. I would think that between these values we could find a good lookback period.  When I originally looked at this concept back in 2011, I picked 16 as a value. I don’t recall why I did that, but it’s certainly not an outline, and I’ve decided to continue to use this value for this article. If starting over from scratch, I may pick a value of 20, which is midway between 16 and 24. Feel free to experiment on your own. The main point here is this:  all the values produce positive results and a wide range of values at the upper end of our scale generate very good results (high profit factor and high profit). This leads me to believe that this indicator is robust in signaling major market changes.

Testing Environment

I decided to test the strategy on the S&P cash index going back to 1960. The following assumptions were made:

  • Starting account size of  $100,000.
  • Dates tested are from 1960 through September 2015.
  • The number of shares traded will be based on volatility estimation and risking no more than $5,000 per trade.
  • Volatility is estimated with a three times 20-week 40 ATR calculation. This is done to normalize the amount of risk per trade.
  • The P&L is not accumulated to the starting equity.
  • There are no deductions for commissions and slippage.
  • No stops were used.

Results

Applying this to the S&P cash index we get the following overall results.

Results

Notice the short side loses money. I would guess this tells us over the life of the market, there is a strong up-side bias. I would also guess that since 2000 the short side probably produces a profit, but I did not test that idea. Below is the equity curve of the strategy.

2016-07-18 Weekly RSI EQ Curve

 

Here is what the strategy looks like when applied to the price chart over the past few years. You will also notice I painted the price bars based upon the RSI signal. Light blue price bars mean we are in a bull market and red price bars mean we are in a bear market. You can clearly see how the RSI indicator defines the financial bear market and reenters at the start of the new bull market in 2009.

WSI_Weekly_New_Bull_2009- Relative Strength Indicator

Using this indicator we come up with the following turning points for major bull and bear markets for the US indices. The blowup of the dot-com bubble happened in 2000 and we got out in November 11, 2000. The indicator then tells us to go long on June 7, 2003. We then ride this all the way up to the financial crisis getting out of the market on January 19, 2008. Then on August 15, 2009 we go long. A failed signal occurred in mid 2011. Overall, not too bad!

How Can This Indicator Help You?

Looking at these dates we see that they are fairly accurate in capturing the major bull and bear regimes of the US stock indices. How can this be used in your trading? Perhaps you can use this as a basis for a long-term swing strategy. Maybe this is an indicator to let you know when to go long or  liquidate your positions within your 401(k) and other retirement accounts. Or perhaps if you are a discretionary trader you can use this to focus on taking trades in the primary direction of the the indicator. Maybe when the RSI indicator signals a bull market you may want to view this as another confirmation or green-light to pursue whatever investment strategy you prefer. Anyway, I thought it was an interesting and novel way looking at the RSI indicator.

Of course we only have 32 signals over the past 53 years. This is hardly a representative sample if we are talking about statistics. However, given the robust nature of the lookback period and the rising equity curve since 1960 this indicator may be worth keeping an eye on.

Where Are We Now?

This indicator signaled a Bull Market at the starting on the week of July 18th, 2016. The previous Bear signal was on August 29, 2015. This bear signal locked in some nice gains but ultimately turned out to be a false signal. Below is a chart with the most recent history of this indicator.

Long-Term Trend

2016-07-18 Weekly RSI

Download

TradeStation 9.1 ELD (strategy,indicators,paintbar)
TradeStation 9.1 WorkSpace
Strategy Code as Text File

The post Capture The Big Moves! appeared first on System Trader Success.

Down Days Trading Model

$
0
0

I’ve written a lot about the 2-period RSI indicator popularized by Larry Connors and Cesar Alvarez. This indicator highlights significant pullbacks which can often be buying opportunities within major market indexes like the S&P.  Pullbacks in the market are a result of the market closing down. That means, today’s close is lower than the open. So, can this simple price action be used to locate buying opportunities. In this article I’m going to take a look at this price pattern and compare it to our the 2-period RSI setup. Free EasyLanguage code will be provided at the conclusion of this article.

Mean Reversion

As a reminder, the traditional two-period RSI indicator (RSI(2)) is an indicator we have used many times on this website. So I will not spend much time talking about it within this article. Overall, it’s primarily used on the stock index markets such as the S&P, as a method to determine an entry point for a mean reverting trading models. You can read more about the RSI(2) indicator and the trading models built from it by reviewing these articles:

 Down Days Setup

I’m going to use EasyLanguage in order to build a trading model to test the effectiveness buying the S&P after two consecutive down days. To build this simple trading model I’m going to assume that a down day is defined when the market closes below its open. I’ll sell the position when we have just the opposite condition, two consecutive up days. That is, two days when the market closes above its open.

The trading rules are:

  • Buy at the open of next day after two consecutive down days
  • Sell at the open of next day after two consecutive winning days

The EasyLanguage code for the basic strategy will look something like this:

Variables:
BuySignal(false),
SellSignal(false);
BuySignal = ( Close < Open ) And ( Close[1] < Open[1] );
SellSignal = ( Close > Open ) And ( Close[1] > Open[1] );
If ( BuySignal ) then Buy("LE") next bar at market;
If ( SellSignal ) then Sell("LX") next bar at market;

Testing Environment

Because you, the reader might want to build a trading model based upon this market study, I’m going to break the historical data into two portions. An in-sample portion and out-of-sample portion. I will perform my testing for this article on the in-sample portion only. Thus, when I’m finished with my testing we’ll still have a good amount of data which can be used for out-of-sample testing.

Before getting into the details of the results, let me say this: All the tests within this article are going to use the following assumptions:

  • Starting account size of $25,000
  • In-sample dates are from 1998 through December 31, 2012
  • One contract was traded per signal
  • $30 was deducted per round-trip for slippage and commissions

Baseline Results

Below is the baseline results over our in-sample historical segment. The maximum drawdown is a percentage of our starting equity, which is $25,000. Keep in mind that this study has no stops, thus some positions will hold through some very deep pullbacks before exiting. Again, we are testing the behavior of the market buy building a trading model. In other words, we don’t have a complete trading system.

BaselineResults

Baseline_EQ_Curve

Longer Consecutive Losing Days

The first thing that I noticed when looking at two consecutive down days is it may not be deep enough. Two-day pullbacks are somewhat common.  Market pullbacks during the last few years of the study have been shallow and these have been great entry points. But what about helping to ensure this trading model will work under different conditions?  Testing three or four days consecutive losing days may generate more profitable and/or more tradable results. For past experience I know, in general, deeper pullbacks may provide a better profit vs risk. That is, the generated signals will be fewer in number but will also provide better rewards. So I modified the code and generated the following results based upon the number of consecutive down days required before opening a new position. During this testing I did not modify the exit rules. They remained the same with two consecutive up days acting as the exit trigger.

FourDayResult

As expected we see the number of trades decreases and the average profit per trade increases as we increase the number of down days. Deeper pullbacks happen less often, but have larger payouts based on our trading model. The four down days has only 85 trades so I’m going to use the three down days during the remainder of my testing. This is a good compromise as a three-day pullback does appear to eliminate many shallow and unproductive pullbacks. Below is the equity graph for the three down day trading model.

Baseline_3_Days_EQ_Curve

Bull/Bear Regime Filter

The next characteristic to explore is the difference between a bull and bear market. I’ll divide the market into two regimes based upon a 200-day simple moving average. The market will be “bullish” when price is trading above the 200-day SMA. The market will be “bearish” when price is below this moving average. Below is the trading model’s results in each regimes.

RegimeTest

Surprisingly, at least to me, we see better performance with the bear market. Overall, both the bull and bear regimes are profitable. The bear regime does suffer from larger drawdowns but it also has the biggest rewards. Notice that both regimes also have the same number of trades. I checked this a couple of times and it does appear to be correct. Given this result, I will not include a regime filter as we test our final modification I wish to test.

5-Day SMA Exit

The 5-Day SMA Exit closes a position once price closes above a 5-day simple moving average. This exit is often used with the RSI(2) system and it’s worth testing here as well. Below are the results of this test vs our baseline. As a reminder, the Baseline column represents the three down day trading model with a 2-day exit.

SMAExit

FiveDaySMAExit_EQ_Curve

 

The power of a good exit! By changing the exit to our 5-day simple moving average we have significantly improved the performance. All metrics have improved. Notice the significant reduction in drawdown. This is huge.

So how does this hold up against the 2-period RSI trading model? Let’s see…

RSI(2) vs Consecutive Down Days

Below is the results of using a two-period RSI with a threshold of 10 vs our 3 down day trading model. Both trading models exit when price crosses the 5-day SMA.

LosingStreakvsRSI

So which one is better? They are very similar in most of the metrics. The maximum drawdown is a lot higher with the RSI(2) system. Again, neither of these tests utilize a stop.

Overall, these are very interesting results and may be an effective replacement for the RSI. I encourage you to perform your own testing to see if this simple price pattern could be used in your own trading. Below you will find the EasyLanguage code for code used in this study.

Downloads

Down Days Strategy (text file)
Down Days Strategy (TradeStation ELD file)
Down Days WorkSpace (TradeStation WorkSpace file)

The post Down Days Trading Model appeared first on System Trader Success.

The Laguerre RSI vs Classic RSI

$
0
0

John Ehlers is a name you’ll run across when you start your journey into testing various indicators and filters to be used in your trading models. I remember reading about the Laguerre Filter and Laguerre RSI many years ago when they first appeared on the scene. At the time I was not nearly into quantitative trading as I am today. So let’s take a closer look at the Laguerre RSI and answer a simple question:

Can the Laguerre RSI perform better than our standard 2-period RSI?

Laguerre RSI (LRSI) was authored by John Ehlers. You can read about the Laguerre filter in his article, “Time Warp – Without Space Travel“. At the heart of the LRSI indicator is the Laguerre Transform. The mathematics and explication of the Laguerre filter is well beyond the scope of this article or my understanding. In short, John Ehlers appears to use this technique to “warp” the time coefficients of a traditional EMA filter which results in a quicker response.

Below is the EasyLanguage code for a 4-element Laguerre filter.

Inputs: Price((H+L)/2),
gamma(.8);
Vars: L0(0),
L1(0),
L2(0),
L3(0),
Filt(0)
FIR(0);
L0 = (1 - gamma)*Price + gamma*L0[1];
L1 = -gamma*L0 + L0[1] + gamma*L1[1];
L2 = -gamma*L1 + L1[1] + gamma*L2[1];
L3 = -gamma*L2 + L2[1] + gamma*L3[1];
Filt = (L0 + 2*L1 + 2*L2 + L3) / 6;
FIR = (Price + 2*Price[1] + 2*Price[2] + Price[3]) / 6;
Plot1(Filt, "Filt");
Plot2(FIR, "FIR");

The standard Relative Strength Index (RSI) was authored by Wells Wilder. The LRSI uses the current price, a user defined gamma factor, and plenty of feedback to calculate its final value. Below is the EasyLanguage code:

Inputs: gamma(.5);
Vars: L0(0),
L1(0),
L2(0),
L3(0),
CU(0),
CD(0),
RSI(0);
L0 = (1 – gamma)*Close + gamma*L0[1];
L1 = - gamma *L0 + L0[1] + gamma *L1[1];
L2 = - gamma *L1 + L1[1] + gamma *L2[1];
L3 = - gamma *L2 + L2[1] + gamma *L3[1];
CU = 0;
CD = 0;
If L0 >= L1 then CU = L0 - L1 Else CD = L1 - L0;
If L1 >= L2 then CU = CU + L1 - L2 Else CD = CD + L2 - L1;
If L2 >= L3 then CU = CU + L2 - L3 Else CD = CD + L3 - L2;
If CU + CD <> 0 then RSI = CU / (CU + CD);
Plot1(RSI, "RSI");
Plot2(.9);
Plot3(.1);

The LRSI behaves in a similar manner to the classic RSI. In the past I’ve tested the 2-period RSI indicator within several mean reverting trading models that trade the U.S. index futures. Several profitable trading models can be built with this indicator that produce surprising solid results for nearly 20 years. The basic rules for the 2-period RSI is to buy when the RSI value falls below a threshold, such as 10. Then sell the position when the price rises above a threshold, such as 90.

Below is a chart of the 2-period RSI trading model applied to the daily chart of the eMin. The bottom pane contains the RSI signal. You can see when this value falls, we enter a new position and hold until the RSI value rises above 90.

2-Period RSI Example

The LRSI would be traded in a similar fashion. Buying when the value falls below a critical threshold, and closing the trade when it rises above a threshold. Below is an image of the LRSI and RSI being applied to a daily chart of the S&P futures.

LRSI Example

You can see when both indicators fall, they create setups for opening trades. I’m now going to compare our old friend, with Ehler’s much more complex LRSI.

Testing Environment

Before getting into the details of the results, let me say this: Unless otherwise stated, all the tests within this article are going to use the following assumptions:

  • Starting account size of $100,000
  • In-sample dates are from 1998 through November 30, 2016
  • One contract was traded per signal
  • No deductions were made for slippage and commissions

Baseline

Our baseline will be the 2-period RSI. This trading model will enter a trade when the RSI value falls below 10 and exists when price rises above 90. Below are the results:

 

RSI vs LRSI On S&P

Now let’s test the LRSI over the same market. The LRSI will enter a trade when the value falls below .10 and closed when the value rises above .90. The results are in the table below.

In this test we can see the baseline and LRSI perform very similar. We end up with about the same net profit and very similar annual returns. The LRSI trading model produces fewer trades and each trade produces nearly $110 more net profit. The maximum intraday drawdown for the LRSI is higher. So if you can endure more drawdown, you can trade a model which makes similar amount of profit on fewer trades.

But this is just looking at a single stock index market. Let’s look at some others.

RSI vs LRSI On Major U.S. Stock Indexes

Below is the results of testing RSI vs LRSI on the DOW (YM).

Looking at the results for trading the DOW we see similar results as when trading the S&P. That is, we see RSI and LRSI make about the same amount of net profit. LRSI does this on fewer trades but it also has more drawdown. In this particular case, LRSI is probably producing slightly better results than RSI. Next is NASDAQ (NQ).

Looking at the results for NASDAQ we can see LRSI actually performs significantly better. More than three times as much profit on fewer trades. Nice! Next up, let’s take a look at midcap stocks by using the S&P Midcap 400 contract.

Once again we see very similar results between the two markets. Finally, let’s take a look at the Russell 2000 (TF).

In this case we see significant improvement in trading the RSI model on the Russell 2000.

Portfolio Comparison

Using TradeStations Portfolio Maestro feature, I’m going to combine all our trading symbols from this test into a basket. We can then apply our trading models to this entire basket. This will allow me to generate a summary of our two trading models over all the markets we looked at. The following table contains the results of trading a $100,000 account across all symbols (ES, YM, NQ, EMD, TF) including deducting $30 from each trade for slippage and commissions. Only one contract was traded per signal.

It’s interesting to note how close net profit and annual rate of return is between the RSI and LRSI trading models. In this respect the trading models are nearly identical. What’s different is the number of trades and drawdown. So which one is better? It comes down to what you prefer with regards to drawdown and number of trades. It looks like they both end up at the same location but take slightly different roads to get there.

Downloads

Laguerre Indicator and Strategy (TradeStation ELD)
Laguerre Function (text)
Laguerre Strategy (text)

The post The Laguerre RSI vs Classic RSI appeared first on System Trader Success.

TRINdicators

$
0
0

When I start to write a blog post, usually my process is this:

  1. Come up with a really bad pun for the title.
  2. Write the rest of it.

Bad puns are an important part of finance, and life in general.

A blog reader contacted me recently to chat about various technical analysis indicators, and one he mentioned was “TRIN”, a.k.a. the Arms Index. If you’ve been reading my blog awhile, you know that technical analysis makes my skin crawl… at least the kind that debates whether the chart shows a double top or a head-and-shoulders pattern. Interpreting shapes in financial data is just another form of tasseography. Give me quantities that I can quantify!

That said, some classical “TA” indicators can be useful. For example, RSI is useful because it can be tested and be shown to work for some systems.

I must admit, I’d never looked at TRIN before (which is derived from the words “trading index” apparently, making it the most generic indicator name one could come up with). Richard Arms developed this index as a way to augment a simple composite advance/decline index. He added a volume component and his name.

I’ve done some experiments with volume because you often hear blogsters qualify their trading systems with the phrase, “on increased volume” or something similar. My experiments with volume as a source of additional information for end-of-day trading has so far shown nothing, but I remain open-minded.

TRIN, or the Arms Index, is calculated thusly:

( advancing issues / declining issues ) / (advancing volume / declining volume )

Sounds like a pain to calculate, doesn’t it? Thankfully, my data supplier has TRIN indices built in so I don’t have to do any math. I just access the index and boom, got my numbers. My faith in the usefulness of TRIN is such that I wouldn’t have bothered testing if I had to write code to calculate the index.

According to the literature, a TRIN value > 1 is considered bearish, and < 1 is bullish. Since the market tends to revert to a mean on a short-term basis, we should see a bearish sentiment as a chance to buy.

First, let’s establish a baseline system that doesn’t use TRIN.

  • Initial investment is $30,000, and put the entire account in for each trade.
  • Trade the SPY ETF.
  • We enter at the close, if the close is below the previous day’s close.
  • We exit on the first profitable day, or after a set duration is passed if not profitable.
  • My in-sample period for optimization is 1/1/2000-12/31/2010.
  • Commissions are for suckers*, so I won’t include them in this test. Just make sure you’re either trading commission-free or you’ve got huge buckets of money so that commissions are nominal.

In itself, the baseline system isn’t bad. Whenever you’ve got a down day, buy at the close and sell at your first profitable close, or after five days (whichever comes first). A duration of five days often turns out to be the magic number for mean-reversion trades. I think this is because that’s a calendar week, and whatever was scaring folks one week seems less scary the next week. It’s a theory anyway.

Our baseline system (notice how I always say “our”, like you had something to do with this? It’s my way of sharing the blame if things go wrong.) made a net profit of 92% in the in-sample period, with a 78% win rate. Our CAR/MDD is 0.18, which isn’t very good. Our maximum system drawdown was 33.32%.

system drawdown

Compare that to buy-and-hold for the same period, which actually lost 15%.

Surely we can improve on “buy on a down day” as an entry point though, right? Let’s sprinkle some TRIN into our mix.

  • Use the S&P 500 Arms Index / TRIN value.
  • Enter at the close of a “down day”, but only when TRIN was above a certain value the previous day.

The TRIN indicator looks like this (at the bottom):

TRIN indicator

We optimize for our TRIN threshold by checking all values between .50 and 2.00 in .05 increments.

TRIN threshold

Right away we see two peaks. Optimizations that look this “peak-ish” are to be viewed skeptically. That said, all these values are profitable in some way. The higher values let fewer trades through. Over the testing period, a value of 1.45 triggered 194 trades, while a value of .8 triggered 543 trades. Both had similar CAR/MDD values, but the .8 trigger made 148% profit (the higher value made only 70% profit). As you might guess, the lower value is also more volatile, with a system drawdown of almost 18%, as compared to just under 10% for the larger trigger value.

Look at it this way: the higher the TRIN, the more bearish the sentiment (supposedly). The higher value means that we enter a trade only when the market takes a big tumble. The lower value means we enter anything as long as sentiment isn’t so good that it’s bound to fail/revert in the coming days.

Here is the equity chart for the higher 1.45 value:

equity chart for the higher 1.45 value

And the lower 0.8 value:

So how do these two different values look in out-of-sample testing? Both values show profit, which is a good thing. It was, however, difficult to lose money over the period of 2011 to present, so mere profitability is not sufficient.

The liberal, higher frequency system with a value of 0.8 made a profit of almost 28% in that time period. 80% of the trades were winners, out of 324 trades. Average profit/loss per trade was 0.09%. The maximum system drawdown was -18.5%. The CAR/MDD was 0.23. The chart is below.

CAR/MDD

Meanwhile, the more conservative value of 1.45 yielded about 22.5% profit. The win rate for trades was almost 86%, and had only 78 trades. The average profit/loss per trade was 0.27%. The max drawdown was -7.4% and the CAR/MDD was 0.47. Less profit than the other system, but also a less bumpy ride. One might be more inclined to leverage this system as a result.

Unfortunately, buy-and-hold beats both of these systems from both a total profit (74%) and CAR/MDD (0.51) standpoint.

CAR/MDD (0.51) standpoint.

The reason of course is the period of 2013-2014, where mean reversion continually failed. The “uninterrupted prosperity” of these two years is an anomaly though, because the FED is unlikely to pour that kind of money into the markets in the future.

Looking at both the “1.45” system and “buy and hold” from the inception of SPY to the present, which one would you like to trade? I would give up a certain percentage of gains to avoid experiencing a 50% drawdown. How about you?

indicators

* I would remiss if I just glossed over the scourge of finance we call “commissions”. For most of this period of time, commissions would have destroyed this system unless you had a huge starting account. These days, you could trade commission-free and actually achieve something along these lines. Some combination of leverage, leveraged ETF, and account size might also make it doable with “regular” commissions. If you are new to trading, be aware that commissions are like a tax that turns many good systems into bad ones.

–by Matt Haines from blog Throwing Good Money

The post TRINdicators appeared first on System Trader Success.

Testing Laguerre RSI Entry and Exits

$
0
0

In a previous article I took a look at an indicator called the Laguerre RSI. The Laguerre RSI (LRSI) was authored by John Ehlers. You can read about the Laguerre filter in his article, “Time Warp – Without Space Travel“. Within the previous article I was comparing the LRSI to the standard RSI. I did this by creating a simple mean reverting trading model for the E-mini market. During that test, signals were generated by the Larguerre RSI when the indicator value fell below a critical threshold (.10) as you can see in the image below.

LRSI Type 1

LRSI Type 1 – Open new trade when indicator falls below threshold of 0.10.

This got me wondering what changes the entry trigger might do. For example, what would happen if we waited to open a new trade when the LRSI indicator rises above the lower threshold as in the image below?

LRSI Type 2 Entry

LRSI Type 2 – Open new trade when indicator rises above threshold (0.10).

So, let’s take a look at how this strategy performs based upon these two types of entries. First, let’s take a look at the testing environment.

Testing Environment

Before getting into the details of the results, let me say this: Unless otherwise stated, all the tests within this article are going to use the following assumptions:

  • Starting account size of $100,000
  • In-sample dates are from 1998 through November 30, 2016
  • 2 ticks of slippage and $5 of commissions were deducted per round trip
  • One contract was traded per signal
  • Markets traded: ES, YM, NQ, EMD, TF
  • LRSI Lower Threshold 0.10
  • LRSI Upper Threshold 0.90

Type 1 – Value Falls Below Threshold

This is our baseline and it’s the trigger method I used in the previous article. A trade is opened when the value of the LRSI indicator falls below our lower threshold and is closed when the value of the indicator rises above the upper threshold.

Type 2

In this case we wait to open a trade when the value of the LRSI indicator rises ABOVE our lower threshold. This means the value of the indicator must first fall below our lower threshold and then rise above it. The concept behind this type of entry is we want to see the falling price of our market recover slightly before opening a new trade. This might prevent us from entering too soon in a falling market. Let’s see how it does.

Looks like this significantly reduces the performance of the trading model. There was virtually no change in max drawdown. No overall improvement here. What does this mean? I think this study is telling us it pays to get in early during a pullback. At least, as defined by our current entry/exit rules. Don’t wait for confirmation of price recovery, instead jump in.

Type 3 – The Momentum Trade

Let’s try something completely different. The studies we have been looking at with LRSI have been based around the concept of mean reverting. That is, we buy pullbacks in hopes that price will soon bounce back giving us a nice profit. I’ve demonstrated in many articles about the mean reversion characteristic of the US stock index markets. However, I think it would be worth testing again with this indicator.

So, in this next test let’s switch up the entry and exit rules. Let’s enter when price crosses above the upper threshold and exit when price crosses below the lower threshold. What we are doing is entering on bullish activity and exiting on bearish activity. In short, we are creating a momentum-based model.

Wow! A significant reduction in profitability. This doesn’t come unexpected. What this study demonstrates again is the mean reverting characteristics of the US stock index markets. Clearly buying into short-term strength is not a strategy worth pursuing. At least, with this type of trading model.

Type 4 – Fall Below Upper Threshold Exit

Let’s go back to looking at our mean reverting trading model. In this test let’s enter our trade as soon as the indicator falls below our lower threshold as before. We will change the exit to occur when the indicator falls below the upper threshold. This is different then the previous exit which was to exit as soon as the indicator value rose above the upper threshold. In this case the indicator must rise above the upper threshold and then fall below the upper threshold to trigger an exit. The concept here is to hold during the market snapback and only exit once some type of market weakness is measured by our indicator. This might produce more profit by holding some trades longer.

It looks like this exit paid off. We are making more net profit and this is done with making more profit per trade. Notice we have about the same amount of trades but we have increased the efficiency of our trades by holding them longer. Drawdown is about the same. This looks like a significant improvement to me.

Type 5 – SMA Exit

Let’s test another exit. In many of the RSI-based trading models tested on this website, a 5-period simple moving average is used to exit trades. Let’s do that here. We’ll exit when price closes above its 5-day simple moving average.

This produces interesting results. We make about the same amount of profit however, there are many more trades. This trading model also has a slightly higher win great. Drawdown is also slightly reduced.

So, which exit is better? The simple moving average exit (Type 4) or the LRSI exit (Type 5)? I think this depends upon your trading style. If you prefer to have a high number of trades I think the Type 5 model would be for you. If you prefer fewer trades but making each of those trades a bigger winner then the Type 5 model is for you.

The post Testing Laguerre RSI Entry and Exits appeared first on System Trader Success.


The Better Rotation Indicator

$
0
0

The Better Rotation Indicator uses 8 major ETFs to track Global Macro trends.

This indicator helps visualize the rotations from one Global Macro asset class to another – from unloved and over-sold to hot and being chased by the herd. Right now (4Q 2016) we’ve got a rotation taking place as Government Bonds get overtaken by Commodities. A sea change that could last quite a while.

“This is fascinating. Thank you for sharing with us.” Elie S.

There’s also a second version of the indicator code for tracking nine major Forex pairs. Another way of seeing where the money is flowing around the world. Remember, there are some major currencies that are pegged – Chinese Yuan, Hong Kong Dollar, Singapore Dollar, and Saudi Riyal – so including them in the analysis adds little value.


How to add the Better Rotation Indicator to a chart

How to add the Better Rotation Indicator to a chart

These instructions are for TradeStation and the ‘Better Rotation Asset Class’ version of the indicator. Start with a new Workspace:

  1. File > New > Workspace
  2. File > New > TradingApp Window > Chart Analysis
  3. Format > Symbol > Settings tab > Symbol field input SPY > Select Weekly interval and 20 years back > Scaling tab > Sub-graph Hidden > OK
  4. Insert > Symbol > Symbol field input EEM > Tick Prompt for format > Plot > Scaling tab > Sub-graph Hidden > OK
  5. Repeat the step above for TLT, LQD, HYG, DBC, GLD and lastly IYR
  6. Check you’ve input the symbols correctly by going Format > Symbol and you should see the same thing as the image above
  7. Insert > Indicator > _Better Rotation Asset Class > OK
  8. Insert > Indicator > _Better Rotation Asset Class > Tick Prompt for format > OK > Inputs tab > Change Normalise input to True > Check the Lookback value is 52 > OK

The steps for adding the ‘Better Rotation Forex’ version of the indicator are almost the same. Just add the following symbols (hidden) to a new chart:

  • EURUSD (Euro)
  • AUDUSD (Australian Dollar)
  • GBPUSD (British Pound)
  • NZDUSD (New Zealand Dollar)
  • USDCAD (Canadian Dollar)
  • USDJPY (Japanese Yen)
  • USDCHF (Swiss Franc)
  • USDMXN (Mexican Peso)
  • USDZAR (South African Rand)

Then add the Forex version of the indicator. Please note there is no ‘Normalise’ input with the Forex version of the indicator. Instead the bold white line calculates the average of the nine Forex symbols and shows what they are doing (on average) against the US Dollar.


Better Rotation Indicator for TradeStation, NinjaTrader & MultiCharts

I hope this video on Global Macro asset class rotation will be helpful to you. Download the Better Rotation Indicator (unlocked code) for TradeStation, NinjaTrader 8, and MultiCharts by visiting Emini Watch.

— by Barry Taylor from blog Emini-watch

The post The Better Rotation Indicator appeared first on System Trader Success.

Predictive Indicators

$
0
0

INTRODUCTION

Technical traders understand that indicators need to smooth market data to be useful, and that smoothing introduces lag as an unwanted side effect. We also know that the market is fractal; a daily interval chart looks just like a weekly, monthly, or intraday chart. What may not be quite as obvious is that as the time interval along the x-axis increases, the high-to-low price that swings along the y-axis also increases, roughly in proportion. This “spectral dilatation” phenomena causes an undesirable distortion, one that has either not been recognized or has been largely ignored by indicator developers and market technicians.

So, we have two challenges to address. 1) How to best smooth the data; and 2) how the fractal nature of the market distorts indicator interpretation.

To address the smoothing problems I will show you a stunning new filter from my aerospace analog filter design experience translated to a digital filter useful for traders. To address the mitigating effects of the fractal structure of the market I will show you the effects of a new filter seldom used in trading. By removing the noise and the indicator distortion I will then show you the core concept of getting consistent short term trading winners.

MARKET DATA STRUCTURE

Picture a chart using daily data. Next, picture a chart using weekly data. They basically look the same when the scales are removed. This is often called the fractal nature of the market. Since the charts look the same, and since the time scales are different by a factor of 5, it must be concluded that the cyclic swings are five times greater when using weekly data. Therefore, the cycle amplitudes in market data are in direct proportion to their wavelength for the fractal dimensions to hold.

There have been many academic studies about the market data structure. Figure 1 captures the significant factors found in these studies. The horizontal axis is in terms of frequency, so that a frequency of 10-1 means a cycle having a 10-bar period and a frequency of 10-2 means a cycle having a 100-bar period, etc. The vertical scale is the power in the wave.

Aliasing noise has the largest amplitude at the higher frequencies (i.e. the shortest cycle periods). Since Aliasing Noise is larger than signals at these cycle periods, noise swamps the information in the signal, and the only thing to do is to avoid trying to use signals that fall within the range of these cycle periods. Aliasing Noise is also as large or larger than signals at longer cycle periods and therefore it must be removed by smoothing to recover the signal.

Starting at periods somewhat shorter than a 10-bar cycle, a longer wave has more power in it than a shorter wave, which means the wave amplitude is larger for the longer wave. I call the shape of this Wave Amplitude versus frequency Spectral Dilation.

Spectral Dilation increases at the rate of approximately 6 dB per octave. This means that each time the cycle period is doubled, the wave amplitude in that longer wave is also doubled. It works the other way too. That is, every time the cycle period is halved the wave amplitude is also halved.

Although I knew about Spectral Dilation I was shocked to find that the phenomenon exists all the way down to shorter cycle periods – even below a 10-bar cycle period. At this point Spectral Dilation intercepts the Aliasing Noise resulting from using sampled data. If we just want to eliminate Aliasing Noise, we do not need a smoothing filter longer than a 10-bar cycle period. In fact, using a smoothing filter longer than 10 bars attenuates the data we are trying to use in trading.

Figure 1. Market Data Contains Both Aliasing Noise and Spectral Dilation. Aliasing Noise Swamps the Signal Where the Cycle Period is Less than 10 Bars

Figure 1. Market Data Contains Both Aliasing Noise and Spectral Dilation. Aliasing Noise Swamps the Signal Where the Cycle Period is Less than 10 Bars

 

It is also worthy of note that Aliasing Noise scales with the sampling frequency, and so it is a good rule of thumb that Aliasing Noise intercepts the signal amplitude at about a 10-bar cycle period regardless of the time frame you are trading.

SMOOTHING FILTERS

Most traders use a moving average for smoothing. The problem is that a moving average is just not a very efficient filter. In order to get the amount of smoothing desired, the moving average length must be made longer. But making the average length longer also causes more lag, with the result that the smoothed trading signals are not timely for a good trade. My SuperSmoother filter is much more efficient. I created the SuperSmoother digital filter by converting an analog filter having real inductors and capacitors into the digital domain and then minimizing the lag of the converted filter. I have compared a 10-bar Exponential Moving Average (EMA) with my SuperSmoother filter set to a critical period of 10 bars for an apples-to-apples comparison in Figure 2. The horizontal scale is in terms of frequency, so that 0.1 corresponds to a 10-bar cycle period and .5 corresponds to a 2-bar cycle period. 0.5 is called the Nyquist frequency, and is the highest possible frequency component using sampled data.

The EMA only reduces the amplitude at the Nyquist frequency by 13 dB. On the other hand, the SuperSmoother filter theoretically completely eliminates components at the Nyquist Frequency. The added benefit is that the SuperSmoother filter has significantly less lag than the EMA.

Figure 2. An EMA Has Only Modest Noise Attenuation While a SuperSmoother Virtually Eliminates Aliasing Noise

Figure 2. An EMA Has Only Modest Noise Attenuation While a SuperSmoother Virtually Eliminates Aliasing Noise

Code Listing 1 gives the EasyLanguage code to compute the Super Smoother filter. The a1 and b1 variables are computed for the 10-bar critical period. These are then used to compute the c1, c2, and, c3 coefficients of the filter. If the reader is translating to another computer language, please note that the trigonometric arguments are in degrees whereas they are in radians in most other languages. Also please note that the notation [N] is the value of that variable “N” bars ago.

Code Listing 1.  EasyLanguage Code to Compute the SuperSmoother Filter

{SuperSmoother filter

© 2013-2017  John F. Ehlers}

Vars:  a1(0), b1(0), c1(0), c2(0), c3(0), Filt(0);

a1 = expvalue(-1.414*3.14159 / 10);

b1 = 2*a1*Cosine(1.414*180 / 10);

c2 = b1;

c3 = -a1*a1;

c1 = 1 - c2 - c3;

Filt = c1*(Close + Close[1]) / 2 + c2*Filt[1] + c3*Filt[2];

Plot1(Filt);

Plot2(0);

Having solved the problem of dealing with Aliasing Noise, we can now turn our attention to Spectral Dilation.

SPECTRAL DILATION

Most trading oscillators and “detrenders” perform basically the same way as a 1-pole HighPass filter because they only have one difference term in their calculation. For example, the difference term of a Stochastic Indicator subtracts the lowest closing price over the length of the indicator from the current closing price. The result of performing as a 1-pole HighPass filter is that the attenuation scales as 6 dB per octave for frequency components smaller than the critical frequency.

But if Spectral Dilation is increasing the amplitude at the rate of 6 dB per octave and the oscillator is reducing the amplitude due to filtering at the rate of 6 dB per octave, the net result is that the longer period waves are not filtered out. The only effect of the single pole filter (or conventional indicator) is to flatten and equalize the Spectral Density. Figure 3 shows the output of a single pole HighPass filter that is smoothed with a SuperSmoother filter.

Figure 3. A Single Pole HighPass Filter (or Oscillator) Does Not Remove Low Frequency Components, Resulting in the Output Failing to Have a Zero Mean

Figure 3. A Single Pole HighPass Filter (or Oscillator) Does Not Remove Low Frequency Components, Resulting in the Output Failing to Have a Zero Mean

If the high pass filter complexity is increased to a 2-pole HighPass filter, then the filter response increases to 12 dB per octave, enabling the effects of Spectral Dilation to be removed. The result of using the 2-pole HighPass filter is compared to the response of the original 1-pole HighPass filter in Figure 4.

The original 1-pole HighPass filter output is shown as the red dashed line and the 2-pole HighPass filter output shows that the effects of Spectral Dilation have been removed. Now the output has a nominally zero mean, allowing for a more accurate assessment of the turning points without the distortion of the long period offsets. In addition, the waveform generally has less lag when longer wave components are removed.

Figure 4.A Two Pole HighPass Filter Removes the Effects of Spectral Dilation. This Gives the Oscillator a Zero Mean to Accurately Assess Turning Points and Generally Reduces Indicator Lag.

Figure 4. A Two Pole HighPass Filter Removes the Effects of Spectral Dilation. This Gives the Oscillator a Zero Mean to Accurately Assess Turning Points and Generally Reduces Indicator Lag.

The combination of a 2-pole HighPass filter and a SuperSmoother filter can be used to precondition data before any additional calculations are performed. Since this filter combination limits the range of cycle periods in the output, it is called a “Roofing Filter” because it provides a roof over further calculations. The EasyLanguage code to compute the Roofing filter is given in Code Listing 2.

Code Listing 2.  EasyLanguage Code to Compute the Roofing Filter
{Roofing filter
© 2013-2017 John F. Ehlers}

Vars: alpha1(0), HP(0), a1(0), b1(0), c1(0), c2(0), c3(0), Filt(0), Filt2(0);

//Highpass filter cyclic components whose periods are shorter than 48 bars
alpha1 = (Cosine(.707*360 / 48) + Sine (.707*360 / 48) - 1) / Cosine(.707*360 / 48); HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close - 2*Close[1] + Close[2]) + 2*(1 - alpha1)*HP[1] - (1 - alpha1)*(1 - alpha1)*HP[2];

//Smooth with a Super Smoother Filter
a1 = expvalue(-1.414*3.14159 / 10);
b1 = 2*a1*Cosine(1.414*180 / 10);
c2 = b1;
c3 = -a1*a1;
c1 = 1 - c2 - c3;
Filt = c1*(HP + HP[1]) / 2 + c2*Filt[1] + c3*Filt[2];

Plot1(Filt);
Plot2(0);

In Code Listing 2, the variable alpha1 is computed for the HighPass critical period of 48 bars. The HighPass filter will pass all spectral components having periods less than 48 bars. The SuperSmoother filter passes all spectral components having period greater than 10 bars. The end result of the Roofing filter is that cyclic components having periods between 10 bars and 48 bars will be passed from the input to the output. If the reader is translating to another computer language, please note that the trigonometric arguments are in degrees whereas they are in radians in most other languages. Also please note that the notation [N] is the value of that variable “N” bars ago.

The impact of using the Roofing filter before computing a Stochastic is shown in Figure5. Clearly, the conventional Stochastic tends to hang near the upper bound when the prices are in an uptrend. Since this characteristic is caused by Spectral Dilation, the tired old explanations of how to use %K, %D, and when to enter a short position at the end of a trend are just plain silly. When the Roofing filter precedes the Stochastic, as shown in the second subgraph of Figure 5, the longer period waves have been removed and the swing waves are obvious by inspection.

Figure 5. A Roofing Filter Preceding a Stochastic Removes Spectral Dilation Distortion

Figure 5. A Roofing Filter Preceding a Stochastic Removes Spectral Dilation Distortion

The Stochastic calculation is simply the current close minus the lowest close over the calculation period, normalized to the highest close minus the lowest close. Although this calculation is trivial, I have included the complete indicator in Code Listing 3 for the convenience of readers who wish to duplicate it. As described above, I use the output of the Roofing filter for the Stochastic calculation rather than the closing price. Also note that I use a SuperSmoother filter rather than an exponential moving average to smooth the result of the calculations. I call the indicator, “My Stochastic” to avoid confusion with the conventional Stochastic indicator.

Code Listing 3. EasyLanguage Code to Compute My Stochastic

{My Stochastic Indicator
© 2013-2017 John F. Ehlers}

Inputs: Length(20);

Vars: alpha1(0), HP(0), a1(0), b1(0), c1(0), c2(0), c3(0), Filt(0),
HighestC(0), LowestC(0), count(0), Stoc(0), MyStochastic(0);

//Highpass filter cyclic components whose periods are shorter than 48 bars
alpha1 = (Cosine(.707*360 / 48) + Sine (.707*360 / 48) - 1) / Cosine(.707*360 / 48);
HP = (1 - alpha1 / 2)*(1 - alpha1 / 2)*(Close - 2*Close[1] + Close[2]) + 2*(1 - alpha1)*HP[1] - (1 - alpha1)*(1 - alpha1)*HP[2];

//Smooth with a Super Smoother Filter
a1 = expvalue(-1.414*3.14159 / 10);
b1 = 2*a1*Cosine(1.414*180 / 10);
c2 = b1;
c3 = -a1*a1;
c1 = 1 - c2 - c3;
Filt = c1*(HP + HP[1]) / 2 + c2*Filt[1] + c3*Filt[2];

HighestC = Filt;
LowestC = Filt;
For count = 0 to Length - 1 Begin
If Filt[count] > HighestC then HighestC = Filt[count];
If Filt[count] < LowestC then LowestC = Filt[count];
End;
Stoc = (Filt - LowestC) / (HighestC - LowestC);
MyStochastic = c1*(Stoc + Stoc[1]) / 2 + c2*MyStochastic[1] + c3*MyStochastic[2];

Plot1(MyStochastic);
Plot2(.8);
Plot6(.2);

EFFECTIVE SHORT TERM TRADING STRATEGIES

Having successfully dealt with the Aliasing Noise issues as well as Spectral Dilation in the price data, we now have the tools to address trading strategies.

Conventional wisdom dictates that a long position trade be entered after the oscillator indicator has reached a minimum and turns up. The thinking here is that the indicator is so unreliable that confirmation of the price movement must be obtained before the trade is made. The conventional trading rules are depicted in Figure 6. Buy signals are created when the indicator crosses over the 20% level. Sell Short (or Sell to Exit) signals are created when the indicator crosses under the 80% level.

Figure 6. Conventional Wisdom is to Buy When the Indicator Crosses Above 20% and To Sell Short when the Indicator Crosses below 80%

Figure 6. Conventional Wisdom is to Buy When the Indicator Crosses Above 20% and To Sell Short when the Indicator Crosses below 80%

We can test this hypothesis. I am going to describe a trading strategy using the Stochastic preceded by a Roofing filter of Code Listing 3. I want to emphasize this is not an explicit trading system, it is only a demonstration of a strategy. The strategy using confirmation is to buy when the indicator has reached a minimum value and then crosses over the 20% level. Also confirmation is used to sell short when the maximum value has been reached and then crosses below the 80% level. The equity curve applying this simple rule to the Stochastic oscillator on 10 years of S&P daily Futures data is shown in Figure 7. Clearly, one would not want to trade this rule in real life.

Figure 7. Consistent Losses are Incurred When Trading the Stochastic Oscillator Using the Conventional Rule of Waiting for Confirmation

Figure 7. Consistent Losses are Incurred When Trading the Stochastic Oscillator Using the Conventional Rule of Waiting for Confirmation

The basic reason the confirmation strategy does not work is lag. If you are using an oscillator indicator, you are probably trying to make short term swing or momentum trades. You are most likely trying to trade a monthly cycle because that is a prevalent component in the data, since most companies have to make their numbers by the month. Therefore, you probably have 10 bars in an up-move to be long, and 10 bars in a down-move to be short or flat. All indicators have lag, even the SuperSmoother filter. A quick assessment gives several bars of lag to the SuperSmoother filter, several bars lag in computing the Stochastic, about 3 bars waiting for confirmation, AND then you have to wait another bar after confirmation to make your trade entry. Add all these lags together and you find you have about eight bars total lag after the prices reached their swing low. The 10-bar up-move is almost over before you make your entry. Then, to exit the trade, you have the move against you for about eight bars. This is why the wait for confirmation strategy cannot ever work for short term trading.

On the other hand, if we have removed the effects of Aliasing Noise as well as Spectral Dilation from the indicator we can conquer lag by anticipating the cyclic turning points. In other words, we have established a predictive and forecasting indicator. For example, to anticipate the turning point using the Roofing filter and Stochastic indicator, we would take a long position when the indicator crosses below the 20% level, BEFORE the indicator reaches its minimum value. Accordingly, we would take a short position when the indicator crosses above its 80% level,  BEFORE the indicator reaches its maximum value. These trading rules are depicted in Figure 7.

Figure 8. Predictive Indicators Enable You to Buy When the Indicator Crosses Below 20% and To Sell Short when the Indicator Crosses Above 80%

Figure 8. Predictive Indicators Enable You to Buy When the Indicator Crosses Below 20% and To Sell Short when the Indicator Crosses Above 80%

Doing just this, with no other rules, we obtain the equity curve shown in Figure 9 when trading the S&P daily Futures over the last 10 years. Clearly, anticipating the turning points works and therefore the correctly filtered indicator is predictive! I want to emphasize again, that this is not a complete trading system. Rather, I have just demonstrated the efficacy of anticipating the indicator turning points.

Figure 9. Consistent Winners Occur When Trading the Stochastic Oscillator by Anticipating the Indicator Turning Points

Figure 9. Consistent Winners Occur When Trading the Stochastic Oscillator by Anticipating the Indicator Turning Points

CONCLUSIONS

I have shown that the information at very short cycle periods is swamped by Aliasing Noise, and therefore the only solution is to avoid these cycle periods in your analyses. Since Aliasing Noise scales with the sample frequency, periods shorter than about 10 bars should be avoided regardless of the time scale on which you are trading. Aliasing Noise is also as large as signals at longer cycle periods, and therefore should be removed by filtering. The SuperSmoother filter is vastly superior to moving averages for removing Aliasing Noise as well as other general smoothing applications.

The SuperSmoother filter can be combined with a 2-pole HighPass filter to create a Roofing filter. The Roofing filter determines the segment of the frequency spectrum to be used for analysis. The Roofing filter removes the effect of Spectral Dilation and helps create oscillators having a nearly zero mean.

Smoothed indicators having a symmetrical swing about a nominal zero mean can be used to create reliable predictive indicators. Most technical analysis indicators merely document what has happened in history. Who needs that? The purpose of indictors is to make a statistically reliable prediction of what the future holds so that a signal can be converted to a profitable trade.

— By John Ehlers of MESA Software

The post Predictive Indicators appeared first on System Trader Success.

Battle of the Oscillators…Round 1

$
0
0

In a recent article, Predictive Indicators written by John Ehlers he highlighted a unique indicator used to time market cycles. This indicator is a heavily modified Stochastic Oscillator and was demonstrated on the S&P. In this article, I want to put John’s Oscillator to the test by comparing it to another popular indicator used for timing to stock index markets.

Backtesting Environment 

For this entire article, the backtest will be conducted from January 1, 2000, to December 31, 2016. I will be deducting $5 in commissions and two-tick of slippage per round trip. I will trade one contract per signal on a $100,000 account. Profits will not be reinvested. The backtest will be conducted on a basket of index futures. The markets I will use are:

  • E-mini S&P
  • E-mini DOW
  • E-Mini NASDAQ
  • E-Mini RUSSEL 2000
  • E-Mini S&P MidCap 400

 John’s Oscillator Performance

These are interesting results and seem to verify that for these stock index markets, this indicator is a decent predictor of market turning points. We have a profit of over $434K which gives us a compounded annual rate of 10.36%. The profit factor is 1.33 and drawdown only exceeded 18% once. Let’s now compare it to another popular indicator used to locate potential turning points.

The 2-period RSI Oscillator

I created a simple strategy to open long trades when the 2-period RSI crosses below 10 and to sell short when price crosses above 90. This is a similar concept to John’s Oscillator as both strategies are either long or short. Below are the results of this strategy.




In this case, we can see the 2-period RSI under perform John’s Oscillator. Not only does it underperform in terms of net profit, profit factor, sharp ratio, and average annual return but the drawdown is larger. We have a profit of over $235K which is about $199K less than John’s Oscillator. The compounded annual rate is 7.37%. The profit factor is 1.24 and drawdown exceeds 20% many times and peaks at around 48%.

John’s Oscillator does appear to pick turning points better than the 2-period RSI on the stock index markets. Using John’s Oscillator combined with these markets might just be a great place to start building a profitable trading system.

In a future article, I’m going to compare it to a few other indicators and then move to other markets such as currency futures, commodities, and bonds.

John Ehlers Workshop!

If you want to get personalized help on how to use advanced cycle and DSP technology in your trading, you’ll want to check out John’s Workshop.

Downloads

The post Battle of the Oscillators…Round 1 appeared first on System Trader Success.

The Internal Bar Strength Indicator

$
0
0

The internal bar strength or (IBS) is an oscillating indicator which measures the relative position of the close price with respect to the low to high range for the same period. The calculation for Internal Bar Strength is as follows… IBS =  (Close – Low) / (High – Low) * 100; For example, on 13/01/2016 the QQQ etf had a high price of $106.23, a low price of $101.74 and a close price of $101.90. The value of IBS would be calculated as … (101.90 – 101.74) / (106.23 – 101.74) * 100 = 3.56 Low IBS readings show that a market has closed near the lows of the day, high IBS readings show that a market has closed near the highs of the day. The following image shows the IBS indicator plotted beneath the price series. IBS-1-630x315

Testing the Internal Bar Strength Indicator The test period is between 01/01/2005 and today. $100,000 hypothetical starting balance, with 100% of available equity invested per position. Commissions are $0.01 per share and there is a minimum cost per trade of $1.00. Tests are carried out using Amibroker and the data is provided by Norgate Premium. These are the Strategy rules:

  • If IBS < 10
  • Buy the close
  • Exit at close if price > previous day high.

QQQ Results

  • No. of trades = 199
  • % of Winners = 72.36%
  • Average P/L% per trade = 0.62%
  • Average hold time = 4 days
  • Annualized return = 11.32%
  • Maximum draw-down = -16.14%
  • CAR/MDD = 0.70
  • Exposure = 28.47% The monthly breakdown of returns is as follows…

Internal-Bar-Strength-QQQ-Performance-1 One common trait among many of these types of mean-reversion systems is that they seem to perform best during volatile markets. To illustrate the point, I added a filter to the above strategy which only allows us to buy QQQ if the VIX has closed above the value of it’s previous 10-day MA. Adding the VIX filter improved the win-rate %, average profit % per trade, and annual % return of the strategy. Here are the results… * No. of trades = 158 * % of Winners  = 75.32% * Average P/L% per trade = 0.85% * Average hold time = 4 days * Annualized return = 12.46% * Maximum draw-down = -14.83% * CAR/MDD = 0.84 * Exposure = 22.3% The Equity curve and monthly breakdown of returns are as follows…

Internal-Bar-Strength-and-VIX

Combining the Internal Bar Strength Strategy with a Trend-Following Strategy Finally, I wanted to see whether combining a trend-following strategy with the Internal Bar Strategy could improve the risk-adjusted returns of either stand-alone strategy. The trend following strategy is as follows…

  • Buy the SPY when the Close > upper Bollinger Band (C,200,1);
  • Sell the SPY when the Close < lower Bollinger Band (C,200,1); Since 2005, this strategy has the following performance metrics:

  • No. of trades = 5

  • % of Winners  = 80%

  • Average P/L% per trade = 19.17%
  • Average hold time = 425 days
  • Annualized return = 7.37%
  • Maximum draw-down = -14.17%
  • CAR/MDD = 0.52
  • Exposure = 76.25% The Equity Curve and monthly breakdown of returns are as follows…

SPY-trend-Following For the Final test, QQQ is traded using the Internal Bar Strength (IBS) strategy and SPY is traded using the above trend-following (TF) strategy. The first test will allocate 70% of available equity to the SPY strategy and 30% of available equity to the QQQ strategy. Further tests will use different capital allocations. Because the SPY can sometimes be held for a long period, it is necessary to periodically rebalance the size of open SPY positions. For the following tests the rebalance frequency will be monthly and the rebalance threshold will be 2%.

70%TF / 30%IBS. Results

  • No. of trades = 163
  • % of Winners  = 75.46%
  • Average P/L% per trade = 1.39%
  • Average hold time = 18 days
  • Annualized return = 9.01%
  • Maximum draw-down = -11.45%
  • CAR/MDD = 0.86
  • Exposure = 60.23%

60%TF / 40%IBS. Results

  • Annualized return = 9.53%
  • Maximum draw-down = -11.09%
  • CAR/MDD = 0.86
  • Exposure = 54.76%

50%TF / 50%IBS. Results

  • Annualized return = 10.04%
  • Maximum draw-down = -10.98%
  • CAR/MDD = 0.91
  • Exposure = 49.35%

40%TF / 60%IBS. Results

  • Annualized return = 10.55%
  • Maximum draw-down = -10.93%
  • CAR/MDD = 0.97
  • Exposure = 43.95%

30%TF / 70%IBS. Results

  • Annualized return = 11.05%
  • Maximum draw-down = -10.87%
  • CAR/MDD = 1.02
  • Exposure = 38.51% The above results illustrate that combining both a trend-following strategy and a mean-reversion strategy within your portfolio has been a useful method for improving risk-adjusted returns. For context, the IBS strategy when traded alone produced a maximum draw-down of 14.83% and a CAR/MDD of 0.86. The Trend-following strategy produced a maximum draw-down of 14.17% and a CAR/MDD of 0.52.

The combined strategy portfolio with a 30% TF and 70% IBS allocation produced a maximum draw-down of 10.87% and a CAR/MDD of 1.02.  This is superior to either strategy if traded alone. The equity curve and monthly breakdown of returns for the 30% TF / 70% IBS portfolio are as follows… Combining-trend-folloiwng-with-Mean-Reversion-2 *Update: As some readers have correctly pointed out, trading on the close when an indicator requires the closing price to be calculated is not necessarily straight forward. With that said, I have included further tests below whereby the trades are executed on the open of the day which follows the signal. The IBS strategy does not perform as well, but the main point of the article (that combining mean-reversion with trend-following can be beneficial) is still valid.

QQQ Results (Enter on open of day which follows signal)

  • No. of trades = 197
  • % of Winners  = 70.05%
  • Average P/L% per trade = 0.49%
  • Average hold time = 4 days
  • Annualized return = 8.69%
  • Maximum draw-down = -15.99%
  • CAR/MDD = 0.54
  • Exposure = 22.04%

QQQ Results with VIX Filter (Enter on open of day which follows signal)

  • No. of trades = 157
  • % of Winners  = 73.89%
  • Average P/L% per trade = 0.64%
  • Average hold time = 4 days
  • Annualized return = 9.15%
  • Maximum draw-down = -16.10%
  • CAR/MDD = 0.57
  • Exposure = 17.26%

SPY Trend-Following Results  (Enter on open of day which follows signal)

  • No. of trades = 5
  • % of Winners  = 80%
  • Average P/L% per trade = 18.87%
  • Average hold time = 425 days
  • Annualized return = 7.24%
  • Maximum draw-down = -14.15%
  • CAR/MDD = 0.51
  • Exposure = 76.06%

Combined Portfolio (70%IBS / 30%TF)  (Enter on open of day which follows signal)

  • No. of trades = 162
  • % of Winners  = 74.07%
  • Average P/L% per trade = 1.19%
  • Average hold time = 17 days
  • Annualized return = 9.90%
  • Maximum draw-down = -11.47%
  • CAR/MDD = 0.86
  • Exposure = 35.47% The equity curve and monthly breakdown of returns for the 70% IBS / 30% TF portfolio are as follows…

Combining-trend-folloiwng-with-Mean-Reversion-3 — By Llewelyn of Backtest Wizard

The post The Internal Bar Strength Indicator appeared first on System Trader Success.

Using a Self-Similarity Metric with Intraday Data to Define Market Regimes

$
0
0

koch-snowflake-and-serpinski-triangle

The images above are the famous Sierpinski Triangle and the Koch Snowflake. These objects are “self-similar” and this means that examination at finer levels of resolution will reveal the same shape. Both are examples of “fractal” geometry, and are characteristic of many phenomena in the natural world such as mountains, crystals, and gases. Self-similar objects are associated with simplicity, redundancy and hence robustness. Self-dissimilar objects are associated with complexity and chaos. Several mathematicians (including Mandelbrot) have observed that markets are clearly non-gaussian or non-normal. Markets exhibit “fat-tails” and have a distribution that shares more in common with a Levy distribution than the normal distribution which is used frequently in quantitative finance. But the market does not have a constant distribution – at times the market behavior is fairly normal in character while at other times the market is wild and unpredictable. The question is how we can effectively determine which regime the market is in so that we can apply the appropriate trading strategies to mitigate risk.

The essence of self-similarity and complexity is to compare the whole to its component parts. For example, let’s take a square that is divided into four separate squares of equal size. The area of the larger square is equivalent to the sum of the areas of each of its component squares. The same of course is true of a one-dimensional line which is equivalent to the sum of its parts. One of the methods of identifying self-similarity in the stock market is to look at the range or the difference between the highs and the lows. We would expect that in a perfectly self-similar market the longer range would be equivalent to the sum of the ranges measured over a smaller interval. The more chaotic the market is, the greater the difference will be between these two measures. Such market conditions would be characterized by a large ratio between the sum of smaller ranges versus the longer measure of range. Essentially this relationship is called fractal dimension and is a measure of complexity. There are many different ways to measure this including using the Hurst exponent, but the problem I have always found in my own humble research is that the suggested thresholds defined by specific absolute values do not seem to reflect the information consistent with theory. I have often found that relative measures tend to be more robust and consistent – much the same way that the magnitude of past returns has less predictive value than the relative rank of past returns. Relative measures tend to be more stationary than absolute values. To compute this measure of self-similarity I use the intraday range (high minus low) versus a longer range window. Here is how it is calculated:

  1. Find the high minus the low for each day going back 10 days.
  2. Take the sum of these values (sum of the pieces).
  3. Find the 10-day range by taking the 10-day maximum (including the highs) and subtracting out the 10-day minimum (whole range).
  4. Divide the sum of the pieces by the whole range – this is a basic measure of fractal dimension/complexity.
  5. Take the 60-day average of the 10-day series of the complexity values – this is the quarterly “chaos/stability” metric.
  6. Use either the 252-day normsdist of the z-score or the percentile ranking of the chaos/stability metric.
  7. Values above .5 indicate that the market is in a “chaos” regime and is much less predictable and non-stationary, values below .5 indicate that the market is stable and much more predictable.

When the market is “stable” it is easier to apply effective quantitative trading systems. When the market is in “chaos” mode, it is not necessarily volatile but rather it is too complex to use for standard measurement and calibration of basic linear prediction. Let’s look at how this measure performs over a long time period using the S&P500 as a test set. The high and low values are generally the same until about 1963 which is when we will begin this test. Here is how the market performed in both regimes over the last 50+ years:

ssm1 (1)

ssm2

 

The market performs quite poorly in “chaos” conditions and seems to make all of its long-term returns in the “stable” regime. Note however that the volatility is not materially different between both regimes – this means that we are capturing something different than just high and low volatility market conditions. Furthermore, the correlation between the chaos indicator signals and for example the basic trend signal of a 200-day moving average is -.116. This means that we are capturing something different than just the market trend as well. The indicator is meant to be used to define regimes rather than as a trading signal to go long or short, but clearly there are some interesting attributes worthy of further exploration and refinement.

  • By David Varadi of CSSA

Update by Jeff Swanson

Here is my attempt at creating this indicator in EasyLanguage. Please let me know of any corrections. The code was last updated on April 9, 2015.

CSSA Regime (TradeStation ELD)
CSSA Regime (Text file)

The post Using a Self-Similarity Metric with Intraday Data to Define Market Regimes appeared first on System Trader Success.

How to Trade the MACD: A High-level Analysis of the MACD Line Feature

$
0
0

Moving Average Convergence Divergence (MACD) is one of the most popular technical indicators used by traders.

It is a flexible indicator that can be used for determining the strength and direction of a trend. It has three distinct features and in this first post we are going to do a high-level analysis of one of those features, the MACD Line.

We will compare three of the most common MACD Line settings on the EUR/USD using daily bars over the past few years to determine whether or not there is a historical pattern that can be exploited.

What is the MACD Line?

The MACD Line was the first feature developed in the MACD indicator. It was developed around 1977 by Gerald Appel. The other two features are the MACD Signal Line, a smoothed average of the MACD Line, and the MACD Histogram, which is the difference between the Signal Line and the MACD Line.

MACD Indicator on EUR/USD 1-Day Bars

The MACD Line is composed of a fast and slow moving average. The value of the MACD Line is the difference between the two moving averages. The default settings for the two moving averages are typically 12-period (fast) and 26-period (slow) exponential moving averages and are generally calculated off of the close price of an asset. Using the MACD Line is the exact same as using a moving average cross. If you subtract the price of a fast-period moving average from the price of a slow-period moving average, you will get the value of the MACD Line. Gerald Appel also commonly uses default periods of 19- and 39-period EMAs while Tom Aspray, who added the histogram feature and studied the MACD in the 1980s commonly uses 10- and 20-period EMAs.

Gerald Appel claims, “As a general rule of thumb, the market climate is most unfavorable when the MACD is falling and below zero.” We’ll take the latter part of his rule of thumb to form our hypothesis; it is unfavorable to go long when the MACD Line is below 0 and it is unfavorable to go short when the MACD Line is above 0.

Using TRAIDE we can test exactly how favorable and unfavorable the market is when the MACD Line is above and below zero; We will try to find values of the MACD Line that lead to bullish and bearish moves the following day by looking at every trading day between August 1st, 2012 and March 24, 2015.

MACD Line (12, 26-Period EMAs) Analysis

TRAIDE automatically generates a histogram of the empirical data to display the distribution of the MACD Line values over our date range. The histogram will show how many of the next days’ bars closed up and how many closed down for every MACD Line value over our date range.

To create the histogram, we will first select the asset we want to analyze, the timeframe and date range. We then select the MACD Line feature under the MACD indicator group in the middle column of TRAIDE’s Strategy Creation page. We can ignore the “Signal Moving Average Type” and “Signal Period” in the indicator settings because we are not using the MACD Signal feature.

Selecting the MACD in TRAIDE

Let’s click analyze and look at the distribution.

MACD Line EUR/USD Distribution

  • y-axis: The number of trades, or trading days, between 08/01/2012 and 03/24/2015.
  • x-axis:The values of the MACD Line, ranging from -0.026 to 0.018.
  • Dividing lines on x-axis: This is the width of a “bin”. There are 10 bins and the edges of the bins are labeled. For example, -0.022 to -0.018 is one bin.
  • Red bars: The height of red bars represents the number of trading days where the following day was bearish, or the close was lower than the open, in any particular bin.
  • Green bars: The height of green bars represents the number trading days where the following day was bullish, or the close was higher than the open. in any particular bin.
  • Shading of the bars: We won’t be using the shading, but this is the strength of signal for that bin. Darker green means that the algorithms found strong signals to go long and darker red bars means that TRAIDE’s algorithms found strong signals for going short.

Using our distribution, let’s test our hypothesis.

The first step is to remove the ambiguous information. The red and green bars in bin -0.002 (-20 pips) to 0.002 (20 pips) straddle the zero line; we don’t know whether the next day closed up or down since we cannot distinguish between the trades that occurred right around zero.

The next step is to click all of the green bars above 0.002 and all of the red bars below -0.002 and see what the accuracy is in our statistics table for each case. When we select the green bars, we are going long for all positive values of the MACD Line above 0.002 and going short for all negative values below -0.002. We want to see if just this simple rule will lead to over 50% of our trades being correct.

Selecting Positive and Negative MACD Line Values

What we find is that when the MACD Line is positive, the price on the next day tends to close higher than the previous bar’s close and when the MACD Line is negative, the price on the following day tends to close below the current day’s close. There were 640 trades in our sample.

It turns out that our hypothesis is true. There is a historical pattern; when the MACD Line is negative (less than -0.002), the next day is bearish 52% of the time and presents an unfavorable condition to go long. When the MACD Line is positive (greater than 0.002), the next day is bullish 54% of the time, presenting an unfavorable condition for going short.

Let’s dive in a little bit deeper and see if we can refine our MACD Line values. From the distribution, it looks like the tail ends of the histograms don’t present a clear historical pattern while the histogram bars on either side of the -0.002 to 0.002 bin appear to have a clear pattern.

Finding the Best Values for Long or Short (MACD Line (12, 26))

On the days where the MACD Line is greater than 0.002, but less than 0.006, the next day was bullish 58% of the time with 183 total trades. In other words, when the 12-period EMA is between 20 and 60 pips above the 26-period EMA the next day closed up 58% of the time. On the days where the MACD Line was less than -0.002 but greater than -0.006, the next day was bearish 52% of the time. We went from a sample size of 640 trades to 380.

Selecting The Best Positive and Negative MACD Line Values

You can use this information to not go long when the MACD Line is between 0.002 and 0.006 or if you are going long, check to see if the MACD Line is within that range. The same goes for going short but with the negative MACD Line values. You could also use this information for the basis of a strategy. Waiting for the MACD Line, with 12- and 26-period EMAs, to be between 0.002 and 0.006 would be a good first filter for going long. I would recommend adding a couple other indicators that you like using. Let’s take a look at the other commonly used settings.

MACD Line (19, 39-Period EMAs) Analysis

Changing the defaults to use 19- and 39-period EMAs in TRAIDE:

Selecting MACD Line Settings 19 and 39-period EMAs

Once I hit analyze, the distribution will load on the Dashboard:

MACD Line Distribution 19 and 39-period EMAs

The two longer EMAs have caused a slight skew left. Let’s apply the same logic that we did in with the 12- and 26-period EMAs to do our analysis. Let’s remove the ambiguous data where the bin could be positive or negative. This takes out the bin -0.0021 to 0.0021. Then let’s select all the green bars to the right of 0.0021 and all the red bars to the left of -0.0021.

MACD Line Distributions Long/Short 19 and 39-period EMAs

Again what we find is that our hypothesis holds to be true; when the MACD Line is positive (above 0.0021), the following day had a 53% chance of closing higher than the previous day’s close. When the MACD Line is negative, the EUR/USD had a 52% chance of closing lower than the previous day’s close.

Looking at the histogram, there appears to be a very similar pattern to our 12- and 26-period settings so let’s take a look and see if we can refine the MACD Line values.

Finding the Best Values for Long or Short (MACD Line (19, 39))

If we click just the bars on either side of the -0.0021 to 0.0021 bin, we can see that 53% of the time, the following day closed lower than the previous day’s close when the MACD Line was negative (below -0.0021) while 54% of the time the next day’s close was higher than the previous day’s close when the MACD Line is positive (above 0.0021).

MACD Line Distributions the Best Long/Short 19 and 39-period EMAs

We found similar results, but the 12- and 26-period EMAs found a stronger pattern for going long, while the 19- and 39-period EMAs led to a slightly strong pattern for going short. Now let’s take a look at our final MACD Line settings; the 10 and 20-period EMAs.

MACD Line (10, 20-Period EMAs) Analysis

We find something very similar when we use 10 and 20-period EMAs. 54% of the time, when the MACD Line is positive (above 0.0017) the following day closed above the previous day’s close. 52% of the time, when the MACD Line is negative (below -0.0017) the following day closed below the previous day’s close. Our sample size is 630.

MACD Line Distributions 10 and 20-period EMAs

Applying the same process as the other two MACD Line parameters, we will see if the values that are just positive and just negative lead to a stronger historical pattern.

Finding the Best Values for Long or Short (MACD Line (10, 20))

MACD Line Distributions the Best 10 and 20-period EMAs

It appears so! Once again, selecting the bin to go short where the MACD Line is less than -0.0017 but greater than -0.0051 gave us 177 days where the following day closed lower than the previous day’s close 57% of the time. Selecting the bin to go long, where the MACD Line is greater than 0.0017 but less than 0.0051 gave us 194 days where the following day closed high than the previous day’s close. 54% of the time.

Summary

The MACD Line, using commonly used settings, is a reliable feature of the MACD indicator for determining whether or not it is favorable to go long or short on the EUR/USD using 1-day bars. I would suggest combining this feature with other indicators, using the MACD Line as a filter, or using it to confirm your trading decision. If you are applying this to other currency pairs or timeframes, make sure you study the MACD Line over those charts. Difference pairs and timeframes are going to behave in their own way.

A table of our results with the percent correct with each of the indicator settings:

Ema1

We can also conclude that the different period settings that we tested do not have a significant impact on whether or not the MACD Line can be used to determine whether or not the market is favorable or unfavorable for going long or short. What did have a significant impact was removing the tail ends of our histograms. Instead, when the MACD Line was just positive or just negative, our accuracy went of significantly for both long and short.

For all three indicator settings, it was better when we refined our parameters by selecting the bins where the MACD Line was just positive or just negative:

A table of our results with the percent correct with each of the indicator settings:

ema 2

It appears that the shorter EMAs, 10 and 20-period, returned the highest accuracy.

This high-level analysis on the empirical data of the EUR/USD using 1-day bars provides a good starting point for incorporating the MACD into your trading. The MACD Line is a reliable feature of the MACD indicator where we can find clear historical patterns.

You can generate these histograms in TRAIDE for any major currency on 1-hour, 4-hour, 6-hour, or 1-day bars since January 1st, 2012.

— by Justin Cahoon from Inovancetech Blog.

The post How to Trade the MACD: A High-level Analysis of the MACD Line Feature appeared first on System Trader Success.

Understanding the Relationship Between Stocks & Bonds

$
0
0

Intermarket Analysis is the comparison of potentially related markets. For example:

  • S&P500 and 30 Year Treasury Bonds
  • 30 Year Treasury Bonds and Gold
  • S&P500 and Japanese Yen
  • Shanghai Composite Index and Aussie Dollar, etc.

The problem with using TradeStation for any Intermarket Analysis is the dreaded “You may not mix symbols with different delays in the same window” error code. That’s exactly what you’ll get if you try to add 30 Year Treasury Bond Futures (symbol US) to an Emini chart (symbol ES). The problem arises because the data comes from two different exchanges – CBOT for Bonds and CME for the Emini. TradeStation says:

Tradestation limitation TradeStation does not allow you to plot two symbols in the same chart window when the amount of delay for the data is different. For example, one is delayed and one is real-time, or both are delayed but the exchanges providing the symbols’ data delay by different amounts of time. Otherwise, during the market session, you would see last prices on the current bar that are asynchronous (i.e. not simultaneous).
There are various ways around the problem – most of them quite complex and involving exchanging data between charts. However, I have found an easier solution. Read on for some tricks of the trade and useful equities vs. bonds indicators.

Using ETFs for Intermarket Analysis

equities_vs_bonds

The solution to the problem is to find market symbols from the same exchange. With the explosion in the number of Exchange Traded Funds (ETFs) it is usually possible to find ones that track the underlying markets you are interested in.

For the Emini the obvious choice is the SPDR (symbol SPY) ETF traded on the AMEX exchange. For the Bond market the best choice is the iShares Lehman 20+ Year Treasury Bond ETF (symbol TLT), also traded on the AMEX exchange.

In the left panel of the chart above, daily data for the SPY and TLT symbols have been plotted quite happily on the same chart. However, in the right panel you get the dreaded “mix symbols” error code when plotting the ES and US symbols.

Are the Emini and Bond Markets Correlated?

The answer is sometimes yes and sometimes no. Correlation between the two markets can go as high as +60% (correlated) or a low as -60% (negatively correlated). You can add the in-built TradeStation correlation indicator on a chart of SPY and TLT to see this for yourself.

There are 2 opposing factors that drive the Bond and Stock markets at different times:

  • Interest rates might be falling and causing Bond prices to rise. The stock market might view the lower interest rates as encouraging for the economy and respond with higher stock prices. Alternatively, rising interest rates will cause Bond prices to fall and the stock market might view the tightening as negative for the economy and stock prices. In these cases correlation between the two markets is positive as they are moving in sync.
  • Stocks and Bonds are also alternative investment vehicles. If the stock market is rising strongly it might encourage Bond investors to cash out and put their money in the stock market and thereby cause Bond prices to fall. Alternatively, if there is a stock market panic investors might rush for the safety of Bonds and push Bond prices up. In these cases the two markets are negatively correlated as they are moving in opposite directions.

Measuring Differences Between the Emini and Bond Markets

SpreadELD

With SPY and TLT plotted on the same chart we can compare price movements. A popular oscillator is shown in the screen grab above. In this case a ratio of SPY and TLT is calculated and this value is compared to a moving average of the ratio.

I prefer to use another measure of relative price movement. The screen grab below shows TradeStation EasyLanguage code for my Bond Oscillator. Instead of using the ratio of SPY and TLT prices it calculates the difference in percentage movement. This indicator is more like a momentum indicator.

BondELD

The two indicators are compared below. The Bond Oscillator (momentum type) is shown above and the Spread Oscillator (moving average type) is shown below. As you can see, the Bond Oscillator generates more defined turning points and is easier to trade.

OscillatorsCompared

The chart below shows the Bond Oscillator added to a 3 year chart of daily SPY prices. Spikes (up and down) in the oscillator show periods when the SPY is over or under-valued against Bonds. These periods can persist for some time – more so on the upside than the downside. To illustrate this a PaintBar has been added to highlight periods when the Bond Oscillator is above +5 (shown as white bars) and below -5 (shown as red bars).

BondOscillator

Rather than use extreme readings on the Bond Oscillator to enter trades, it is safer to wait until the Oscillator crosses the zero line after an extreme reading. This prevents entering the trades too early.

Another trick I have found using this indicator is to wait for an extreme Oscillator reading and then look for a large daily move in the opposite direction in the Bond market. For example, Bonds are in a down trend, the Bond Oscillator goes above +5 and then Bonds have a one-day large up move. This pattern is signaling that professionals are taking profits at stock market highs and reaching for the safety of Bonds, hence driving Bond prices higher.

TradeStation EasyLanguage code for the PaintBar is shown in the screen grab below.

PaintbarELD

Bond Market Turning Points and the Emini

The last series of Bond Intermarket indicators are designed to highlight market turning points. I have found that there is a tendency for the Emini to lag the Bond market by approximately 20 days. To illustrate this point check out the chart below.

20DayDelay

The SPY (Emini equivalent) is shown in the top of the chart and below it is TLT (Bond market equivalent) with closing prices shifted by 20 days. The red vertical lines show how turning points in the two markets (one delayed by 20 days) often line up. The neat thing about this analysis is that the Bond market turning points are known well in advance.

As an aside, this 20 day delay is also the reason I use 20 days as the look back period in the previous two indicators, Spread Oscillator and Bond Oscillator.

The chart below shows the state of the current Bond market (mid April 2007). A vertical line has been added showing where prices were 20 days ago. As you can see, since then the Bond market has declined steeply. If the 20 day relationship holds we may well see another turning point in the stock market. Only time will tell.

VerticalLine

If you’re interested in following turning points in the Bond market you can use the indicator below to plot these vertical lines. The indicator allows multiple vertical lines of different frequencies to be plotted. Just vary the inputs NumLines (number of vertical lines) and Period (20 days, etc.). Make sure there’s enough back history in the chart to plot the lines though – if you ask for two 200 day lines and only have 300 days of history on the chart, the indicator won’t work!

VerticalELD

I hope this article on Intermarket Analysis and equities versus bonds was helpful to you. Download the indicator code used in this analysis from the link below.

Downloads

Bond Indicators (TradeStation ELD)

— Barry Taylor of Emini Watch

“I’m not a trading Guru and I haven’t discovered the Holy Grail. I’m just a regular guy who makes a living day trading Emini futures full-time. This website shows what works for me and is a record of how my trading methodology is evolving.” Read more at Emini Watch.

The post Understanding the Relationship Between Stocks & Bonds appeared first on System Trader Success.


Five Stock Market Timing Indicators Put To The Test

$
0
0

Humans have been trying to clock in the stock market with fancy indicators since the beginning of time. But do they work? In this article I test five different market timing indicators. They are:

  • Coppock Curve
  • Zweig Breadth Thrust
  • Arms Index (TRIN)
  • McClellan Oscillator
  • No. Of New 52-Week Lows

These market indicators are all available with my historical database from Norgate Data.

1) Coppock Curve Indicator

The first indicator we will test is the Coppock Curve.

The Coppock Curve first appeared in a Barron’s article in 1962 and was invented by economist Edwin Coppock.

The indicator takes a weighted moving average of the rate-of-change and is designed to spot long term trend changes in market indexes.

According to Investopedia, you should buy when the Coppock Curve moves above zero and sell when the indicator moves below zero.

Five Stock Market Timing Indicators Put To The Test

Coppock Curve indicator plotted in Amibroker with SPY.

Coppock Curve Strategy

  • Buy the S&P 500 SPY ETF when the Coppock Curve moves above zero.
  • Sell when the Coppock Curve moves below zero.

Testing this strategy between 1/1994 – 1/2017 resulted in an annualized return of 9.90% with a maximum drawdown of -19%. There were four trades in total and each one was a winner.

This compares to a buy and hold return between 1/1994 – 1/2017 of 9.09% with a max drawdown of -55%.

For an indicator that was developed in 1962 this is not such a bad result. The performance is better than buy and hold on a risk-adjusted basis.

Below you can see the equity curve taken from Amibroker with a $25,000 starting capital:

2) Zweig Breadth Thrust

Developed by Marty Zweig, the Breadth Thrust indicator takes the number of advancing issues in an index divided by the total number of issues (advancing and declining). A 10-period exponential moving average is then laid on top.

According to most sources, you should buy when the indicator moves from a level of under 40% to a level above 61.5% within a 10-day period.

This is noted as a rare sentiment shift and usually comes at the beginning of a new bull market.

Zweig Breadth Thrust in Amibroker with SPY.

Zweig Breadth Thrust Strategy

  • Buy SPY when Zweig Breadth Thrust moves from below 40% to above 61.5% within a 10-day period.
  • Sell after 20 days.

I tested this strategy between 1/1994 and 1/2017 and got an annualized return of 1.48% with a maximum drawdown of -14% and a win rate of 65% across 26 trades.

Below you can see the equity curve as taken from Amibroker:

3) Arms Index (TRIN)

The Arms Index was developed by Richard W. Arms in 1967 and is also referred to as the TRIN. This is another market breadth indicator. It’s calculated by dividing the advance-decline ratio by the advance-decline-volume ratio.

There are a number of interpretations on how to use TRIN and some suggest it is most useful for day traders.

According to this article, you should go long when the 10-day moving average of TRIN moves below 0.8 and sell when it moves above 1.2.

Arms Index (TRIN) example in Amibroker with SPY

Arms Index (TRIN) Strategy

I tested buying SPY according to the above definition between 1/1994 – 1/2017 and recorded an annualized return of 3.52% with a maximum drawdown of -22% and a win rate of 65% from 20 trades.

Following is the equity curve taken from Amibroker. You can see that this is a rare signal in recent times so the settings may need to be altered:

4) McClellan Oscillator

The McClellan Oscillator is another market breadth indicator. This one is based on the smoothed difference between the number of advancing and declining securities on the NYSE or some other market index.

Ratio Adjusted Net Advances (RANA) = (Advances – Declines) / (Advances + Declines)

McClellan Oscillator = 19-day EMA of RANA –  39-day EMA of RANA

Looking online, I found it difficult to find any consistent definition on how this oscillator should be used.

According to one article, you should be bullish when the McClellan Oscillator moves above zero and bearish when it moves below zero.

I tested this on the SPY ETF and the results were poor. I also tried a number of other variations which also showed net losses. The best result came from a strategy taken from Futures Mag.

McClellan Oscillator in Amibroker with SPY.

McClellan Oscillator Strategy

  • Buy SPY when the McClellan Oscillator moves to between -70 and -100, then turns up.
  • Sell SPY when the McClellan Oscillator moves to between 70 and 100, then turns down.

In other words, we are looking for the indicator to move down into an oversold range before turning back upwards.

This strategy generated an annual return of 9.61% with a maximum drawdown of –24% and a win rate of 76% over 45 trades between 1/1994 and 1/2017.

This compares to a buy and hold return between 1/1994 – 1/2017 of 9.09% with a max drawdown of -55%.

This indicator has some interesting characteristics and it is always nice to see a win rate above 70%. You can see the equity curve below:

5) Number Of New 52-Week Lows

The final stock market indicator we will look at today is the number of stocks making new 52-week lows in comparison to the index itself.

This is a classic indicator that can be used to measure strength in the prevailing trend and is also useful when looking for divergence.

You can see that in the chart below the number of stocks hitting new 52-week lows hit a peak of over 400 (out of 500) in 2008.

New 52-week low divergence example in Amibroker with SPY.

New 52-Week Lows Divergence Strategy

  • Buy SPY when it closes at a new 20-day low but the number of stocks making new 52-week lows goes down.
  • Sell five days later.

This strategy is based on divergence. The index has hit a new low but the stocks that make up the index have not made new 52-week lows. This suggest the downward trend is weakening and an upturn could be on the cards.

This strategy produced an annualized return of 3.74% between 1/1994 and 1/2017 with a maximum drawdown of -14% and a win rate of 62% over 100 trades.

Below you will find the equity curve produced in Amibroker:

Conclusions

There are countless numbers of different indicators on the market but few are able to generate profits superior to buy and hold. We have looked at five indicators here and the results are mixed.

The Coppock Curve Indicator, McClellan Oscillator, and Number of New 52-Week Lows Divergence strategy look fairly interesting and they might be useful for day traders or as market timing filters.

For example, traders could use these indicators to only take trades when certain conditions line up. These strategies might also be enhanced with extra leverage or adapted for futures.

As usual, the data proves there is no easy money available in the stock market despite what is claimed by the inventors and promoters of simple market indicators.

--by Joe Marwood from blog Jbmarwood.com

The post Five Stock Market Timing Indicators Put To The Test appeared first on System Trader Success.

The MVCI (Whatever That Means) Indicator

$
0
0

Some people tell me that I have “too much time on my hands” because I spend so much time “crunching numbers”. I tell them, “That’s ridiculous, I don’t have any time on my hands because I am so busy crunching numbers”. (That usually shuts them up. At least for a little while).

In any event it is true that I am something of an “indicator junkie”. And it is also true that sometimes I multiply two numbers together (or divide two numbers) just “because I can”. And every once in awhile something potentially valuable seems to surface (see Applying VIX(like) Indicators to Stocks).

But in the most recent case I am hoping that someone can help me here. Not so long ago, I came across an indicator referred to by the acronym of MVCI – or at least that’s what I recorded it as. I just can’t remember where I read about it. In fact I don’t even recall what MVCI stands for.

But I like what I’ve seen of it so far.

The MVCI Indicator Calculations

OK, what follows is a list of a fairly lengthy set of calculations. If you are not a “numbers geek” you might consider skipping down to the actual results.

A = Daily High

B = Daily Low

C  = Daily Close

D = 200-day moving average of daily closing prices

E = Daily True High (Today’s high or yesterday’s low, whichever is greater)

F = Daily True Low (Today’s low or yesterday’s high, whichever is lower)

G = Daily True Range (E-F)

H = Average Daily Price (A + B) / 2

I  = 15-day Average of H

J = 15-day Average of G

K = MVCI = (C-I) / (J * Square Root of 2))

L = Buy Signal Cutoff Value

M = # days to hold a long position

Figure 1 displays an Excel spreadsheet with these calculations.

Figure 1 – Excel spreadsheet for MVCI (whatever that means) Indicator

Hmmm, maybe I do have too much time on my hands. But I digress. In (slightly long-winded) English, the indicator is calculated by:

1) Subtracting the 15-day average of the average daily price (defined as ([high]+[low]/2)) from today’s closing price, and dividing that result by;

2) The 15-day average of the Average True Range times the square root of 2

Don’t ask me how someone came up with multiplying something by the square root of 2 because, well, heck I don’t even know what MVCI stands for, so how would I know?

The default value for variable L is -0.51. The default value for M is 22 days.

A “Buy Signal” occurs when:

1) The closing price for SPY is above its 200-day simple moving average AND;

2) The MVCI value for that day is -0.51 or less. So when a buy signal occurs the trader buys SPY and holds it for 22 trading days.

If MVCI drops below -0.51 during these 22 days then the 22-day holding period starts again at 22, i.e., positions can be held for longer than 22 days.

Figure 2 displays the fluctuations of the MVCI since 12/31/2012 with the -0.51 level highlighted in red.

Figure 2 – The MVCI (whatever that means) indicator in action

So in a nutshell, anytime SPY is above its 200-day moving average each day the MVCI is below -0.51 starts a 22-day holding period.

Crazy, right?

Well, maybe we should consider the results first.

The Results

OK, so SPY started trading in 1997, to get a 200-day moving average we can start testing in June of 1998. If we start with $1,000 and invest in SPY for 22 trading days following any day where MVCI drops to -0.51 or below, we get the equity curve that appears in Figure 3. No interest is earned while out of the market and buying and holding SPY is also plotted in red.

Figure 3 – Growth of $1,000 using MVCI (blue) versus Buying and Holding SPY (red); 1998-2015

For the record:

-$1,000 invested in SPY using MVCI in the manner described here grew to $4,417 (+342%)

-$1,000 invested in SPY on a buy-and-hold basis grew to $1,848 (+84.8%)

Maybe not so crazy, right?

Summary

For the record, please note that I do not actually use this indicator at the moment in any of my trading, nor am I recommending that you start using it either. I have this rule – well, OK in the immortal words of Bill  Murray, “it’s more like a guideline” – that I don’t use indicators when I don’t even know what they’re freaking called.

But the purpose of this blog is not to offer “advice” or to tell you what to do. Its purpose is simply to educate you and give you something to think about that you might not otherwise.

Like for instance, “What the heck does MVCI mean?”

–by Jay Kaeppel from blog Jay On The Markets

The post The MVCI (Whatever That Means) Indicator appeared first on System Trader Success.

Down Days Trading Model

$
0
0

I’ve written a lot about the 2-period RSI indicator popularized by Larry Connors and Cesar Alvarez. This indicator highlights significant pullbacks which can often be buying opportunities within major market indexes like the S&P.  Pullbacks in the market are a result of the market closing down. That means, today’s close is lower than the open. So, can this simple price action be used to locate buying opportunities. In this article I’m going to take a look at this price pattern and compare it to our the 2-period RSI setup. Free EasyLanguage code will be provided at the conclusion of this article.

Mean Reversion As a reminder, the traditional two-period RSI indicator (RSI(2)) is an indicator we have used many times on this website. So I will not spend much time talking about it within this article. Overall, it’s primarily used on the stock index markets such as the S&P, as a method to determine an entry point for a mean reverting trading models. You can read more about the RSI(2) indicator and the trading models built from it by reviewing these articles:

Down Days Setup I’m going to use EasyLanguage in order to build a trading model to test the effectiveness buying the S&P after two consecutive down days. To build this simple trading model I’m going to assume that a down day is defined when the market closes below its open. I’ll sell the position when we have just the opposite condition, two consecutive up days. That is, two days when the market closes above its open. The trading rules are:

  • Buy at the open of next day after two consecutive down days
  • Sell at the open of next day after two consecutive winning days The EasyLanguage code for the basic strategy will look something like this:
Variables:
BuySignal(false),
SellSignal(false);
BuySignal = ( Close < Open ) And ( Close[1] < Open[1] );
SellSignal = ( Close > Open ) And ( Close[1] > Open[1] );
If ( BuySignal ) then Buy("LE") next bar at market;
If ( SellSignal ) then Sell("LX") next bar at market;

Testing Environment {#testing-environment} Because you, the reader might want to build a trading model based upon this market study, I’m going to break the historical data into two portions. An in-sample portion and out-of-sample portion. I will perform my testing for this article on the in-sample portion only. Thus, when I’m finished with my testing we’ll still have a good amount of data which can be used for out-of-sample testing. Before getting into the details of the results, let me say this: All the tests within this article are going to use the following assumptions:

  • Starting account size of $25,000
  • In-sample dates are from 1998 through December 31, 2012
  • One contract was traded per signal
  • $30 was deducted per round-trip for slippage and commissions

Baseline Results {#baseline-results} Below is the baseline results over our in-sample historical segment. The maximum drawdown is a percentage of our starting equity, which is $25,000. Keep in mind that this study has no stops, thus some positions will hold through some very deep pullbacks before exiting. Again, we are testing the behavior of the market buy building a trading model. In other words, we don’t have a complete trading system.

Losing Streak

Baseline

Net Profit

$25,800

Profit Factor

1.17

Total Traders

300

%Winners

63%

Avg.Trade Net Profit

$86.00

Annual Rate of Return

4.89%

Max Drawdown(Intraday)

79%

Longer Consecutive Losing Days The first thing that I noticed when looking at two consecutive down days is it may not be deep enough. Two-day pullbacks are somewhat common. Market pullbacks during the last few years of the study have been shallow and these have been great entry points. But what about helping to ensure this trading model will work under different conditions? Testing three or four days consecutive losing days may generate more profitable and/or more tradable results. For past experience I know, in general, deeper pullbacks may provide a better profit vs risk. That is, the generated signals will be fewer in number but will also provide better rewards. So I modified the code and generated the following results based upon the number of consecutive down days required before opening a new position. During this testing I did not modify the exit rules. They remained the same with two consecutive up days acting as the exit trigger.

Losing Streak

Baseline

3 Days

4 Days

Net Profit

$25,800

$32,290

$31,925

Profit Factor

1.17

1.37

1.83

Total Traders

300

177

85

%Winners

63%

64%

71%

Avg.Trade Net Profit

$86.00

$182.43

$375.59

Annual Rate of Return

4.89%

5.72%

5.67%

Max Drawdown(Intraday)

79%

66%

64%

As expected we see the number of trades decreases and the average profit per trade increases as we increase the number of down days. Deeper pullbacks happen less often, but have larger payouts based on our trading model. The four down days has only 85 trades so I’m going to use the three down days during the remainder of my testing. This is a good compromise as a three-day pullback does appear to eliminate many shallow and unproductive pullbacks. Below is the equity graph for the three down day trading model.

Bull/Bear Regime Filter The next characteristic to explore is the difference between a bull and bear market. I’ll divide the market into two regimes based upon a 200-day simple moving average. The market will be “bullish” when price is trading above the 200-day SMA. The market will be “bearish” when price is below this moving average. Below is the trading model’s results in each regimes.

Losing Streak Regime Test

Bull only

Bear only

Net Profit

$14,542

$29,530

Profit Factor

1.39

1.57

Total Traders

94

94

%Winners

69%

62%

Avg.Trade Net Profit

$154.71

$314.15

Annual Rate of Return

3.16%

5.38%

Max Drawdown(Intraday)

54%

73%

Surprisingly, at least to me, we see better performance with the bear market. Overall, both the bull and bear regimes are profitable. The bear regime does suffer from larger drawdowns but it also has the biggest rewards. Notice that both regimes also have the same number of trades. I checked this a couple of times and it does appear to be correct. Given this result, I will not include a regime filter as we test our final modification I wish to test.

5-Day SMA Exit The 5-Day SMA Exit closes a position once price closes above a 5-day simple moving average. This exit is often used with the RSI(2) system and it’s worth testing here as well. Below are the results of this test vs our baseline. As a reminder, the Baseline column represents the three down day trading model with a 2-day exit.

Losing Streak Exit Test

Baseline

SMA Exit

Net Profit

$32,290

$43,475

Profit Factor

1.37

1.68

Total Traders

177

205

%Winners

64%

67%

Avg.Trade Net Profit

$182.43

$212.07

Annual Rate of Return

5.72%

6.95%

Max Drawdown(Intraday)

66%

30%

The power of a good exit! By changing the exit to our 5-day simple moving average we have significantly improved the performance. All metrics have improved. Notice the significant reduction in drawdown. This is huge. So how does this hold up against the 2-period RSI trading model? Let’s see…

RSI(2) vs Consecutive Down Days Below is the results of using a two-period RSI with a threshold of 10 vs our 3 down day trading model. Both trading models exit when price crosses the 5-day SMA.

Losing Steak VS RSI (2)

Baseline

RSI (2)

Net Profit

$43,475

$45,960

Profit Factor

1.68

1.68

Total Traders

205

183

%Winners

67%

68%

Avg.Trade Net Profit

$212.07

$251.15

Annual Rate of Return

6.95%

7.19%

Max Drawdown(Intraday)

30%

68%

So which one is better? They are very similar in most of the metrics. The maximum drawdown is a lot higher with the RSI(2) system. Again, neither of these tests utilize a stop. Overall, these are very interesting results and may be an effective replacement for the RSI. I encourage you to perform your own testing to see if this simple price pattern could be used in your own trading. Below you will find the EasyLanguage code for code used in this study.

Downloads

Down Days Strategy (text file) Down Days Strategy (TradeStation ELD file) Down Days WorkSpace (TradeStation WorkSpace file)

The post Down Days Trading Model appeared first on System Trader Success.

Battle of the Oscillators…Round 2

$
0
0

In a past article, Predictive Indicators written by John Ehlers, he highlighted a unique indicator used to time market cycles. This indicator is a heavily modified Stochastic Oscillator and was demonstrated on the S&P. In this article, I want to put John’s Oscillator to the test by comparing it to another popular indicator Backtesting Environment for this entire article, the backtest will be conducted from January 1, 2000 to December 31, 2016. I will be deducting $5 in commissions and two-ticks of slippage per round trip. I will trade one contract per signal on a $100,000 account. Profits will not be reinvested. The backtest will be conducted on a basket of index futures. The markets I will use are:

  • E-mini S&P
  • E-mini DOW
  • E-Mini NASDAQ
  • E-Mini RUSSEL 2000
  • E-Mini S&P MidCap 400

 John’s Oscillator Performance

These are interesting results and seem to verify that for these stock index markets, this indicator is a decent predictor of market turning points. We have a profit of over $434K which gives us a compounded annual rate of 10.36%. The profit factor is 1.33 and drawdown only exceeded 18% once. Let’s now compare it to another popular indicator used to locate potential turning points.

​In the 2-period RSI Oscillator I created a simple strategy to open long trades when the 2-period RSI crosses below 10 and to sell short when price crosses above 90. This is a similar concept to John’s Oscillator as both strategies are either long or short. Below are the results of this strategy.

In this case, we can see the 2-period RSI under perform John’s Oscillator. Not only does it underperform in terms of net profit, profit factor, sharp ratio, and average annual return but the drawdown is larger. We have a profit of over $235K which is about $199K less than John’s Oscillator. The compounded annual rate is 7.37%. The profit factor is 1.24 and drawdown exceeds 20% many times and peaks at around 48%. John’s Oscillator does appear to pick turning points better than the 2-period RSI on the stock index markets. Using John’s Oscillator combined with these markets might just be a great place to start building a profitable trading system. In a future article, I’m going to compare it to a few other indicators and then move to other markets such as currency futures, commodities, and bonds.

Downloads

The post Battle of the Oscillators…Round 2 appeared first on System Trader Success.

Capture The Big Moves!

$
0
0

Wouldn’t it be great to have an indicator to help tell you when we are in a major bull or bear market? Imagine if you had a clear signal to exit the market on January 19, 2008 before the major market crash. Then the same indicator told you when to get back into the market on August 15, 2009. Such an indicator would have also gotten you out of the market during the dot-com crash on November 11, 2000. Well, this indicator I’m going to talk about does just that.

Below you will also find the EasyLanguage code for this indicator. This major trend indicator was inspired by an article entitled “Combining RSI With RSI” by Peter Konner, and it appears in the January 2011 issue of Technical Analysis of Stocks and Commodities.

How It Works
We are going to start with a well-known indicator: the Relative Strength Indicator (RSI). The goal is to identify major bull market and bear market regimes. In his article, Peter does this by simply using an RSI indicator on a weekly chart and identifying two unique thresholds. Peter noticed that during bull markets the RSI rarely goes below the value 40. On the other hand, during a bear market the RSI rarely rises above the value of 60. Thus, you can determine the beginning and ending of bull/bear markets when the RSI crosses these thresholds. For example, in the bear market during the financial crisis of 2008 the weekly RSI indicator did not rise above 60 until August of 2009. This signaled the start of a new bull trend. The next bear trend will be signaled when the weekly RSI falls below 40. This is clear in the images just below. With these simple rules you are able to determine bull and bear markets with a surprising amount of accuracy given the S&P futures market.

The two images below show the SPY ETF on a weekly chart. Below the price is a second pane with a 12-period RSI. Why a 12-period RSI? I simply chose that number because it represents a quarter of a year of trading, if you figure four weeks in a month. There was nothing optimized about this number, it just seemed to be a logical starting point. Other lookback values will produce very similar results.

In the image below (click to enlarge) you will see the RSI signal stays above the 40 level during the strong bull market of the 1990’s.

RSI In Bull Market Does Not Go Below 40 Often.

In the image below (click to enlarge) you will see the RSI signal stays below the 60 level during the strong bear market in the financial crisis of 2007-2009.

RSI In A Bear Market The Does Not Often Rise Above 60

As you can see the RSI appears to do a fairly decent job of dividing the market into bull and bear regimes. You will also notice the RSI indicator paints red when it goes below 40 and only returns to a light blue when it rises above 60. It is these critical thresholds which highlight a significant turning point in the market that may be occurring.

Modifying RSI
I personally found the RSI signal a little choppy. I decided to make two modifications to help smooth the raw RSI signal. First, the input into the RSI indicator was modified by taking the average of the high, low, and close. The RSI value is also smoothed with a 3-period exponential moving average. The resulting EasyLanguage code looks like this:

RSI_Mod = RSI( (c+h+l)/3, RSI_Period );
Signal = Xaverage( RSI_Mod, 3 );

These two modifications will smooth out our RSI signal line. Next, I want to test the RSI lookback period. To do this I create a simple strategy using EasyLanguage. I open a long position when the RSI crosses above the 60 value and sell short when it crosses below the 40 value. The strategy is always in the market either going long or short. Just as a side note, the system I’m developing is not necessarily a trading system. Instead it’s an indicator to help determine the market regime: bull or bear. While I use the word “strategy”, it’s not a trading system.

Testing Lookback Periods

I’m curious to see how well this strategy holds up over various lookback periods. Ideally, the a strategy should be robust enough to produce solid results over a range of lookback periods. To test this aspect of the strategy I’m going to use TradeStation’s optimization feature to optimize the lookback period over the values 2-24.

The first chart is the lookback period (x-axis) vs the net profit (y-axis).

Lookback Period vs Net Profit

The above chart shows rising profit as the lookback period increased from 5 to 17. Then it begins to fall off. Let’s look at this from a different angle: profit factor. The next chart is the lookback period (x-axis) vs the profit factor (y-axis).

Lookback Period vs Profit Factor

We see a similar picture but there is more of a stable region between 16-24. I would think that between these values we could find a good lookback period. When I originally looked at this concept back in 2011, I picked 16 as a value. I don’t recall why I did that, but it’s certainly not an outline, and I’ve decided to continue to use this value for this article. If starting over from scratch, I may pick a value of 20, which is midway between 16 and 24. Feel free to experiment on your own. The main point here is this: all the values produce positive results and a wide range of values at the upper end of our scale generate very good results (high profit factor and high profit). This leads me to believe that this indicator is robust in signaling major market changes.

Testing Environment

I decided to test the strategy on the S&P cash index going back to 1960. The following assumptions were made:

  • Starting account size of  $100,000.
  • Dates tested are from 1960 through September 2015.
  • The number of shares traded will be based on volatility estimation and risking no more than $5,000 per trade.
  • Volatility is estimated with a three times 20-week 40 ATR calculation. This is done to normalize the amount of risk per trade.
  • The P&L is not accumulated to the starting equity.
  • There are no deductions for commissions and slippage.
  • No stops were used.

Results

Applying this to the S&P cash index we get the following overall results.

Notice the short side loses money. I would guess this tells us over the life of the market, there is a strong up-side bias. I would also guess that since 2000 the short side probably produces a profit, but I did not test that idea. Below is the equity curve of the strategy.

Here is what the strategy looks like when applied to the price chart over the past few years. You will also notice I painted the price bars based upon the RSI signal. Light blue price bars mean we are in a bull market and red price bars mean we are in a bear market. You can clearly see how the RSI indicator defines the financial bear market and reenters at the start of the new bull market in 2009.

Using this indicator we come up with the following turning points for major bull and bear markets for the US indices. The blowup of the dot-com bubble happened in 2000 and we got out in November 11, 2000. The indicator then tells us to go long on June 7, 2003. We then ride this all the way up to the financial crisis getting out of the market on January 19, 2008. Then on August 15, 2009 we go long. A failed signal occurred in mid 2011. Overall, not too bad!

How Can This Indicator Help You?
Looking at these dates we see that they are fairly accurate in capturing the major bull and bear regimes of the US stock indices. However, the short trades are not profitable. In my opinion during these short times you're better off to step aside. That is close, long positions and move to cash without attempting to short.

How can this be used in your trading? Perhaps you can use this as a basis for a long-term swing strategy. Maybe this is an indicator to let you know when to go long or liquidate your long positions within your 401(k) and other retirement accounts. Or perhaps if you are a discretionary trader you can use this to focus on taking trades in the primary direction of the the indicator. Maybe when the RSI indicator signals a bull market you may want to view this as another confirmation or green-light to pursue whatever investment strategy you prefer. Anyway, I thought it was an interesting and novel way looking at the RSI indicator.

Of course we only have 35 signals over the past 53 years. This is hardly a representative sample if we are talking about statistics. However, given the robust nature of the lookback period and the rising equity curve since 1960 this indicator may be worth keeping an eye on.

Where Are We Now?
Recent market behavior at the end of 2018 and going into the new year resulted in this indicator signaling Bear Market. The signal triggered on the week of December 28, 2018. This ends the Bull Market signal which occurred on July 22, 2016.

The previous Bear signal was on September 4, 2015. The last signal was a false signal. Will this be another false Bear signal? Who knows?

Bear Market Signal Since December 28, 2018

The post Capture The Big Moves! appeared first on System Trader Success.

Viewing all 40 articles
Browse latest View live


Latest Images