trading strategy – Helping you Master EasyLanguage https://easylanguagemastery.com Helping you Master EasyLanguage Tue, 24 Jan 2023 22:48:03 +0000 en-US hourly 1 https://wordpress.org/?v=7.0.2 https://easylanguagemastery.com/wp-content/uploads/2019/02/cropped-logo_size_icon_invert.jpg trading strategy – Helping you Master EasyLanguage https://easylanguagemastery.com 32 32 A Complementary Approach To Trading Technical Indicators https://easylanguagemastery.com/building-strategies/a-complementary-approach-to-trading-technical-indicators/?utm_source=rss&utm_medium=rss&utm_campaign=a-complementary-approach-to-trading-technical-indicators https://easylanguagemastery.com/building-strategies/a-complementary-approach-to-trading-technical-indicators/#comments Mon, 21 Aug 2017 10:00:08 +0000 http://systemtradersuccess.com/?p=3960

In the October issue of Futures magazine, author Jean Folger discusses an important aspect in selecting two or more indicators when developing a trading system. While I don't recommend simply combining indicators to create a trading system, and I don't think that's what Folger is suggesting either, when there comes a time to introduce two or more technical indicators to a trading system, this is when Folger's advice is relevant. The author highlights a common mistake when selecting two or more indicators that could really hinder the performance of your system. By following Folger's advice you can multiply the effectiveness of your system by selecting two or more indicators when done properly.

Types of Indicators

When it comes to technical indicators we are talking about mathematical formulas that are applied to price or volume. These technical indicators include MACD, Moving Averages, Stochastics, ADX, ATR, CCI, and many others. Folger first organized these indicators into different categories based upon what they are measuring.

  • Trend - ADX, Moving Averages, MACD, Parabolic SAE
  • Momentum - CCI, RSI, Stochastics
  • Volatility - ATR, Bollinger Bands, Standard Deviation
  • Volume - Chaikin Oscillator, OBV, Rate of Change

Selecting Two Indicators

When it comes to selecting two indicators the mistake can be from selecting two from the same category. By selecting from the same category you are measuring the same market characteristics (Trend, Momentum, Volatility, or Volume). In this case you're not getting new information about the market. For example, if you select ADX and Moving Average you are simply looking at the trending characteristics of the market. I'm a believer in keeping things simple and if you are introducing two indicators that are telling you the same thing, this is not helpful and it needlessly complicates your trading system. Each indicator should be dedicated to a specific purpose, not telling you the same thing two different ways. The point is to look at different market characteristics to expand your view. This can be done by selecting two indicators from different groups, say from Trend and Momentum. Now you are gathering complementary information about the market and are better prepared to make a decision.

Example

An example strategy will make this concept even more clear. I'll take Folger's lead and create a similar strategy used in the original article. Let's create a simple strategy for the S&P E-mini futures market. We'll use a daily chart just to keep things simple. No slippage or commissions will be deducted. Entry signals will generate with the stochastic indicator move out from its overbought/oversold regions. The system will simply reverse its current position thus, we are always in the market.

  • Go Long when the SlowD line crosses above 20
  • Go Short when the SlowD line crosses below 80

Below are the results of this strategy.

One Indicator

One Indicator

Net Profit

$4,325

Profit Factor

1.03

Total Trades

137

%Winners

58%

Avg.Trade Net Profit

$31.57

Annual Rate of Return

2.08%

Sharpe Ratio

0.06

Max Drawdown(Intraday)

$50,325

Now let's try a complementary indicator. One technique I would like to utilize a lot is the use of a simple moving average to divide the market into two different regimes: bull market and bear market. Often a 200-period moving average applied to a daily chart will work just fine. However, Folger suggested an SMA crossover method to determine the market regime. A 50-period moving average and a 60-period moving average. If the 50-period SMA is above the 60-period SMA the market is considered in a bullish regime. Otherwise the market is considered in a bearish regime. Let's apply this filter here.

  • Go Long when the SlowD line crosses above 20 and within Bull Market
  • Go Short when the SlowD line crosses below 80 and within Bear market

