EasyLanguage Mastery Contributor – Helping you Master EasyLanguage https://easylanguagemastery.com Helping you Master EasyLanguage Wed, 12 Jun 2024 15:36:49 +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 EasyLanguage Mastery Contributor – Helping you Master EasyLanguage https://easylanguagemastery.com 32 32 What Is Walk Forward Optimization? https://easylanguagemastery.com/building-strategies/what-is-walk-forward-optimization/?utm_source=rss&utm_medium=rss&utm_campaign=what-is-walk-forward-optimization https://easylanguagemastery.com/building-strategies/what-is-walk-forward-optimization/#respond Mon, 03 Jun 2024 10:00:26 +0000 http://systemtradersuccess.com/?p=5851

One of the biggest issues with system development is that many trading strategies do not hold up into the future. This could be due to several reasons:

  • The system is not based on a valid premise
  • Market conditions have changed in a dramatic way that invalids the theoretical premises on which the system was developed
  • The system has not been developed and tested with a sound methodology. For instance, (a) lack of robustness in a system due to improper parameters, and (b) inconsistent rules and improper testing of the system using out-of-sample and in-sample data

There are several approaches and methodologies to asses robustness and increase likelihood of positive real life trading performance including:

  • Peak avoidance
  • Limited number of optimizable parameters
  • 3D surface charting
  • Monte Carlo analysis
  • Data scrambling
  • Walk forward & walk backward analysis

One of the most robust ways of testing the reliability of a trading system and making sure the program will have the highest likelihood of performing well in real live trading is to use walk forward optimization (WFO), a method first described in the book “Design, Testing, and Optimization of Trading Systems” by Roberto Pardo.

What is walk forward analysis?

Walk forward analysis is the process of optimizing a trading system using a limited set of parameters, and then testing the best optimized parameter set on out-of-sample data. This process is similar to how a trader would use an automated trading system in real live trading. The in-sample time window is shifted forward by the period covered by the out-of-sample test, and the process is repeated. At the end of the test, all of the recorded results are used to assess the trading strategy.

In other words, walk forward analysis does optimization on a training set; tests on a period after the set and then rolls it all forward and repeats the process. We have multiple out-of-sample periods and look at these results combined. Walk forward testing is a specific application of a technique known as Cross-validation. It means taking a segment of data to optimize a system, and another segment of data to validate. This gives a larger out-of-sample period and allows the system developer to see how stable the system is over time.

The picture below illustrates the walk forward analysis procedure. An optimization is performed over a longer period (the in-sample data), and then the optimized parameter set is tested over a subsequent shorter period (the out-of-sample data). The optimization and testing periods are shifted forward, and the process is repeated until a suitable sample size is achieved.

Walk Forward Optimization

Runs in a Walk Forward Optimization

In order to demonstrate the concept we will perform in this article a walk forward optimization on a volatility breakout trading system (VBO). For the test we will use the German DAX futures, NinjaTrader, CQG historical 1-minute data, and we will assume 3 points of slippage for each R/T trade to cover trading frictions.

The process consists of three main steps:

  1. Define in-sample and out-of-sample periods
  2. Define a robust parameters area
  3. Execute the walk forward

Definition of the in-sample and out-of-sample periods

We will choose as in-sample 1/1/2001 to 12/31/2009 for system design and in-sample optimization and 1/1/2010 to 12/31/2012 as out-of-sample period to evaluate the in-sample optimization robustness and execute the walk forward. We will then use a 3:1 ratio for the WFO (walk forward optimization):

  • Optimize 2007 to 2009 and verify performance out-of-sample in 2010
  • Optimize 2008 to 2010 and verify performance out-of-sample in 2011
  • Optimize 2009 to 2011 and verify performance out-of-sample in 2012

Define the robust parameters area in the in-sample period

In this section we will define the "robust area" of the system parameters. We will optimize only 3 system parameters:

  • Lookback period of the fast average
  • Lookback period of the slow average
  • Volatility filter

Other system parameters that we will not optimize are:

  • Start time: 09:00 (GMT+1)
  • End time: 22:00 (GMT+1)
  • Last trade: 18:00 (GMT+1)
  • Stop risk: 2%
  • Maximum trades per day: 3
  • Exit on close: True

Optimization of the charting resolution

As we can see the average SQN (system quality number) tends to decrease as we increase the time period of the chart in minutes. We will choose 14 minutes for all simulations going forward.

Definition of the robust parameter area for the averages

Via a 3D surface chart we can identify the robust parameter area as follows:

  • Slow average: 12 to 30 minutes
  • Fast average: 330 to 500 minutes

We define "robust" a parameter surface area that does not have major peaks or valleys and has generally a good performance.

Definition of the robust parameter for the volatility filter

As we can see the robust area for the filter is between 0.55 and 0.70 when the SQN is slowly increasing.

Now that we have identified the robust parameters area it is worth performing a full in-sample optimization to see how the system would have performed between 2001 and 2009.

The system generated a net profit of $120,000 between 2001 and 2009 with a profit factor of 1.56, performing 756 trades with an average of 41% trades profitable. The systems exhibits certain desirable characteristics such as a high win/loss ratio of 2.28.

Walk forward optimization

As anticipated, we will now proceed with a walk-forward optimization.

Step 1: We'll optimize between 2007-2009 and find the best parameters.

The best parameters for the 2007-09 period are:

  • Fast average: 12
  • Slow average: 410
  • Filter: 0.55

We apply these parameters to the out-of-sample period in 2010 with the following results:

Net profit: $12,300
DD: $9,000
% profitable: 43%
Profit factor: 1.38

Step 2: We'll optimize between 2008-2010 and find the best parameters.

The best parameters for the 2008-10 period are:

  • Fast average: 20
  • Slow average: 500
  • Filter: 0.70

We apply these parameters to the out-of-sample period in 2011 with the following results:

Net profit: $27,900
DD: $7,450
% profitable: 43%
Profit factor: 1.61

Step 3: We'll optimize between 2009-2011 and find the best parameters.

The best parameters for the 2009-11 period are:

  • Fast average: 20
  • Slow average: 420
  • Filter: 0.55

We apply these parameters to the out-of-sample period in 2012 with the following results:

 Net profit: $17,540
DD: $7,300
% profitable: 41%
Profit factor: 1.58

Conclusions

In this article we have shown how to perform a walk forward optimization on an intraday mechanical system. The walk forward results are in line with the in-sample results and this builds confidence in the robustness of the strategy.

-- By Amon Licini has been a private trader for 15 years and a senior manager with various corporates in Italy. Amon's main trading interests lie in the area of volatility and open range breakouts for intraday systems. He lives in Milan with his wife and 2 children and loves traveling when he's not developing new systems. Amon has a degree in mechanical engineering from the Polytechnic University of Milan.

]]>
https://easylanguagemastery.com/building-strategies/what-is-walk-forward-optimization/feed/ 0
Using a Self-Similarity Metric with Intraday Data to Define Market Regimes https://easylanguagemastery.com/indicators/using-self-similarity-metric-intraday-data-define-market-regimes/?utm_source=rss&utm_medium=rss&utm_campaign=using-self-similarity-metric-intraday-data-define-market-regimes https://easylanguagemastery.com/indicators/using-self-similarity-metric-intraday-data-define-market-regimes/#comments Mon, 13 Sep 2021 10:00:00 +0000 http://systemtradersuccess.com/?p=7210

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:

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
]]>
https://easylanguagemastery.com/indicators/using-self-similarity-metric-intraday-data-define-market-regimes/feed/ 22
9 Mistakes Quants Make that Cause Backtests to Lie https://easylanguagemastery.com/building-strategies/9-mistakes-quants-make-cause-backtests-lie/?utm_source=rss&utm_medium=rss&utm_campaign=9-mistakes-quants-make-cause-backtests-lie https://easylanguagemastery.com/building-strategies/9-mistakes-quants-make-cause-backtests-lie/#comments Mon, 02 Nov 2020 11:00:32 +0000 http://systemtradersuccess.com/?p=7534