With these rules added to our buy condition we have introduced a trend-based filter. This should reduce unproductive trades by only taking trades in the direction of the dominate market regime. As a result this should reduce the total number of trades and increase the profitability of our strategy.

Below are the results of this strategy.

Complementary Indicators

One Indicator

Two Indicators

Net Profit

$4,325

$48,275

Profit Factor

1.03

1.5

Total Trades

137

57

%Winners

58%

47%

Avg.Trade Net Profit

$31.57

$846.93

Annual Rate of Return

2.08%

10.18%

Sharpe Ratio

0.06

0.10

Max Drawdown(Intraday)

$50,325

$34,825

As you can see using two complementing indicators can really improve the results. Keep this in mind when developing a trading system. The example trading strategy is, of course, not a tradable system. It's only an example of how applying a complementary indicator to filter trades can improve the trading system's performance. I personally use this technique a lot. It really can do wonders for a trading system. You will find below the code used in this article along with a TradeStation workspace.

]]>
https://easylanguagemastery.com/building-strategies/a-complementary-approach-to-trading-technical-indicators/feed/ 6
The Death Cross – What You Need To Know https://easylanguagemastery.com/building-strategies/the-death-cross/?utm_source=rss&utm_medium=rss&utm_campaign=the-death-cross https://easylanguagemastery.com/building-strategies/the-death-cross/#respond Mon, 07 Sep 2015 10:00:00 +0000 http://eminiedges.com/wp/?p=957

On August 31, 2015 an indicator called “Death Cross” appears on the S&P cash index. This has not happened since 2011. The Death Cross is simply when a 50-period simple moving average (SMA) crosses under a 200-period SMA on a daily chart. Such a signal is believed to warn of upcoming bearish market activity. The opposite signal is called a “Golden Cross”, and is alleged to warn of bullish market activity. But does the Death Cross or the Golden Cross hold any merit? What can we learn from these signals and how can we use this information in our trading? In this article I’m going to demonstrate why the Death Cross is important and why its opposite signal, the Golden Cross, may be even more important.

Both the 50-period SMA and the 200-period SMA are well known moving averages. Thus a lot of eyes are watching price around these levels. It’s no surprise when these moving averages cross the event and might be worth noting.  One way to test how well the Death Cross and Golden Cross perform historically  is to create a simple trading system based upon these signals. Using TradeStation’s EasyLanguage coding language it’s simple to create a trading system that is always in the market switching between a long position and a short position based upon a moving average crossover. Here is what the entire trading system code looks like:

if ( Average(Close,50) crosses above Average(Close,200) ) then buy(“Golden Cross”) next bar at open;
if ( Average(Close,50) crosses under Average(Close,200) ) then Sell short(“Death Cross”) next bar at open;

Below is the most recent Death Cross. You can see the faster moving average (black) has dipped below the slower moving average (red).

Testing Environment

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:

  • Amount dedicated to each trade $100,000
  • Long only
  • The P&L is not accumulated
  • $30 was deducted per round-trip for commissions

In order to get a long-term feel for this system I’m going to use the S&P500 cash index going back to 1961. The trading system will trade a fixed dollar amount to each trade. In this case, $100,000.

Before we start looking at some of the numbers I want to break this study into two parts: Shorting a Death Cross vs. going long the Golden Cross. What interests me is how well the system functions going long vs going short. In other words, what does the SMA cross tell us about a bearish cross vs a bullish cross? Are they different?

Shorting The Death Cross

Since we recently experienced a Death Cross, let’s first look at shorting every Death Cross signal. The equity graph is below and it’s not pretty.

What does this tell us? To simply short the Death Cross may not be very profitable. We can see the equity curve hangs around the zero line for decades. In recent times it has climbed from negative territory to just below the zero line. Yet, there is nothing in this picture that suggests we have an edge simply shorting the S&P index upon a Death Cross signal. Below is a graph of the week drawdown experienced while shorting the Death Cross.

This is an ugly picture where you have many trades where drawdowns reached 30% or more. At some points you have to endure drawdowns of up to 65%. That’s massive heat you must take and what is your reward? Not to make any money! Simply using the Death Cross and Golden Cross as a timing signal does not appear to be a good use of your time.

Going Long The Death Cross

Maybe we should be taking the Death Cross as a buying opportunity? Why not? We want to be opposite the crowd, right? Below is the equity graph when we go-long at every Death Cross and exiting our trade when the Golden Cross appears.

Interesting! At times going long actually makes money and notice how the equity graph spends a lot of its time above the zero line. Furthermore, unlike shorting the Death Cross, going long actually produces a positive result. Not much of a result but the equity graph does end in positive territory. Counter intuitive to common knowledge, I would say. Yet, it’s not much of a profit for all those years of trading and it’s certainly not an edge we can take advantage of. All in all this strategy is a wash much like shorting the Death Cross. This graph probably reflects the fact that the S&P 500 has had a bullish bias since 1961.

The equity graph also shows that during those periods imminently after a Death Cross and before a Golden Cross we have continued market weakness. In other words, not many market gains take place when the 50-period SMA is below the 200-day SMA. In general, this appears to be a time of market weakness.

Let’s take a quick look at the drawdown one would have to endure with this type of strategy.

Not as bad as shorting, but there are two spikes of 50%. There is also plenty of time spent around the 20% drawdown mark. That’s still some ugly drawdown that would be very painful to endure.

Going Long The Golden Cross

Next let’s look at going long the Golden Cross and Exiting on on the Death Cross.  Below is the equity graph.

This is a much improved equity graph! We seem to have a clear edge going long the S&P cash index when a Golden Cross is triggered. This graph highlights the fact that when the 50-period SMA is above the 200-day SMA the market often exhibits strong bullish behavior. Below is the drawdown experienced by this system.

Here drawdown is limited to a maximum of around 12%. This is a massive improvement from our previous signals we looked at. A 12% drawdown is much more tolerable. Clearly when a Golden Cross shows up it appears to be the “all-clear” sign in terms of both reward and risk. That is, we see substation market gains and low drawdown.

Summary

Combining what we have now learned I would say it might be wise moving your investing accounts into cash when a Death Cross takes place. This would be done in my opinion to prevent drawdown and thus avoid the pain seeing your profits evaporate. After a Death Cross drawdowns over 50% can take place and we see the upside is limited. It’s certainly can be much more psychologically appealing to be in cash when those big bear markets hit. Shorting a Death Cross does not have much of an edge and you often see massive drawdown with little profit as well.  It’s only after a Golden Cross does the market hold a strong bullish edge.

The table below shows the performance of each system.

Short Death Cross

Long Death Cross

Long Golden Cross

Total Net Profit

-$19,742

$18,122

$442,921

Profit Factor

0.86

1.14

18.52

Total  Trades

27

27

28

% winners

30%

70%

82%

Avg.Trade Net Profit

-$741

$671

$15,818

Annual Rate of Return

-0.33%

0.30%

3.08%

Max Drawdown (intraday)

76%

62%

11%

Avg Time in Market

220 days

220 days

500 days

By comparing the market behavior during a Death Cross vs a Golden Cross we can come to some generalizations that might help in both your investing accounts as well as your trading accounts (depending upon your timeframe). Of course the results of this article are based upon the S&P cash index, not individual ETFs or stocks. Thus the results could be generalized for a broad U.S. tradable index like SPY. Of course, you must do your own testing!

Death Cross = Move To Cash: During this time the market shows general weakness to the upside. This weakness can be difficult to short and drawdowns can be very substantial.  Moving into cash during this time may prevent you from experiencing these significant drawdowns. Remember, we are not talking about day trading in this article. The Death Cross and Golden Cross are based upon slow moving averages that work best for long term holding periods. A skilled day trader can make a lot of money shorting during a bear market, of course. However, when it comes to using a slow timing method such as the Death Cross, it does not seem to pay off.