"I’ve never seen a bad backtest” -- Dimitris Melas, head of research at MSCI.

A backtest is a simulation of a trading strategy used to evaluate how effective the strategy might have been if it were traded historically. Backtesting is used by hedge funds and other researchers to test strategies before real capital is applied. Backtests testing are valuable because they enable quants to quickly test and reject trading strategy ideas.

All too often strategies look great in simulation but fail to live up to their promise in live trading. There are a number of reasons for these failures, some of which are beyond the control of a quant developer. But other failures are caused by common, insidious mistakes.

An over optimistic backtest can cause a lot of pain. I’d like to help you avoid that pain by sharing 9 of the most common pitfalls in trading strategy development and testing that can result in overly optimistic backtests:

1. In-sample backtesting

Many strategies require refinement, or model training of some sort. As one example, a regression-based model that seeks to predict future prices might use recent data to build the model. It is perfectly fine to build a model in that manner, but it is not OK to test the model over that same time period. Such models are doomed to succeed.

Don’t trust them.

Solution: Best practices are to build procedures to prevent testing over the same data you train over. As a simple example you might use data from 2007 to train your model, but test over 2008-forward.

By the way, even though it could be called “out-of-sample” testing it is not a good practice to train over later data, say 2014, then test over earlier data, say 2008-2013. This may permit various forms of lookahead bias.

2. Using survivor-biased data

Suppose I told you I have created a fantastic new blood pressure medicine, and that I had tested it using the following protocol:

a. Randomly select 500 subjects
b. Administer my drug to them every day for 5 years
c. Measure their blood pressure each day

At the beginning of the study the average blood pressure of the participants was 160/110, at the end of the study the average BP was 120/80 (significantly lower and better).

Those look like great results, no? What if I told you that 58 of the subjects died during the study? Maybe it was the ones with the high blood pressure that died! This is clearly not an accurate study because it focused on the statistics of survivors at the end of the study.

This same sort of bias is present in backtests that use later lists of stocks (perhaps members of the S&P 500) as the basis for historical evaluations over earlier periods. A common example is to use the current S&P 500 as the universe of stocks for testing a strategy.

Why is this bad? See the two figures below for illustrative examples.

Figure: The green lines show historical performance of stocks that were members of the S&P 500 in 2012. Note that all of these stocks came out of the 2008/2009 downturn very nicely.

Figure: What really happened: If, instead we use the members of the S&P 500 starting in 2008, we find that more than 10% of the listed companies failed.

In our work at Lucena Research, we see an annual 3% to 5% performance “improvement” with strategies using survivor-biased data.

Solution: Find datasets that include historical members of indices, then use those lists to sample from for your strategies.

3. Observing the close & other forms of lookahead bias

In this failure mode, the quant assumes he can observe market closing prices in order to compute an indicator, and then also trade at the close. As an example, one might use closing price/volume to calculate a technical factor used in the strategy, then trade based on that information.

This is a specific example of lookahead bias in which the strategy is allowed to peek a little bit into the future. In my work I have seen time and again that even a slight lookahead bias can provide fantastic (and false) returns.

Other examples of lookahead bias have to do with incorrect registration of data such as earnings reports or news. Assuming for instance that one can trade on the same day earnings are announced even though earnings are usually announced after the close.

Solution: Don’t trade until the open of the next day after information becomes available.

4. Ignoring market impact

The very act of trading affects price. Historical pricing data does not include your trades and is therefore not an accurate representation of the price you would get if you were trading.

Consider the chart below that describes the performance of a real strategy I helped develop. Consider the region A, the first part of the upwardly sloping orange line. This region was the performance of our backtest. The strategy had a Sharpe Ratio over 7.0! Based on the information we had up until that time (the end of A), it looked great so we started trading it.

When we began live trading we saw the real performance illustrated with the green “live” line in region B– essentially flat. The strategy was not working, so we halted trading it after a few weeks. After we stopped trading it, the strategy started performing well again in paper trading (Region C, Arg!).

How can this be? We thought perhaps that the error was in our predictive model, so we backtested again over the “live” area and the backtest showed that same flat area. The only difference between the nice 7.0 Sharpe Ratio sections and the flat section was that we were engaged in the market in the flat region.

What was going on? The answer, very simply, is that by participating in the market we were changing the prices to our disadvantage. We were not modeling market impact in our market simulation. Once we added that feature more accurately, our backtest appropriately showed a flat, no-return result for region A. If we had had that in the first place we probably would never have traded the strategy.

Solution: Be sure to anticipate that price will move against you at every trade. For trades that are a small part of overall volume, a rule of thumb is about 5 bps for S&P 500 stocks and up to 50 bps for more thinly traded stocks. It depends of course on how much of the market your strategy is seeking to trade.

5. Buy $10M of a $1M company

Naïve backtesters will allow a strategy to buy or sell as much of an asset as it likes. This may provide a misleadingly optimistic backtest because large allocations to small companies are allowed.

There often is real alpha in thinly traded stocks, and data mining approaches are likely to find it. Consider for a moment why it seems there is alpha there. The reason is that the big hedge funds aren’t playing there because they can’t execute their strategy with illiquid assets. There are perhaps scraps of alpha to be collected by the little guy, but check to be sure you’re not assuming you can buy $10M of a $1M company.

Solution: Have your backtester limit the strategy’s trading to a percentage of the daily dollar volume of the equity. Another alternative is to filter potential assets to a minimum daily dollar volume.

6. Overfit the model

An overfit model is one that models in-sample data very well. It predicts the data so well that it is likely modeling noise rather than the underlying principle or relationship in the data that you are hoping it will discover.

Here’s a more formal definition of overfitting: As the degrees of freedom of the model increase, overfitting occurs when in-sample prediction error decreases and out-of-sample prediction error increases.

What do we mean by “degrees of freedom?” Degrees of freedom can take many forms, depending on the type of model being created: Number of factors used, number of parameters in a parameterized model and so on.

Solution: Don’t repeatedly “tweak” and “refine” your model using in-sample data. And always compare in-sample error versus out-of-sample error.

7. Trust complex models

Complex models are often overfit models. Simple approaches that arise from a basic idea that makes intuitive sense lead to the best models. A strategy built from a handful of factors combined with simple rules is more likely to be robust and less sensitive to overfitting than a complex model with lots of factors.

Solution: Limit the number of factors considered by a model, use simple logic in combining them.

8. Trusting stateful strategy luck

A stateful strategy is one whose holdings over time depend on which day in history it was started. As an example, if the strategy rapidly accrues assets, it may be quickly fully invested and therefore miss later buying opportunities. If the strategy had started one day later, it’s holdings might be completely different.

Sometimes such strategies’ success vary widely if they are started on a different day. I’ve seen, for instance, a difference in 50% return for the same strategy started on two days in the same week.

Solution: If your strategy is stateful, be sure to test it starting on many difference days. Evaluate the variance of the results across those days. If it is large you should be concerned.

9. Data mining fallacy

Even if you avoid all of the pitfalls listed above, if you generate and test enough strategies you’ll eventually find one that works very well in a backtest. However, the quality of the strategy cannot be distinguished from a lucky random stock picker.

How can this pitfall be avoided? It can’t be avoided. However, you can and should forward test before committing significant capital.

Solution: Forward test (paper trade) a strategy before committing capital.

Summary

It is best to view backtesting as a method for rejecting strategies, than as a method for validating strategies. One thing is for sure: If it doesn’t work in a backtest, it won’t work in real life. The converse is not true: Just because it works in a backtest does not mean you can expect it to work in live trading.

However, if you avoid the pitfalls listed above, your backtests stand a better chance of more accurately representing real life performance.

-- Tucker Balch from Augmented Trader

]]>
https://easylanguagemastery.com/building-strategies/9-mistakes-quants-make-cause-backtests-lie/feed/ 7
A Flexible Trailing Stop Function https://easylanguagemastery.com/development-tools/a-flexible-trailing-stop-function/?utm_source=rss&utm_medium=rss&utm_campaign=a-flexible-trailing-stop-function https://easylanguagemastery.com/development-tools/a-flexible-trailing-stop-function/#comments Mon, 17 Feb 2020 11:00:24 +0000 http://systemtradersuccess.com/?p=2882

The Anatomy of a Stop

A stop can be defined by specifying four basic parameters, illustrated in Figure 1 below:

Price Reference: The price from which the stop is offset (white line) to create a stop value.

Stop Offset: The distance from the Price Reference to the stop value.

Price Trigger: The value of price that will trigger the stop. Usually this is the low or the high of a price bar. However, more sophisticated stops can be created by setting the trigger to a custom function of price, such as Average(Low, 3) to make the stop less vulnerable to isolated tall tails.

Reset Padding: The distance the stop should be reset away from the Price Trigger when the stop has been hit. Resetting the stop level serves two purposes: (1) it is much easier to see when a stop is hit, especially when the price trigger comes very close to but not quite touches the stop level, and (2) if a trade is re-entered in the same direction after stopping out, this reset padding can serve as the initial stop loss.

With these parameters defined, the following stop values can be calculated:

Stop Value: The value of the stop (yellow line). The stop is hit when the Price Trigger touches or crosses the Stop Value.

Ratchet Stop Value: The value of the ratchet stop (red line) is the Stop Value when it is constrained to move only in the direction toward the price action. The ratchet stop is hit when the Price Trigger touches or crosses the Ratchet Stop Value.

Fig. 1. Chandelier 5% Ratchet Trailing Stop (red line).

Fig. 1. Chandelier 5% Ratchet Trailing Stop (red line).

In this case, the Price Reference is the high of the bar, shown in white. The Stop Value is the yellow line, a distance of 5% below the Price Reference. The red line is the ratchet stop, which is the Stop Value constrained to always move in a direction closer to the price and never away from the price (unless the stop is hit and reset). The Price Trigger is the low of the bar. The cyan dots indicate the points at which the Price Trigger has crossed below the Ratchet Stop Value, triggering the stop.

Generating Many Stops from a Single Function (or Method)

By manipulating the four basic parameters that define a stop, a multitude of different stops can be generated:

Price Reference can be defined to be the highlow, or average price of a bar. It could also be defined as some custom function of price, such as a Linear Regression function of price.

Stop Offset can be defined in terms of pointsprice percentageATR units, or some custom function of price or volatility.

Trigger Price is usually set to the last trading price or the closing price for the bar. However, an alternative definition based on a custom formula of price, such as Average (Avgprice, 2), can be used to make the stop less vulnerable to tall tails and isolated bars extending beyond historical support or resistance.

Stop Directional Constraints can allow the stop to vary up and down, as in a yo-yo stop, or can force the stop to move only in a direction toward the current price, as in a ratchet stop.

Each unique type of stop could be coded into a separate function. However, since much of the code in each of these functions would be duplicated it makes sense to create a single unified stop generating function that could specify any type of stop by manipulating its input parameters. This would serve to reduce coding errors and encourage consistency when using stops in indicators and strategies. There is, however, an even greater motivation for using such a function. When used to generate stops within strategies, the optimizer could vary not only the value of the stop, but the type of stop as well, to determine which type of stop extracts the greatest profit from a trading system. It is with these goals in mind that the superfunction (or method), StopsFlexible was created. This single function (or method) can be used to create almost any type of stop desired.

Advantages of Using Function: StopsFlexible

  1. Coding duplication is markedly reduced, lessening the possibility of errors and making code maintenance more efficient.
  2. When used in a chart, the type of stop can be varied by simply changing an input parameter. This is more convenient than manually locating and inserting a new indicator from a large collection of stop indicators.
  3. Indicators using function StopsFlexible can display the differences in behavior of several different types of stops simultaneously, giving the user a graphical representation of each on the chart and visually revealing their unique behaviors. Such a graphical comparison assists in the selection of the most appropriate stop without the need for formal backtesting.
  4. When used in a strategy, optimization can exercise many types of stops using StopsFlexible, not just a single type of stop. In this manner, the best type of stop can be determined for the trading system being tested rather than only varying the “distance” of a single type of stop from the price reference.
  5. Blended Stops can easily be created. For example, one blended stop could be the sum of 1% of price plus 1.5 ATR units. Optimization can test blended stops efficiently to determine if the unique characteristics of blended stops can extract more profit from a trading system than traditional stops.

Advantages of Converting the Function: StopsFlexible to a Method

The function StopsFlexible is a series function, not a simple function. Therefore, when called by an indicator or strategy formatted, “Update each tick”, the function MUST execute with every tick, even if it is desirable to re-calculate only once per bar. Bracketing the call to the function with If BarStatus(1) = 2 condition, will NOT prevent a series function from executing with each tick, since this is the behavior of all series function within EasyLanguage. Since the calculation in StopsFlexible needs to occur only once per bar, the inefficiency forced upon the programmer by using a series function can be eliminated by recoding the function as a Method. Method calls, in contrast to series function calls, CAN be restricted to occur only once per bar when the indicator or strategy must be formatted to “Update each tick”. This technique is used in the current version of indicator StopsFlexible, bracketing the method StopsFlexible call by an If BarStatus(1) = 2 condition.

More Sophisticated Stops

Reference Point for a Stop. Although the reference point for a trailing stop is usually defined as the high of the bar for long trades, there is nothing that prevents an alternative definition. For example, the reference point could be the Low rather than the High of the bar. This would make the stop less sensitive to unusually tall bars or tall tails which might pull the stop up abruptly and cause a trade to stop out of a continuing trend prematurely. An alternative approach to make the stop movement less sensitive to bars with “tall tails” would be to define a chandelier stop to be based on the reference point of Average(high, length) or MinList(high, high[1]) rather than simply the high of the bar. More sophisticated stops may be created by referencing them to custom functions of price, such as linear regression or Kaufman Adaptive Moving Average of the price. 

Stop Offset Variations. In addition to stop offsets being based on points, price percentage, and ATR units, other offset definitions are possible. For example, blended stops formed by adding a price percentage offset and an ATR unit offset can be created, inheriting some of the characteristics of each. Such blended stops can be optimized to extract additional profit from trading systems. Stops can also be made to react dynamically to the acceleration of price movement by tightening the stop to capture additional profit in the event of rapid price thrust before a significant price retracement can occur. Stops can also use custom volatility functions, such as Standard Error, in place of the standard ATR unit, as illustrated below:

Figure 2. 6 StdErr Trailing Stop vs 1.5 ATR Trailing Stop.

Figure 2. 6 StdErr Trailing Stop vs 1.5 ATR Trailing Stop.

Why choose Standard Error? The goal here is to tighten the stop whenever the price moves in a very well behaved trend for at least n-bars. Well behaved, in this case, means a consistent trend with low volatility. The StdError(Price, N) function measures the degree to which price deviates from a linear regression line through the most recent “n” price bars. Notice that the minimums of the StdError function above (yellow arrows) correspond to intervals when the price moved in a consistent trend with low volatility for a period of at least 6 bars. A high standard error indicates that the price action is not moving consistently along a straight linear regression line, and maximums in the standard error typically occur at points where the trend abruptly changes direction. You can also see at each relative minimum in the StdError function value, the 6 StdError Trailing Stop tightened while the 1.5 ATR Trailing Stop remained about the same distance from the price. The StdError Trailing Stop can squeeze a few more dollars out of a trend trade, as shown in the three instances illustrated above, as it will tighten further after a consistent price move has occurred.

Trigger Reference Modification. Instead of using the last trade price or the low of the bar as a trigger for a stop, a custom trigger reference could be created as an input parameter to StopsFlexible. The screen shot to the right shows a Trigger Reference (white line) defined as Average(AvgPrice, 2). This moving average must hit the stop level to trigger the stop. Note that the bar crossing the ratchet trailing stop (red line) did NOT trigger the stop. This is an example of a custom trigger reference that makes the stop less sensitive to isolated bars extending just below or above a historical level of support or resistance. Such a trigger definition might be useful when using a stop order for a breakout entry, either long or short. It prevents an isolated tall tail from triggering a stop prematurely and protects to some extent against stop running and head fakes by larger traders.