Golden Cross = Invest: Upon a Golden Cross signal the market has demonstrated a lot of bullish activity with low drawdown. It appears to be the “all clear” signal to enter the market once again. When a Golden Cross occurs, we should be looking to go long.

]]>
https://easylanguagemastery.com/building-strategies/the-death-cross/feed/ 0
A Statistical Method For Stop Placement https://easylanguagemastery.com/building-strategies/a-statistical-method-for-stop-placement/?utm_source=rss&utm_medium=rss&utm_campaign=a-statistical-method-for-stop-placement https://easylanguagemastery.com/building-strategies/a-statistical-method-for-stop-placement/#comments Mon, 24 Mar 2014 10:00:11 +0000 http://systemtradersuccess.com/?p=3712

In the September 2012 issue of Futures magazine, author Neil Rosenthal began a multi-part series on system development. During the first series Neil uses MetaTrader 4 (MT4) to code a simple system and demonstrates how he uses Excel to analyze the results as the first step to building a trading system. After discovering a market edge – what I call a key concept – Neil demonstrates his process of finding an initial hard stop value for his system. I found his method similar to what I use. I thought it would be helpful if I recount his method here.

While many people focus on the specifics of a trade entry, trade exit is also vitally important. After you have discovered what you think is a solid “key concept” the next question you may wish to explore is: Where should the initial stop be placed? Within Neil’s article he calls this his ISL (initial stop loss).

The Trading System

Because we are not focusing on a specific trading system I’m going use Neil’s idea of using a random entry method. That is, upon the open of the market a virtual coin will be flipped. If the coin comes up heads, we go long. If it comes up tails, we go short. This will take the focus off the trading system and place the emphasis on the true point of this article, how to determine where to place your ISL. Indeed, this process is applicable to all system trading development.

I’m going to trade this on the Euro currency futures market and will use the 830 open (Central) as the time to open a new trade and the 1500 close (Central) to close the trade. Trades will be executed and managed on a 5-minute bar chart. Below is the TradeStation code that will act as the foundation of our trading system. If you are familiar with the steps I use to develop a trading system, you will recognize this stage of development as the “Baseline” system. This Baseline system will act as our stake-in-the-ground or reference point to compare the modified version against.

vRandomNumber = Intportion( Random(100) );
If ( vRandomNumber >= 50 ) Then buy("LE") next bar at market
Else sellshort("SE") next bar at market;

The results

The system was executed over a five-year period ending July 31, 2012. No slippage or commissions were deducted from the results. The test generated 1,269 trades. The number of short trades (625) accounted for 49% of the trades and the number of long trades (644) accounted for 51% of the trades. As expected the number of winning trades is near the 50% mark at 51%. You can see that this system actually produced a positive net profit of $27,200 with an average trade of $21.43. If we factor slippage and commissions the system would appear to be a break-even system.

We can probably improve the average profit per trade by limiting what we lose on trades that move against us. This is the purpose of having an ISL. By using an Excel spreadsheet to analyze the maximum adverse excursion (MAE) for our winning and losing trades we can help narrow down a proper value for our ISL. MAE is the amount a trade moves against us. For example, if we open a trade that immediately climbs to a profit of $100, then falls to $75 into the red before we finally close the trade at our $250 profit target, our MAE would be $75.

So we now know we wish to examine the MAE of our system, but how do we do that?

TradeRecorder
Fortunately, I created an EasyLanguage function called Trade Recorder which does exactly what we need. By placing this function within our strategy code all our required trade information is sent to an Excel formatted file on our hard drive. From there it’s just a matter of cutting-and-pasting our trade information into another Excel spreadsheet to analyze our results. Please read this article for a more complete description on what Trade Recorder can do.

Data Analysis
Now that we have all the trades in an Excel file I can take this data and cut-and-paste it into another spreadsheet called Trade Analysis, which is available at the bottom of this article. This spreadsheet is nothing fancy but will compute what we are looking for. Using the sort feature in Excel I can separate the winning and losing trades. Then I can use Excel’s built in functions to generate the mean and standard deviation of the MAE values.

Below are the values generated by Trade Analysis for our example run of our trading system.

In our example trading system we can see winning trades have a mean MAE of around 19 ticks. This suggests that a stop value smaller than this value will likely result in stopping-out of winning trades. In other words, the stop value would not be large enough. On the other hand, if we look at our losing trades we can see the mean MAE is 72 ticks.  Such an extreme move against us is unlikely to produce a positive trade and we should be looking at cutting our losses. Notice how losing trades move strongly against our position while winning trades take much less “heat”. With this information we already have a ballpark idea on where to place our ISL. Furthermore, the same analysis can be done with the maximum favorable excursion (MFE) to help us locate a proper profit target to test. But more on that later.