StopsFlexible Indicator Input Parameters

HighRef is the Price Reference for the high stop (positioned above the price). LowRef is the Price Reference for the low stop (positioned below the price). Length is used to delay changes in the price reference by “Length” bars by adjusting the HighRef and LowRef values to MaxList(high, Length) and MinList(low, Length), respectively. UseKAMA is used to apply a KAMA (Kaufman Adaptive Moving Average) filter to HighRef and LowRef values. Default value is false.

EffRatioLength, FastAvgLength, and SlowAvgLength are all parameters that determine the degree of KAMA filtering. StopOffset is the offset to the bar used to calculate the stop for the current bar. Usually should be set = 1 (since strategy orders use the format: Buy/Sell NEXT bar at Value Limit). TradeDir indicates if stops will be displayed below the price (+1), above the price (-1), or both (0). Similarly, AlertDir indicates if the corresponding low (+1), high (-1), or both (0) stops will generate an alert.

ATRLengthJATRLength, and StdErrLength are the lengths used to calculate the Average True Range, Jurik Average True Range, and Standard Error.

StopPtsStopPctStopATRStopJurikATR, and StopStdErr are the multipliers used for the stop offset expressed in points, price percentage, ATR units, Jurik ATR units, and standard error units, respectively. All specified values are calculated and added together to form the final stop value. For example, to create a pure 2 ATR stop, StopATR should be 2 and all other values 0. To create a stop that is a blend of 1 ATR unit and 1%, set StopATR = 1, StopPct = 1 and all other values to 0. HighRefTrig and LowRefTrig are the price references triggering the stop. Normally, HighRefTrig = high and LowRefTrigger = low indicating the high or low of the bar will trigger stops above and below the price, respectively. SmoothTrigRef is the length of the simple moving average applied to the HighRefTrig and LowRefTrig values. ResetPtsResetPctResetATRResetJATR, and ResetStdErr are the amounts the stop will be offset each time it is hit. Moving the stop value when hit makes it easier to determine if a stop that comes very close to the low or high of a bar was hit or not. 

ShowRefShowStopsShowRatchetShowRefTrigger, and ShowStopTriggered are set to true or false to indicate whether these values are to be displayed on the chart. PlotWidth indicates the width of all lines plotted. UsePlotWidth indicates whether the PlotWidth value will be used, or if the user will be free to specify line formatting manually. ShowHitsOffsetATR is the amount of vertical offset (in ATR units) the ShowMe dot, indicating a stop has been hit, will be displayed. This offset moves the dot away from the price action to make it more easily visible. If ShowHitsOffsetATR = 0, then the dot appears at the HighRefTrig or LowRefTrig value. NOTE: The Jurik moving average function used to calculate the Jurik Average True Range is disabled in StopsFlexible, as this is a third party add-in that must be purchased from Jurik Research. Those users that have purchased this add-in may uncomment out the appropriate section of code.

Downloads

The download package is a zip file that contains the following three EasyLanguage files:

  1. StopFlexable Indicator
  2. StopFlexable Function
  3. StopFlexable Method

StopFlexable Zip File 

— by Mark Krisburg from HighTick Trading. Do you have a custom indicator or function you would like to use, but don’t have the programming experience to create it? We provide custom programming services, as well as a variety of useful add-on functions and screening tools to find profitable trades in any market condition, while controlling risk.

]]>
https://easylanguagemastery.com/development-tools/a-flexible-trailing-stop-function/feed/ 7
In-Sample and Out-Of-Sample Testing https://easylanguagemastery.com/building-strategies/in-sample-and-out-of-sample-testing/?utm_source=rss&utm_medium=rss&utm_campaign=in-sample-and-out-of-sample-testing https://easylanguagemastery.com/building-strategies/in-sample-and-out-of-sample-testing/#comments Mon, 03 Feb 2020 11:00:11 +0000 http://systemtradersuccess.com/?p=12129

I am frequently asked if I do out-of-sample testing. The short answer is not always, and when I do it is not how most people do the test. There are lots of considerations and pitfalls to avoid when doing out-of-sample testing. Out-of-sample testing is not the panacea it is made out to be. There are lots of grey areas which I will discuss below.

Definition

To do in-sample (IS) and out-of-sample (OOS) testing, one first divides their historical data into two parts. The most common methods for dividing the data are 50% IS/50% OOS and 67% IS/33% OOS. I will be using 15 years of data. Here are some ways that one can divide the data:

There are different reasons one may want the IS data to be the oldest data or the newest data which I will discuss below. The IS data is used to create and optimize your strategy. After refining your strategy, you choose one variation to test on the OOS sample data. From the OOS result, one must decide if the result is good enough to say that the strategy continued to work and was not overfit to the IS data. If it passes your criteria, one can then start trading the strategy. If it does not, well it is game over on that strategy.

When I don’t use OOS Testing

The most common reason not to use OOS testing is because of lack of data. I trade a VXX/XIV strategy I can only test back to 2011. There are just not enough trades to justify breaking the data into two. How do I know that strategy is not overfit? I don’t. I often will use parameter sensitivity testing as described in this post. Here my real trading becomes the OOS test, which is the best OOS test one can have.

Out-of-sample Issues

Past is likely very different from today. Even though I have data back to the 1990’s, I don’t like going that far back for my data because those markets differ greatly from what we have today. This is the time before decimalization, high-frequency trading, government invention, lots of ETFs, and many more change. I will go with 15 years of data.

What is the size and period of OOS?

The first big decision to make is what period to use as the IS period and what period to use for the OOS along with how big each will be. I use the most recent data as my IS period and the older data for the OOS period. The reason for this is I want to optimize my strategy on the most recent market because I believe that is more likely to be closer to the future market than the farther out period. I want to capture a full market cycle of bull and bear when doing this. As to size I typically go with the 67/33 method. Next, I will show how the decision of which period to OOS can lead to very different results.

Only taking one bite of the apple

One of the core tenets of OOS testing is taking only one bite of the apple. Meaning you only test once on the OOS data to see if your strategy holds up. This is hard to do because it is against human nature. You spend weeks or months developing a strategy, and then a quick test on OOS testing fails. No one wants to throw away all that work. But here is the more subtle thing. What is a second bite? Meaning I tested a mean reversion strategy and it failed in OOS. Does that mean I can test no more mean reversion strategies? Of course not, that would be crazy. How much does one need to change a current strategy to make it different enough to use that OOS data? Is changing parameter values to something one did not test enough? Not in my book.

What about adding a new rule, say a moving average cross? Still probably not enough? What if I remove a rule and add profit target? Maybe. There is no clear change to strategy when it is OK to use the data again. It is up to each individual to decide and that means we are likely to fool ourselves and say that small change is enough. Also, we have knowledge about our test period. I know from experience that mean reversion trading did well from 2003 to 2009. If I use 2002 to 2006 as my OOS sample data for a mean reversion test, is that cheating?

Defining success

The above issues are not even that big to me. These next two are huge ones for me. When we run our strategy on the OOS data, how do we know that it passed the OOS test? First, the strategy will probably not perform as well because it was developed on the current market conditions and now it is being tested on different ones. Just because it made money doesn’t make it passed the OOS test. What if the CAGR only dropped a little? That sounds like a pass.

But what if that is the worst CAGR if you ran all your original 1,000 variations on the OOS data? Now it doesn’t sound good. How about a goal of beating a simple strategy? Buy the SPY when it crosses above its 200-day moving average and sell when it closes below it. Can we beat that CAGR by more than 100%? I use this idea and another which I will explain in the next post.

Picking only one variation

Now this is where I have my biggest issue with how OOS testing is normally done. For example, we have a strategy with 1,000 variations. We go through some methods to pick one to test on the OOS data. See this post on how I would pick The One. Now we run The One on the OOS data and make our decision. Say our strategy did “poorly” that means we should stop and consider this a failure. Here is where I have my problem.

What if I got unlucky and picked a variation that did poorly during this timeframe but many of my other choices did well. My strategy concept held up but just not the one I picked. That is wrong because what we want to know is if our strategy concept hold up in OOS. Imagine the reverse scenario. Your strategy concept sucks and it behaves as well as choosing random entry and exit times. In this case, you could get “lucky” and pick a variation that does well in OOS data. Now you are off trading a strategy that is as good as random.

Final Thoughts

In the next post, I will show results of doing IS and OOS testing on a mean reversion strategy and how picking only one variation can be dangerous. Then I will show how using a set of variations is a much better way to help determine if your strategy did well in OOS testing. The post will also show how one can come to different conclusions depending on how the IS and OOS ranges are chosen.

— by Cesar Alvarez from blog Alvarez Quant Trading.

]]>
https://easylanguagemastery.com/building-strategies/in-sample-and-out-of-sample-testing/feed/ 1
Why You Should Really Optimize and Even If You Don’t https://easylanguagemastery.com/building-strategies/why-you-should-optimize/?utm_source=rss&utm_medium=rss&utm_campaign=why-you-should-optimize https://easylanguagemastery.com/building-strategies/why-you-should-optimize/#comments Mon, 06 Jan 2020 11:00:00 +0000 http://systemtradersuccess.com/?p=10714

Today’s topic is on optimization. Some system developers don’t believe in optimization. However, I’m going to show you why you should really learn how to optimize, and second I’m going to demonstrate that even if you don’t believe in optimization then “not optimizing” is not the solution. “Not optimizing” is not the opposite of optimization!

First, we’re going to assume you want supernormal returns. Let’s just think about what it means for both the strategy and about the markets. If a strategy can deliver supernormal returns without optimization then it suggests that there is robustness to the strategy. That’s a good thing! But what does it say about the market? It suggests the market is not very efficient. We know that’s not the typical case.

The “opposite of optimization” is not “not optimizing”! Merely looking at a single performance report won’t tell you about how robust a strategy is or what the typical return is likely to be. What you are really doing when you “don’t optimize” is making an arbitrary decision, or a random decision. You are picking some random values. It doesn’t tell you conclusively about what the typical result looks like. Now, if you were to randomly pick values for your variables and do that over and over again then you’d start to get some real insights into the strategy. And that’s the idea behind Monte Carlo methods. An optimization algorithmic is just a more intelligent take on the same theme. Instead of randomly selecting values, the optimizer simply steps through the reasonable values one by one (or uses genetic or other advanced methods), and goes one step further by highlighting the very best input values for you. You see the true opposite of optimization is diversification. Diversification, in this case, means to trade multiple combinations of parameters. Instead of trading a strategy with optimal parameters with more size, you could trade a basket or “class” of similar strategies all running with slightly different parameters. In a future post, I’ll share with you an advanced technique for achieving both a higher degree of optimization and diversification, and without requiring a larger account.

But, here’s a simple way to optimize sensibly. Run your optimization and look over all returns. Do they look random or do you see any clear relationships? Look at the values above and below the best returns. Are they still reasonable? This is called sensitivity analysis testing and is important. Next, take an average of all returns say 25% above and below your optimal and average them to get a more realistic outlook on your system. You can also take an average of the top 25% of all returns and the bottom 25% of all considered returns. You can do this for drawdowns and other system measures too. You can also compute the min/max for these values which will provide more information than a single performance report. By going through these processes, you’ll start to build up a more complete perspective of the performance metrics of your system.

Examples follow:

Sensitivity analysis reveals that the returns are random. Don’t trade this system.

Input

Return ($)

12

-3,000

11

2,000

10

25,000

9

-8,000

8

-15,000

Sensitivity analysis looks good. Even though the best return was $29,000, the average of the best returns was only $20,000. Going forward, we might hope to get $29,000 over the same length of time but we know that $20,000 is a more realistic optimistic return.

Input

Return ($)

12

18,000

11

23,000

10

29,000

9

17,000

8

15,000

What’s a pessimistic return for the strategy below over the same length of time? The tricky part is determining what a “reasonable” value is for a parameter. But, let’s assume all the values shown are reasonable. We take the average of the bottom three returns which yields approximately $400. One benefit to analyzing your systems this way is it gives you a more complete and realistic view.

Best Case Return: $24,000 (MAX)
Optimistic/Target Return: $19,000 (Average of top 3rd)
Average: $10,000 (Average)
Pessimistic: $400 (Average of bottom 3rd)
Worst Case: -$1,500 (MIN)
All values are rounded to avoid giving a false sense of precision.

Input

Return ($)

10

24,000

9

17,000

8

15,000

7

12,000

6

10,000

5

11,000

4

2,500

3

-1,500

2

-700

1

3,500

-- Curtis from blog Beyond Backtesting

]]>
https://easylanguagemastery.com/building-strategies/why-you-should-optimize/feed/ 1
Are your backtest results fooling you? https://easylanguagemastery.com/development-tools/backtest-results-fooling/?utm_source=rss&utm_medium=rss&utm_campaign=backtest-results-fooling https://easylanguagemastery.com/development-tools/backtest-results-fooling/#comments Mon, 30 Dec 2019 11:00:13 +0000 http://systemtradersuccess.com/?p=7437

Have you ever started trading a strategy that performs well in the backtests but delivers a very different result when you begin trading it with real money?

Could your backtest reports be fooling you by indicating a strategy is great but really only showing you part of the overall picture?

How do you give yourself a better chance of developing trading systems that are robust and perform well going forward?

Kevin Davey (not the guy pictured above!), World Cup Trading champion from kjtradingsystems.com, has been creating trading strategies for over 25 years. In Episode 5 of the BetterSystemTrader podcast he says:

It’s amazing how easy it is to create systems that you think are good that just fall apart. –...

Click to Tweet

To reduce the chance this could occur he completes Monte Carlo analysis on all his systems to ensure they are robust and meet his risk requirements BEFORE he puts his money on the line.

What is Monte Carlo analysis and how can it be used to improve your own trading results? Read on, we’re going to show you.

What is Monte Carlo analysis?

Monte Carlo analysis is a process that allows you to get a more accurate picture of the performance of a trading strategy beyond what a standard backtest report can provide.

A backtest report shows the results of a series of trades in a specific order, but the problem is that’s just history, you don’t know what’s going to happen as it goes forward. What if a lot of losing trades all show up in a row, what type of drawdown will you experience? What’s the chance that you could get a drawdown larger than anticipated, or a string of losing trades longer than expected?

Monte Carlo analysis basically lets you scramble the order of the trades in a backtest to provide a better understanding of possible future performance, based on the assumption that future trades will have similar characteristics to historical trades but in an unknown order.

The results allow you to determine the probabilities of drawdown and profit levels and the chance your trading account could be completely wiped out.

Your worst drawdown is always in front of you.– Kevin Davey

Click to Tweet

Is it really that important?

Yes, even the seasoned pros like Kevin use it and this is why:

I’ve actually found cases where the walk forward equity curve looked great – probably a lot of people just made the decision, “Hey, I’m going to trade it.” But when I ran the Monte Carlo simulation I found out that there was really a lot more risk in the system and it was a lot riskier than I had anticipated. So basically the amount of return that I was getting compared to the amount of risk I could have, that didn’t necessarily show up in that historical equity curve, was just too much for the profit I was getting and so I basically said, “Well I can’t trade this particular system.”

Using the Monte Carlo analysis tool

Kevin has kindly offered a free copy of the Monte Carlo analysis tool he’s developed in Excel, for all Better System Trader podcast listeners. There is a link to download the tool at the end of this article but let’s first see how it works and how to apply the results to our own trading.

When you open the simulator, there are a few values you need to enter based on your own personal trading parameters. (If it prompts you to enable the macros you will need to say yes otherwise the simulator won’t work).

To setup the simulator enter your trading details in the light blue sections, starting in the top left with the base starting equity, the level at which you would stop trading the system if the account equity fell below it and the average number of trades per year:


To enter your trades into the simulator press the ‘Clear’ button and paste the list of trade profit and loss in $ from your backtest report.