While it may be tempting to place a stop just beyond our 19 tick mean, a more optimal number can be found by using optimization. We are not done yet on determining our ISL. However, it will have to wait for a future article.

Video

Below is a video that explains in detail on how to use the Trade Recorder function with the Trade Analysis spreadsheet. These two tools can be used to help you determine your ISL for systems you develop. Both these tools are available as a free download at the bottom of this article.

]]>
https://easylanguagemastery.com/building-strategies/a-statistical-method-for-stop-placement/feed/ 9
Predictive-Model Based Trading Systems Part II https://easylanguagemastery.com/building-strategies/predictive-model-based-trading-systems-part-ii/?utm_source=rss&utm_medium=rss&utm_campaign=predictive-model-based-trading-systems-part-ii https://easylanguagemastery.com/building-strategies/predictive-model-based-trading-systems-part-ii/#comments Mon, 19 Aug 2013 10:00:14 +0000 http://systemtradersuccess.com/?p=5422

The fundamental idea behind predictive modeling is indicators may contain information that can be used to predict a forward looking variable, called a target. The task of a predictive model is to find and exploit any such information.


Date                           Trend        Volatility          Day_return

19950214                 0.251          1.572                   0.144

19950215                 0.101          1.778                   0.055

19950216                -0.167          2.004                  -0.013

...

Suppose we provide several years of this data to a model and ask it to learn how to predict day_return, the one day forward return, from two indicators, one called trend and the other volatility. In the lingo of machine-learning this process is called model training. Then, we may at a later date calculate from recent prices that trend=0.225 and volatility=1.244 as of that day. The trained model may then make a prediction that the target variable day_return will be 0.152. (These are all made-up numbers.) Based on this prediction that the market is about to rise substantially, we may choose to take a long position.

Converting Predictions to Trade Decisions

Intuition tells us that we should put more faith in extreme predictions than in more common predictions near the center of the model’s prediction range. If a model predicts that the market will rise by 0.001 percent tomorrow, we would not be nearly as inclined to take a long position as if the model predicts a 5.8 percent rise. This intuition is correct, because our research has shown in general there is a large correspondence between the magnitude of a prediction and the likelihood of success of the associated trade. Predictions of large magnitude are more likely to signal profitable market moves than predictions of small magnitude. The standard method for making trade decisions based on predicted market moves is to compare the prediction to a fixed threshold. If the prediction is greater than or equal to an upper threshold (usually positive), take a long position. If the prediction is less than or equal to a lower threshold (usually negative), take a short position. The holding period for a position is implicit in the definition of the target. This will be discussed in detail in our book Statistically Sound Machine Learning for Algorithmic Trading of Financial Instruments (SSML) . It should be obvious that the threshold determines a tradeoff in the number of trades versus the accuracy rate of the trades. If we set a threshold near zero, the magnitude of the predictions will frequently exceed the threshold, and a position will be taken often. Such trades carry a relatively high rate of failure. Conversely, if we set a threshold that is far from zero, predicted market moves will only rarely lie beyond the threshold, so trades will be rare but have a relatively high success rate. We already noted that there is a large correspondence between the magnitude of a prediction and the likelihood of a trade’s success. Thus, by choosing an appropriate threshold, we can control whether we have a system that trades often but with only mediocre accuracy, or a system that trades rarely but with excellent accuracy.

TSSB automatically chooses optimal long and short thresholds by choosing them so as to maximize the profit factor for long systems and short systems separately. Profit factor, a common metric of trading system performance is the ratio of total gains on successful trades to total loses on failed trades. In order to prevent degenerate situations in which there is only one trade or very few trades, the user specifies a minimum number of trades that must be taken, either as an absolute number or as a minimum fraction of bars. In addition, TSSB has an option for using two thresholds on each side (long and short) so as to produce two sets of signals, one set for ‘normal reliability’ trades, and a more conservative set for ‘high reliability’ trades. Finally, in many applications, TSSB prints tables that show performance figures that would be obtained with varying thresholds.