For this example we’ll use a list of 1,805 trades over 10.5 years. Based on a $10,000 starting balance the CAR is 31% and Maximum Drawdown is 11%, which results in quite a smooth equity curve:

The results may seem impressive but let’s run it through the Monte Carlo simulator. By adding the trades into the simulator and pressing the Calculate button, the simulator runs through the list of trades 2,500 times, randomizing the sequence of trades each time. We’ve set a starting equity of $10,000 to match the backtest and the stop trading level has been set to $8,000.

The results from the simulator are very interesting.

Analyzing the results

We’ve run the trade list through the Monte Carlo simulator and now it’s time to compare the results with the backtest:

The first thing to notice in the Median Drawdown for the Monte Carlo simulations is 24.6%, however, the backtest reported a Maximum Drawdown of 11%. How can this be?

By switching the order of the trades we’ve identified that the strategy actually contains more risk than the backtest report shows. The favorable sequence of trades in the backtest is understating actual risk!

Also, if the backtest report only produces a drawdown of 11% but the Monte Carlo Median Drawdown is 24.6%, there are likely sequences of trades that have produced 50% drawdowns or larger, much higher than the drawdown limit of 20%.

Note that trading this strategy with a $10,000 starting balance has a 33% chance that it will meet or exceed the 20% drawdown limit. This risk of ruin is much too high.

Applying the results

The Monte Carlo results have shown that starting with a $10,000 account and a 20% drawdown limit we have a 33% chance of ruin and the Median Drawdown of 24.6% is higher than our drawdown limit. What can we do about this?

Without adjusting the strategy rules or risk per trade it seems the best approach is to start with a higher account balance. By checking the yellow results table in the Monte Carlo simulator we can see that we should probably trade this strategy with $25,000 or higher:

Conclusion

We can now see the importance of Monte Carlo analysis in the system development process. This basic example has shown us how backtest results, which only show the performance of one order of trades, may not be showing the full picture.

By running the trade list through the Monte Carlo simulator we’ve determined:

  • The Maximum Drawdown value in the backtest report (-11%) was based on a favorable run of trades and was understating the actual risk of drawdowns, with the Monte Carlo simulations showing a Median Drawdown of -24.6%.
  • The Risk of Ruin when trading a $10,000 account size was 33%, much too risky to trade, therefore a larger account size or smaller trade risk would be required to reduce the possibility of ruin.

Download it

To get your free copy of the Excel document please visit this link and scroll to the bottom of the page. The Excel document is provided by Kevin Davey and Better System Trader. Be sure to listen to Kevin Davey’s interview on Better System Trader.

—  by Andrew Swanscott from Better System Trader

]]>
https://easylanguagemastery.com/development-tools/backtest-results-fooling/feed/ 4
World’s Simplest Trading System https://easylanguagemastery.com/strategies/worlds-simplest-trading-system/?utm_source=rss&utm_medium=rss&utm_campaign=worlds-simplest-trading-system https://easylanguagemastery.com/strategies/worlds-simplest-trading-system/#comments Mon, 16 Dec 2019 11:00:00 +0000 http://systemtradersuccess.com/?p=9366

[NB. OK, it's possible that this isn't absolutely the simplest trading system imaginable, but apart from buy and hold it is unlikely there are many systems much simpler than this one!]

The following chart illustrates such a portfolio for the FTSE 100 Index since 1995. The diamond markers indicate the decisions made at the end of each month whether to be in the market (green diamond) or in cash (red diamond).

Roughly, one can see that the system kept the portfolio in the market in uptrends and out of the market (in cash) when the market fell. This trading system is well-known in the US, what we will look at here is:

  1. if the trading system can be profitably applied to the FTSE 100 Index.
  2. Whether 10 months is the optimum parameter for the moving average (or would a 5-month, or 15-month, moving average produce superior results)?

Terminology: we will use SMATS(10) to refer to the 10-month simple moving average trading system. And SMATS(5) for the trading system using the 5-month simple moving average etc. Below we will analyse the trading system for 14 different parameters of the simple moving average, i.e. from SMATS(4) to SMATS(16).

Performance Analysis 

First, let’s look at the overall profitability of SMATS.

Proftiability 

The following chart plots the values of the SMATS portfolios for the 14 different simple moving averages (i.e. 4-month to 16-month). As a benchmark the FTSE 100 is added (i.e. this is the value of a buy and hold FTSE 100 portfolio). All values were re-based to start at 100.

Some observations:

  1. By the end of the 20-year period all the SMATS portfolios had out-performed the FTSE 100 – except SMATS(5).
  2. By the end of the period, SMATS(10) had the highest value; although it can be seen that it wasn’t consistently the most profitable throughout the whole period.
  3. For the first six years (up to August 2001) all SMATS under-performed the FTSE 100. This was caused by the market volatility in 1998 and 2001, which caused the portfolios to be whipsawed in and out of the market.
The following chart summarizes the final portfolio values in 2016 after running the trading system from 1995.

By 2016 the STATS(10) portfolio had the highest value of all portfolios at 269; the FTSE 100 buy and hold portfolio a value of 199.

Risk 

We’ve looked at profitability, let’s now consider the risk incurred by each portfolio. We’ll use volatility as a (fairly standard) proxy for risk.

The following chart shows the volatility of the portfolios over the 20-year period.

Not surprisingly the FTSE 100 had the highest volatility. The volatility of the SMATS portfolios was less due to the fact they were in cash for part of the time; broadly their volatility increased as the moving average month parameter increased.

The Sharpe Ratio combines returns with volatility to provide a comparative measure of profitability per unit of risk incurred. The ratio’s purpose is to answer questions of the form: is the profitability of a strategy justified by the risk incurred, compared to another strategy?

The following chart plots the Sharpe Ratio for the 14 portfolios. (The benchmark for the Sharpe Ratio calculation was the FTSE 100 Index.)

SMATS(10) had the highest (i.e. the best) Sharpe Ratio, although close behind were SMATS(14) and SMATS(15).

Max Drawdown 

Maximum Drawdown decribes the maximum loss a portfolio suffered from a previous high value. For example, in this test SMATS(10) had a max drawdown value of 22.8%. This means that over the 20-year test period the portfolio was at most 22.8% under water (from a previous high).

Frankly, max drawdown has more significance for strategies that employ leveraged products (e.g. futures), as drawdowns incur realised losses as margins have to be paid. By contrast in the case of unleveraged equities or ETFs, drawdowns incur unrealised losses. Having said that, unrealised losses can still be uncomfortable and can have a major adverse psychological impact on the investor or trader.

The following chart shows the max drawdown values for the 14 SMATS portfolios and the FTSE 100 Index.

Here the SMATS(10) portfolio only had a middling relative score. The best portfolios (i.e. those with the lowest max drawdowns) were: SMATS(7), SMATS(14), SMATS(15), and SMATS(16).

Trade Frequency

The following chart shows the average number of trades for the year for each portfolio. For example, over the 20-year test period SMATS(10) portfolio traded 36 times, which is an average of 1.7 times a year.

As would be expected the number of trades decreases as the length of the moving average month parameter increases. In other words, systems get whipsawed less with longer moving averages. 

The profitability figures above did not include transaction costs, but with the systems averaging under 2 trades per year the transaction costs would not be significant.

Summary Of Analysis

The following table summarises the above analysis. The values are colour-coded with green being the best value through to red being the worst for each respective analysis.

Conclusion

  1. This simple moving average trading system did work for the FTSE 100 (i.e. it out-performed the FTSE 100 Index) over the 20-year period.
  2. The best performing portfolio was indeed SMATS(10), i.e. the trading using the 10-month simple moving average. It had the highest absolute profitability and also the highest Sharpe Ratio. After SMATS(10), the best portfolio was the SMATS(14), followed by SMATS(15).

 -- By  Almanacist from Stock Market Almanac

]]>
https://easylanguagemastery.com/strategies/worlds-simplest-trading-system/feed/ 8
Strategy Testing – Violating These Steps Will Damage Your Account https://easylanguagemastery.com/building-strategies/strategy-testing-violating-these-steps-will-damage-your-account/?utm_source=rss&utm_medium=rss&utm_campaign=strategy-testing-violating-these-steps-will-damage-your-account https://easylanguagemastery.com/building-strategies/strategy-testing-violating-these-steps-will-damage-your-account/#comments Mon, 04 Nov 2019 11:00:14 +0000 http://systemtradersuccess.com/?p=2817

One of the most rewarding experiences for a TradeStation trader is to pick up a performance report that proves their great strategy idea is indeed a profitable strategy. Strategy testing done properly, as is outlined in this article, can verify the efficacy of your trading strategy and give you confidence to start trading it. But be forewarned, strategy testing done improperly can lead you toward financial destruction.

Strategy testing done incorrectly can result in false hope in a losing strategy. A trader recently shared his experience of getting great results from strategy testing his idea, but after trading it live in the market, he was losing money every day. He was baffled about what he did wrong. Having gotten excellent results on his back-testing performance report, he wondered why his promising strategy was draining his trading account. The problem was he violated several of the proper steps necessary for reliable strategy testing.

With the knowledge of how to get an accurate performance report you will be able to trust your strategy in live trading and protect your trading account. In order to properly test a strategy, there are 5 main steps that are vital to follow; configure TradeStation, "in-sample data" testing, "out-of-sample data" testing, live forward testing on the simulator account, and real live trading execution.

Step 1: Configure TradeStation

Before you begin testing your data, you must configure TradeStation so that the data it pulls onto your performance report will be accurate. Follow these 3 critical items to properly configure TradeStation.

(a) In your TradeStation platform menu, go to “format symbol” and give TradeStation a starting and ending date to test. This historical date range is called the "in-sample data." Do not include the most recent six months in this “in-sample data.” The most recent six months is called the "out-of-sample data," and it will be used later during your "out-of-sample data" testing step.

(b) Next, in your TradeStation platform menu, go to "format strategy" and select "properties for all." Now select the "general" tab and enter the commissions and slippage (be as realistic as possible, or estimate too high if you are not sure). If this step is skipped, then the strategy testing performance report will be meaningless. If this is not done you might have a good looking performance report equity curve, but as soon as you enter the commissions and slippage figures the equity curve can reverse into an underwater equity curve.

(c) The last configuration step is under "properties for all" under the "general" tab. Look in the bottom left section called "strategy testing resolution." Check the "look-inside-bar back-testing" option and then select the smallest time frame available for your chart style to make the strategy testing more closely resemble live data. When strategy testing, TradeStation uses the open, high, low, and closing data, thus the larger the time frame bar, the more distorted the strategy testing performance report can be. This "look-inside bar back-testing" option will make the computer do a lot more strategy testing calculations. This may really slow down your performance report generation, so please be patient. For an accurate performance report you must use the "look-inside bar back-testing" option.

These configuration steps are critical to getting an accurate performance report, so be sure this is completed precisely before continuing. Once TradeStation has been configured correctly, you can begin testing your strategy.

Step 2: In-Sample Data Testing (also called “Back testing”)

You are now ready to start testing your strategy idea. We will begin with testing the “in-sample data” that you set up for testing during the configuration steps. Begin with bringing up a TradeStation performance report. Right now I have a performance report in front of me that I will refer to, but you will be looking at your own performance report to analyze your own numbers. This is what we will be referring to in the steps below. There are 7 sub-steps to “in-sample data” testing, as follows:

First, look at how many trades the strategy made. To reduce strategy testing errors, where error is defined by [ error = 1 / Square Root (Number Trades In Test) ], you want at least 400 trades to reduce the margin for error to 5% in your strategy testing results. At 100 trades you have a 10% margin for error. The greater the number of inputs in your strategy that you optimize, the greater the number of trades you need to keep from over optimizing your strategy.

Also look at how many times the strategy traded on average per day. The more often a strategy trades the more profit it can generate.

In the performance report that I am looking at, it traded 397 trades in the last 3 1/2 months, averaging 5.3 trades per day.

Second, look at the “Average Trade Amount.” It needs to be large enough that slow order fills and/or larger than normal slippage does not kill the profitability of the strategy.

In my report the “Average Trade Amount” is $162.32. The commissions and slippage amount as defined in the set up steps is already subtracted in this performance report.

65% of the time this strategy trades 1 contract.
35% of the time this strategy trades 3 contracts.
10% of the time this strategy trades 5 contracts.

Third, look to see if the “Profit Factor” and “Ratio Average Win-Average Loss” are both above 1.5 and the percentage of winning trades around 45% or better

This strategy had a “Profit Factor” of 1.83.
This strategy had a “Ratio Average Win-Average Loss” of 2.28 (2.28 means breakeven is around 28% “Percent Winning Trades”)
On this strategy the “Percent Winning Trades” was 44.58%.

Fourth, look at the trade list page and assess the profit run ups and draw downs column. Notice how many trades made money and how much money they made before the trade exit occurred. Looking at what amount of money was made in relation to the profit run up and draw down, you want to know if managing the trades could generate more profits. The example used here shows that a good percentage of trades made much higher profits than where the automated exit points occurred.

Fifth, look at the three draw down (DD) numbers. I like to see the largest number at 15% or less of the “Total Net Profit” and the “Max DD” at 5% or less of the “Total Net Profit” (these numbers tell about the draw down risk level during your trades).

Total Profit - $64,440
Peak to Valley DD - $8,960 is 13% of Total Profit
Close to Close DD - $7,120 is 11% of Total Profit
Max DD - $3,420 - 5% of Total Profit

Sixth, Looking at the “Largest Losing Trade” on the report, I like to see 5% or less of the “Total Net Profit.” In my report the “Largest Losing Trade” that occurred was $2,580 which is 4% of “Total Net Profit.”

Seventh, I review the length of time in the average trade. Does the average time in a trade comply with the golden rule of trading; "cut your losses quickly and let your profits run?" You will also want to see if the strategy is built using only profit exits (no real stop loss exits). It might have a nice looking report, but it could show a messed up ratio between average bars per winning trade verses average bars per losing trade if there are no stop loss exits. Here are my average bars:

Average bars per winning trade 7.24
Average bars per losing trade 3.51 bars

This strategy complies with the golden rule of trading. Notice how it cuts losses quickly, at an average of 3.51 bars, and lets the profits run for an average of 7.24 bars.

So what does this all mean? It means this strategy has passed the historical strategy testing phase of strategy testing.

Step 3: Out-of-Sample Data (also called "Walk Forward Testing")

Once you have tested your “in-sample data” and have determined that your strategy is worthy of continued testing, you can now test your strategy against the “out-of-sample data.” If you have not yet tested your “in-sample data, do that before proceeding.

To test the “out-of-sample data” we use the most recent 6 months of data available that you reserved in step 1(a). In step 1(b) of this article, we talked about configuring TradeStation and covered entering commissions and slippage and using the “look-inside-bar back-testing” option, which must be used to run any performance report used in your strategy testing. Be sure you have configured TradeStation correctly before moving on.

Go into “format symbol” and change the date range to include ONLY the "out-of-sample data" date range that was NOT used during the strategy testing on "in-sample data." This is referred to as testing on the "out-of-sample" data.

Begin with bringing up a TradeStation performance report on the "out-of-sample" data and review all the items that we discussed in step 2 above on this "out-of-sample" performance report. The closer it performs to the Step 2 “in-sample data” performance report, the more robust the strategy is. This suggests that the results were not from curve fitting and you have a good chance of having a viable strategy. This “out-of-sample” date range test is much more important than the strategy testing step on the “in-sample-data” for finding a successful strategy. It is a good idea to test multiple different "out-of-sample" date ranges, which is called “Walk Forward Analysis.”

Robustness: Perry J. Kaufman stated, "Practically speaking, a robust trading strategy is one that produces consistently good results across a broad set of parameter (input) values applied to many different markets tested for many years."