Computation of thresholds and interpretation of trade results based on predictions relative to these thresholds are advanced topics that will be discussed in detail in SSML. For now, the reader needs to understand only the following concepts:

  • The user specifies indicator variables based on recent observed history and target variables that portray future price movement
  • TSSB is given raw historical market data (prices and perhaps other data, such as volume) and it generates an extensive database of indicator and target variables. One or more models are trained to predict the target given a set of indicators. In other words, the model learns to use the predictive information contained in the indicators in order to predict the future as exemplified by the target.
  • Every time a prediction is made, the numerical value of this prediction is compared to a long or upper threshold. If the prediction is greater than or equal to the long threshold, a long position is taken. Similarly, the prediction is compared to a short or lower threshold, which will nearly always be less than the long threshold. If the prediction is less than or equal to the short threshold, a short position is taken.
  • The holding period for a position is inherent in the target variable. This is discussed in detail in SSML.
  • TSSB will report results for long and short systems separately, as well as net results for the combined systems.

Testing the Trading System

TSSB provides the ability to perform many tests of a predictive model trading or filtering system. The available testing methodologies will be discussed in detail SSML. However, so that the reader may understand the elementary trading/filtering system development and evaluation presented in the next chapter, we now discuss two general testing methodologies: cross validation and walkforward testing. These are the primary standards in many prediction applications, and both are available in TSSB in a variety of forms.

The principle underlying the vast majority of testing methodologies, including those included in TSSB, is that the complete historical dataset available to the developer is split into separate subsets. One subset, called the training set or the development set, is used to train the predictive model. The other subset, called the test set or the validation set, is used to evaluate performance of the trained model. (Note that the distinction between the terms test set and validation set is not consistent among experts, so the increasingly common convention is to use them interchangeably. The same is true of training set and development set.)

The key here is that no data that takes part in the training of the model is permitted to take part in its performance evaluation. Under fairly general conditions, this mutually exclusive separation guarantees that the performance measured in the test set is an unbiased estimate of future performance. In other words, although the observed performance will almost certainly not exactly equal the performance that will be seen in the future, it does not have a systematic bias toward optimistic or pessimistic values. Having an unbiased estimate of future performance is one of the two main goals of a trading system development and testing operation. The other goal is being able to perform a statistical significance test to estimate the probability that the performance level achieved could have been due to good luck. This advanced concept is beyond the scope of this brief overview but its is discussed in depth in  SSML.

In the earliest days of model building and testing, when high speed computers were not readily available, splitting of the data into a training set and a test set was done exactly once. The developer would typically train the model using data through a date several years prior to the current date, and then test the model on subsequent data, ending with the most recent data available. This is an extremely inefficient use of the data. TSSB makes available both cross validation and walkforward testing. These techniques split the available data into training sets and test sets many times, and pool the performance statistics into a single unbiased estimate of the model-based trading system’s true capability. This extensive reuse of the data for both training and testing makes efficient use of precious and limited market history.

Walkforward Testing

Walkforward testing is straightforward, intuitive, and widely used. The principle is that we train the model on a relatively long block of data that ends a considerable time in the past. We test the trained model on a relatively short section of data that immediately follows the training block. Then we shift the training and testing blocks forward in time by an amount equal to the length of the test block and repeat the prior steps. Walkforward testing ends when we reach the end of the dataset. We compute the net performance figure by pooling all of the test block trades. Here is a simple example of walkforward testing:

1) Train the model using data from 1990 through 2007. Test the model on 2008 data.

2) Train the model using data from 1991 through 2008. Test the model on 2009 data.

3) Train the model using data from 1992 through 2009. Test the model on 2010 data.

Pool all trades from the tests of 2008, 2009, and 2010. These trades are used to compute an unbiased estimate of the performance of the model.

The primary advantage of walkforward testing is that it mimics real life. Most developers of automated trading systems periodically retrain or otherwise refine their model. Thus, the results of a walkforward test simulate the results that would have been obtained if the system had been actually traded. This is a compelling argument in favor of this testing methodology.

Another advantage of walkforward testing is that it correctly reflects the response of the model to nonstationarity in the market. All markets evolve and change their behavior over time, sometimes rotating through a number of different regimes. Loosely speaking, this change in market dynamics, and hence in relationships between indicator and target variables, is called nonstationarity. The best predictive models have a significant degree of robustness against such changes, and walkforward testing allows us to judge the robustness of a model.

TSSB’s ability to use a variety of testing block lengths makes it easy to evaluate the robustness of a model against nonstationarity. Suppose a model achieves excellent walkforward results when the test block is very short. In other words, the model is never asked to make predictions for data that is far past the date on which its training block ended. Now suppose the walkforward performance deteriorates if the test block is made longer. This indicates that the market is rapidly changing in ways that the model is not capable of handling. Such a model is risky and will require frequent retraining if it is to keep abreast of current market conditions. On the other hand, if walkforward performance holds up well as the length of the test block is increased, the model is robust against nonstationarity. This is a valuable attribute of a predictive-model based approach to trading system development. Look at Figure 1 which depicts the placement of the training and testing blocks (periods) along the time axis. Figure 1 above shows two situations. 

The top section of the figure depicts walkforward with very short test blocks. The bottom section depicts very long test blocks. It can be useful to perform several walkforward tests of varying test block lengths in order to evaluate the degree to which the prediction model is robust against nonstationarity.

Walkforward testing has only one disadvantage relative to alternative testing methods such as cross validation: it is relatively inefficient when it comes to use of the available data. Only cases past the end of the first training block are ever used for testing. If you are willing to believe that the indicators and targets are reasonably stationary, this is a tragic waste of data. Cross validation, discussed in the next section, addresses this weakness.

Cross Validation

Rather than segregating all test cases at the end of the historical data block, as is done with walkforward testing, we can evenly distribute them throughout the available history. This is called cross validation. For example, we may test as follows:

1) Train using data from 2006 through 2008. Test the model on 2005 data.

2) Train using data from 2005 through 2008, excluding 2006. Test the model on 2006 data.

3) Train using data from 2005 through 2008, excluding 2007. Test the model on 2007 data.

4) Train using data from 2005 through 2008, excluding 2008. Test the model on 2008 data.

This idea of withholding interior ‘test’ blocks of data while training with the surrounding data is illustrated in Figure 2 below. In cross validation, each step is commonly called a fold.

The obvious advantage of cross validation over walkforward testing is that every available case becomes a test case at some point. However, there are several disadvantages to note. The most serious potential problem is that cross validation is sensitive to nonstationarity. In a walkforward test, only relatively recent cases serve as test subjects. But in cross validation, cases all the way back to the beginning of the dataset contribute to test performance results. If the behavior of the market in early days was so different than in later days that the relationship between indicators and the target has seriously changed, incorporating test results from those early days may not be advisable.

Another disadvantage is more philosophical than practical, but it is worthy of note. Unlike a walkforward test, cross validation does not mimic the real-life behavior of a trading system. In cross validation, except for the last fold, we are using data from the future to train the model being tested. In real life this data would not be known at the time that test cases are processed. Some skeptics will raise their eyebrows at this, even though when done correctly it is legitimate, providing nearly unbiased performance estimates. Finally, overlap problems, discussed in the next section, are more troublesome in cross validation than in walkforward tests.

Overlap Considerations

The discussions of cross validation and walkforward testing just presented assume that each case is independent of other cases. In other words, the assumption is that the values of variables for a case are not related to the values of other cases in the dataset. Unfortunately, this is almost never the situation. Cases that are near one another in time will tend to have similar values of indicators and/or targets. This generally comes about in one or both of the following ways:

  • Many of the targets available in TSSB look further ahead than just the next bar. For example, suppose our target is the market trend over the next ten bars. This is the quantity we wish to predict in order to make trade decisions. If this value is high on a particular day, indicating that the market trends strongly upward over the subsequent ten days, then in all likelihood this value will also be high the following day, and it was probably high the prior day. Shifting ahead or back one day still leaves an overlap of nine days in that ten-day target window. Such case-to-case correlation in time series data is called serial correlation.
  • In most trading systems, the indicators look back over a considerable time block. For example, an indicator may be the market trend over the prior 50 days, or a measure of volatility over the prior 100 days. As a result, indicators change very slowly over time. The values of indicators for a particular day are almost identical to the values in nearby days, before and after.