If the strategy fails during this "out-of-sample data" test, do NOT optimize using your reserved “out-of-sample data.” This would defeat this vitally important step in strategy development. You can go back to your strategy and fix it, or else drop it and develop a new strategy idea.

One caveat - if your strategy is capitalizing on a certain market condition, like the current volatility, and then you “out-of-sample data” test a non-volatile date range, it may not perform well, However in our next phase of testing, “ Live Forward Testing,” it could prove to be successful since we are still in a volatile market. You must understand why your strategy works, under what market conditions it performs well, and in what market conditions it does not perform well.

Now that you have tested your “out-of-sample” data and your strategy is promising, you are ready to live forward test your strategy on the simulator account.

At this point you have configured TradeStation so your performance report will be accurate, you have tested your “in-sample data” and your “out-of-sample” data and your strategy still looks great. Now you are ready to live forward test your strategy on the simulator account.

Step 4: Live Forward Testing on the Simulator Account

During your live forward testing on the simulator, you want to verify that the live data feed entries and exits are similar to historical entries and exits. After you have made live data trades for a day, save the live trade list. Now reload this same chart so the strategy recalculates based on the historical for this same day. Record the historical trade list and compare the live entries and exits to the historical entries and exits. Are they the same or at least similar? Do you understand the differences and the impact your "Live Data" test says about your strategy?

Only by monitoring the program daily can performance be seen under real "live" market conditions. Continue Live Forward Testing on the simulator until you are totally comfortable that your strategy works on live data. Real time results will often be less profitable than your historic results. The key question is does the real time testing show that you have a profitable strategy that is worth trading?

Step 5: Real Live Trading Execution

Once you have done your due diligence and are comfortable with your strategy results on the simulator, you are ready to trade live. Since you are trading a brand new strategy with real money, start with a significantly reduced position sizing risk of 1/4 of 1% of your account equity at risk per your stop loss point per trade. Continue trading with minimal risk until you have verified everything is working properly within your new strategy during live order executions.

Once your strategy is making money in the live market, slowly over time begin to increase your position sizing risk. Move your risk upward from 1/4 of 1% toward 1%. Continue trading at 1% risk until you have several weeks to months of consistent trading performance. If you want to be aggressive and use more, you can continue to increase toward the maximum 3% of your account equity at risk per trade.

If you follow the 5 steps as outlined in this article, you will now be able to confidently strategy test any strategy idea that you have. Keep this article for reference so the next time you are inspired with a great idea, you will be able to prove it out, protect your TradeStation trading account, and have confidence in live trading your strategy.

Click on this link to learn how to quickly and accurately strategy test any trading idea you might have.

-- by Mark David Johnson from Customizedtrading.

Mark David Johnson is a full time TradeStation Trader and TradeStation EasyLanguage Programmer for the past 6 years. He has been involved in programming for over 26 years and involved in trading for over 16 years.

]]>
https://easylanguagemastery.com/building-strategies/strategy-testing-violating-these-steps-will-damage-your-account/feed/ 2
Stops – When Not to Use Them https://easylanguagemastery.com/building-strategies/stops-when-not-to-use-them/?utm_source=rss&utm_medium=rss&utm_campaign=stops-when-not-to-use-them https://easylanguagemastery.com/building-strategies/stops-when-not-to-use-them/#comments Mon, 28 Oct 2019 10:00:07 +0000 http://systemtradersuccess.com/?p=3045

Using a stop on a position is a very popular risk management technique used by traders. My research and experience has led me to believe they are appropriate for some – but not all – types of trades. Today I will discuss when I believe they aren’t appropriate.

In Larry Connors' new book, “Short-term Trading Strategies That Work”, he dedicates a chapter to stops. It’s entitled, “Stops Hurt”.  The chapter discusses how Larry’s research team ran hundreds of tests to try and find optimal stop levels. In doing so, they came to the conclusion that for the trades they were looking at, the optimal stop was consistently none at all. In every case they found that instituting stops hurt system performance.

You should keep in mind that Larry Connors trades mean reversion strategies. Much of what I do is mean reversion based also. For instance, the Catapult system which makes up the CBI looks to buy stocks that are undergoing capitulative selling. It enters long positions in stocks or ETFs that are extremely oversold. When I first designed the system in 2005 I went through a massive series of tests to find a way to successfully incorporate stops into the methodology. Like Larry I failed to find a stop technique that would enhance the performance of the system.

I’ve gone through numerous other exercises and found the same thing time and time again. When looking to trade overbought/oversold techniques, stops generally don’t work well. If the system suggests the security should bounce when it drops to $20 and it continues to $18, then it is REALLY overdue for a bounce. Any level of stop ensures you are selling an extremely oversold security that is making a low. Those are buying conditions for oversold systems – not selling conditions.

One stop technique for oversold systems that I will sometimes use that in testing hurts performance less than the other techniques I evaluated is this:

Wait until the security bounces for a bar or two. Look for a higher high, higher low, and higher close – or at least 2 of those 3. Then place a stop under the swing low that was just made. In cases like this even if the security doesn't hit your target exit price, it still ensures that you won’t have to suffer through the entire next leg down. While it seems logical and can sometimes help avoid catastrophic trades in the long run, you’re normally better off just waiting for the mean reversion to occur and exiting at your target level.

Not using stops does not equal not controlling risk. Position sizing becomes very important. Traders could also consider using options to trade their short-term positions. Options provide a natural stop (zero). I wrote a series back in the spring (when the VIX was a lot lower) on how I sometimes use options for my short-term trading. You can find the link here:

While stops do not work well for overbought/oversold trading, they DO work well with breakouts or trend following systems. Traders that buy on a pattern breakout do so because their analysis indicates a trend could emerge in the stock or security they are trading. A reversal back into the base or below it would invalidate the pattern from a technician’s standpoint. Therefore, in such cases I believe a stop is completely appropriate. Once the pattern “fails” you should no longer be in the trade. Of course some people may want to give a little extra leeway rather than putting a stop right at a support point, but even so, there is a point where the breakout simply didn’t take.

For my own breakout trading I tend to use very tight stops. I also tend to show little patience for a trade to work once I enter it. Most successful breakouts have a tendency to work right away, and when the market environment is conducive to breakouts there’s just no point in sitting around with dead wood. I’d rather exit with a small profit or loss and try the next one.

The edge in breakout or trend trading is not in the winning percentage. It’s in the risk/reward. A big winner can gain several hundred percent if it goes on a tear. That makes up for an awful lot of scratches and small losses. As an example, in 2003 I did a lot of breakout trading. Cup & Handles, Flat Bases, High Tight Flags, Double Bottoms, etc. – all based primarily on daily bars. It was a tremendous year for trading breakouts because the ones that took caught fire rather quickly. It was also one of my best market years. Yet, at the end of the year I went back and tallied the percentage of breakout trades I took that “worked”.  In other words, they did better than a very small gain or scratch. My success rate? A little under 15%.  And it was a great year. Why?  Tiny losses and massive gains.

Everyone’s style is different and someone with more patience would likely have had a better win rate, but the win rate wasn’t important. What was important was controlling the losses, and one way to do that was through the use of stops.

-- By Rob Hanna from Quantifiable Edges. Rob Hanna has been a full-time market professional since 2001.  He has served as president of Hanna Capital Management, LLC since that time.  He first began publishing his market views and research in 2003.  From 2003 to 2007 his column “Rob Hanna’s Putting It All Together” could be found twice a week on TradingMarkets.com. In January of 2008 Rob began Quantifiable Edges.  In 2012 Rob opened his 2nd website, Overnight Edges.  Both sites use historical analysis to asses current market action and odds.  Rob utilizes price action, volume, breadth, sentiment, seasonality, liquidity flows and more to conduct his research.  Some of the indicators he uses are well known and publicly available.  Others were created in-house.  His work has been widely referenced and quoted over the years, and is often linked to in blogs, tweets, Stocktwits messages, magazine articles and more.  Below are some other places you may have seen some of Rob’s work.

]]>
https://easylanguagemastery.com/building-strategies/stops-when-not-to-use-them/feed/ 9