These facts have several important implications. Because indicators change only slowly, the model’s predictions also change slowly. Hence market positions change slowly; if a prediction is above a threshold, it will tend to remain above the threshold for multiple bars. Conversely, if a prediction is below a threshold, it will tend to remain below that threshold for some time. If the target is looking ahead more than one bar, which results in serial correlation as discussed above, then the result of serial correlation in both positions and targets is serial correlation in returns for the trading system. This immediately invalidates most common statistical significance tests such as the t-test, ordinary bootstrap, and Monte-Carlo permutation test. TSSB does include several statistical significance tests that can lessen the impact of serial correlation. In particular, the stationary bootstrap and tapered block bootstrap will be discussed elsewhere in SSML. Unfortunately, both of these tests rely on assumptions that are often shaky. We’ll return to this issue in more detail later when statistical tests are discussed. For the moment, understand that targets that look ahead more than one bar usually preclude tests of significance or force one to rely on tests having questionable validity.

Lack of independence in indicators and targets has another implication, this one potentially more serious than just invalidating significance tests. The legitimacy of the test results themselves can be undermined by bias. Luckily, this problem is easily solved with a TSSB option called OVERLAP. Its details are discussed in SSML. For now we will simply explore the nature of the problem.

The problem occurs near the boundaries between training data and test data. The simplest situation is for walkforward testing, because there is only one (moving) boundary. Suppose the target involves market movement ten days into the future. Consider the last case in the training block. Its target involves the first ten days after the test block begins. This case, like all training set cases, plays a role in the development of the predictive model. Now consider the case that immediately follows it, the first case in the test block. As has already been noted, its indicator values will be very similar to the indicator values of the prior case. Thus, the model’s prediction will also be similar to that of the prior case. Because the target looks ahead ten days and we have moved ahead only one day, leaving a nine-day overlap, the target for this test case will be similar to the target for the prior case. But the prior case, which is practically identical to this test case, took part in the training of the model! So we have a strong prejudice for the model to do a good job of predicting this case, whose indicators and target are similar to the training case. The result is optimistic bias, the worst sort. Our test results will exceed the results that would have been obtained from an honest test.

This boundary effect manifests itself in an additional fashion in cross validation. Of course, we still have the effect just described when we are near the end of the early section of the training set and the start of the test set. This is the left edge of the red regions in Figure 2. But we also have a boundary effect when we are near the end of the test set and the start of the later part of the training set. This is the right edge of each red region. As before, cases near each other but on opposite sides of the training set / test set boundary have similar values for indicators and the target, which results in optimistic bias in the performance estimate. The bottom line is that bias due to overlap at the boundary between training data and test data is a serious problem for both cross validation and walkforward testing. Fortunately, the user can invoke the OVERLAP option to alleviate this problem.

Get the Book

Screen Shot 2014-10-19 at 6.36.03 PM

-- By David Aronson

Part 1 of this series can be found here, Predictive-Model Based Trading Systems, Part 1.

David Aronson is a pioneer in machine learning and nonlinear trading system development and signal boosting/filtering. Aronson is Co-designer of TSSB (Trading System Synthesis and Boosting) a software platform for the automated development of statistically sound predictive model based trading systems. He has worked in this field since 1979 and has been a Chartered Market Technician certified by The Market Technicians Association since 1992. He was an adjunct professor of finance, and regularly taught to MBA and financial engineering students a graduate-level course in technical analysis, data mining and predictive analytics. His recently released book, Statistically Sound Machine Learning for Algorithmic Trading of Financial Instruments, is a in-depth look at developing predictive-model-based trading systems using TSSB.

]]>
https://easylanguagemastery.com/building-strategies/predictive-model-based-trading-systems-part-ii/feed/ 8