automated trading – Helping you Master EasyLanguage https://easylanguagemastery.com Helping you Master EasyLanguage Sun, 01 Feb 2026 10:53:17 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://easylanguagemastery.com/wp-content/uploads/2019/02/cropped-logo_size_icon_invert.jpg automated trading – Helping you Master EasyLanguage https://easylanguagemastery.com 32 32 Riding the Market Waves: How to Surf Seasonal Trends to Trading Success https://easylanguagemastery.com/market-studies/market-seasonality-study-may-2019/?utm_source=rss&utm_medium=rss&utm_campaign=market-seasonality-study-may-2019 https://easylanguagemastery.com/market-studies/market-seasonality-study-may-2019/#comments Mon, 26 Aug 2024 10:00:00 +0000 http://easylanguagemastery.com/?p=19871

Remember that old Wall Street chestnut, "Sell in May and go away"? Well, grab your favorite beverage and settle in, because we're about to dive into this age-old wisdom and see if it really holds water.

Now, I don't know about you, but I've always been a bit skeptical of these catchy market phrases. They sound great at cocktail parties, but do they actually work? That's exactly what I set out to discover.

In this article, we're going to break down our Market Seasonality Study step by step.

Below is a graph of the market with a "buy" at the start of the strong period and a "sell" at the end of the strong period.

Testing the "Buy in November, Sell in May" Strategy

To evaluate the popular trading concept of buying the S&P in November and selling in May, I set up a test with the following parameters:

  • Market: S&P cash market
  • Time period: 1960 to present
  • Position sizing: Risk-adjusted, with $5,000 risked per trade based on market volatility
  • Transaction costs: Not included (no slippage or commissions accounted for)

The core logic of this strategy can be implemented in EasyLanguage as follows:

CurrentMonth = Month(Date);
If (CurrentMonth = BuyMonth) And (MP = 0) Then
Buy("Buy Month") iShares contracts next bar at market;
If (CurrentMonth = SellMonth) Then
Sell("Sell Month") iShares contracts next bar at market;

This code does the following:

  1. Determines the current month
  2. If it's the buy month (November) and we're not in the market, it enters a long position
  3. If it's the sell month (May), it exits the position

By using this simple logic, we can test whether this well-known market adage holds up over a long period of historical data.

Test Parameters and Assumptions

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

  • Starting account size: $100,000
  • Test period: January 1960 through May 2024
  • Position sizing: Full account size used when opening a new position
  • Equity management: P&L not accumulated to the starting equity
  • Transaction costs: No deductions for commissions and slippage
  • Risk management: No stops were used

With these parameters set, we can now input the key months for our seasonality strategy:

  • Buy month: November
  • Sell month: May

Using these inputs, we generated the following equity graph:

Buy November, Sell May

Buy November, Sell May

"Sell in May and Go Away" Strategy Results

The equity curve we generated visually represents the performance of our "Sell in May and Go Away" strategy over the 64-year test period. It allows us to see the long-term trend as well as any significant drawdowns or periods of exceptional growth. And I must say, it sure looks like these months have a long bias - those are some impressive results!

Let's break down the numbers:

  • Total Profit: $4,640,085
  • Max Intra-day Drawdown: $1,403,538
  • Net Profit vs Drawdown Ratio: 3.3

In simpler terms, for every dollar of drawdown, the strategy is making just over three dollars in profit. That's a respectable ratio by most trading standards.

Inverting the Strategy

But here's where it gets really interesting. What would happen if we flipped our strategy on its head? Instead of buying in November and selling in May, what if we did the opposite - buying in May and selling in November?

To find out, I inverted the BuyMonth and SellMonth inputs in our test. Here's the resulting equity curve:

Buy May, Sell November

Buy May, Sell November

Analyzing the Inverted Strategy Results

The inverted equity curve provides a fascinating contrast to our original strategy, allowing us to visually compare the performance of buying during the traditionally "weak" months versus the "strong" months.

Let's break down the performance of this inverted strategy:

  1. 1960-1970: The equity curve consistently declined.
  2. 1970-1978: It bottomed out and began to climb.
  3. 1978-1997: Steady growth, reaching an equity peak in 1997.
  4. 1997-2008: Entered a drawdown period, bottoming in 2008.
  5. 2008-2021: Recovered, reaching new equity highs in 2020 and 2021.

Key metrics for the inverted strategy:

  • Total Profit: $94,148
  • Max Intra-day Drawdown: $92,357
  • Net Profit vs Drawdown Ratio: 1.0

This 1:1 ratio indicates that you must endure a dollar of drawdown for every dollar of profit - a much less attractive risk-reward proposition compared to our original strategy.

Let's focus on the strong season period from November-May moving forward. Can we add a filter to improve the results?

Implementing a Simple Moving Average Filter

To refine our strategy and avoid potentially unfavorable entry and exit points, we're introducing a 30-period simple moving average (SMA) as a short-term trend filter. This addition aims to prevent us from:

  1. Buying immediately into a falling market
  2. Selling immediately into a rising market

Here's how it works:

  • For Selling: If May (our SellMonth) arrives and the market is rising (price above the 30-period SMA), we delay selling until the price closes below the SMA.
  • For Buying: If November (our BuyMonth) arrives, we only buy when the price closes above the SMA.

To implement this in EasyLanguage, we create two flags: BuyFlag and SellFlag. These indicate when the proper conditions for buying or selling are met based on our short-term trend filter.

if (MinorTrendLen > 0) Then 
BuyFlag = Close > Average(Close, MinorTrendLen)
Else
BuyFlag = true;

If (MinorTrendLen > 0) Then
SellFlag = Close < Average(Close, MinorTrendLen)
Else
SellFlag = true;

The MinorTrendLen variable is an input that determines the SMA's look-back period. An additional check allows us to enable or disable the SMA filter:

  • If MinorTrendLen > 0: The SMA filter is active
  • If MinorTrendLen = 0: Both flags are always true, effectively disabling the filter

This flexibility lets us easily compare performance with and without the filter.

Strong Seasonality Trade (November-May) With Filters

Baseline

SMA Filter

Net Profit

$4,640,095

$5,961,005

Profit Factor

4.42

4.81

Total Trades

64

64

Avg.Trade Net Profit

$72,501

$93,140

Annual Rate of Return

9.54%

9.93%

Max Drawdown(Intraday)

$1,403,538

$1,856,564

NP vs Drawdown

3.3

3.2

We increased the net profit, profit factor, average profit per trade, and annual rate of return. There is a slight decline in the NP vs Drawdown ratio, but it's tiny. We can decently pull more profit by applying a simple moving average.

MACD Filter

A standard MACD filter is a well known indicator that may help with timing. I'm going to add a MACD calculation, using the default settings, and only open a new trade when the MACD line is above zero. Likewise, I'm only going to sell when the MACD line is below zero.  Within EasyLanguage we can create a MACD filter  by creating two Boolean flags called MACDBull and MACDBear which will indicate when the proper major market trend is in our favor.

If ( MACD_Filter ) Then
Begin
MyMACD = MACD( Close, FastLength, SlowLength );
MACDAvg = XAverage( MyMACD, MACDLength );
MACDDiff = MyMACD - MACDAvg;
If ( MyMACD crosses over 0 ) Then
Begin
MACDBull = True;
MACDBear = False;
End
Else If ( MyMACD crosses under 0 ) Then
Begin
MACDBull = False;
MACDBear = True;
End;
End
Else Begin
MACDBull = True;
MACDBear = True;
End;

Below are the results with the MACD filter:

Strong Seasonality Trade (November-May) With Filters

Baseline

SMA Filter

MACD Filter

Net Profit

$4,640,095

$5,961,005

$4,685,543

Profit Factor

4.42

4.81

5.35

Total Trades

64

64

63

Avg.Trade Net Profit

$72,501

$93,140

$74,373

Annual Rate of Return

9.54%

9.93%

9.55%

Max Drawdown (Intraday)

$1,403,538

$1,856,564

$1,205,264

NP vs Drawdown

3.3

3.2

3.8

Utilizing the MACD filter and comparing it to our baseline system, we can see we don't make as much more as the simple moving average filter, however, we increased our risk adjusted return with a NP vs DD of 3.8. So, if drawdown is your concern and not just pure profit it looks the MACD filter is slightly better.

RSI Filter

For our final filter I will try the RSI indicator with its default loopback period of 14. Again, like the MACD calculation, I want price moving in our direction so I want the RSI calculation to be above zero when opening a position and below zero when closing a position.

If ( RSI_Filter ) Then
Begin
   RSIBull = RSI(Close, 14 ) > 50;
   RSIBear = RSI(Close, 14 ) < 50;
End
Else Begin
   RSIBull = true;
   RSIBear = true;
End;

Strong Seasonality Trade (November-May) With Filters

Baseline

SMA Filter

MACD Filter

RSI Filter

Net Profit

$4,640,095

$5,961,005

$4,685,543

$4,080,657

Profit Factor

4.42

4.81

5.35

4.24

Total Trades

64

64

63

64

Avg.Trade Net Profit

$72,501

$93,140

$74,373

$63,760

Annual Rate of Return

9.54%

9.93%

9.55%

9.34%

Max Drawdown (Intraday)

$1,403,538

$1,856,564

$1,205,264

$1,291,784

NP vs Drawdown

3.3

3.2

3.8

3.1

Filter Comparison Results

The RSI filter performed worse than both the MACD and SMA filters.

In the end, it appears that applying either an SMA filter or an MACD filter can improve the baseline results. Both filters are relatively simple to implement and were tested for this article using their default values. Of course, this simple study could be expanded much further.

Applying Filters to the Weak Seasonality Period

After performing the different filter tests and selecting the simple moving average filter as the most effective, I began to wonder how our three filters would perform if applied to the weak seasonality period. Below are the performance results.

Weak Seasonality Trade (May-November) With Filters

No Filter

SMA Filter

MACD Filter

RSI Filter

Net Profit

$94,148

$244,406

$221,672

$121,740

Profit Factor

1.42

1.67

1.79

1.52

Total Trades

64

64

63

64

Avg.Trade Net Profit

$1,471

$3,818

$3,518

$1,902

Annual Rate of Return

3.64%

5.03%

4.88%

4.00%

Max Drawdown (Intraday)

$92,357

$128,921

$106,121

$100,544

NP vs Drawdown

1.0

1.7

2.0

1.2

We can see that adding MACD Filter produces the best results in terms risk adjusted return (NP vs Drawdown). The SMA Filter products the best results in terms of net profit. Both provide a radical change when compared to the No Filter situation. 

Conclusion

It certainly appears there is a significant seasonal edge in the S&P market. The trading rules we used above for the S&P cash market could be applied to the SPY and DIA ETF markets. I've tested these ETFs, and they produce very similar results. The S&P futures market also yields comparable outcomes. Interestingly, this approach even seems to work well for some individual stocks.

Keep in mind that this market study did not utilize any market stops. This is not a complete trading system!

Practical Use: Market Regime Filter For Stock Index Markets

With some additional work, an automated trading system could be built from this study. Another application would be to use this study as a filter for other trading systems. I envision using these results as a regime filter for your existing trading systems that trade the stock index markets.

Strong Season Bull/Bear Filter

  • Bull Market = if price is above 30-day SMA
  • Bear Market = if price is at or below 30-day SMA

Weak Season Bull/Bear Filter

  • Bull Market = if MACD is above zero
  • Bear Market = if MACD is at or below zero

This seasonality filter could be applied to both automated trading systems and discretionary trading. While it may not be particularly helpful for intraday trading, it's worth testing in that context as well.

Being aware of these major market cycles can be invaluable in understanding current market conditions and potential future directions. This knowledge can enhance your overall market perspective and potentially improve your trading decisions.

I hope you found this study helpful and that it provides you with new insights for your trading strategies.

]]>
https://easylanguagemastery.com/market-studies/market-seasonality-study-may-2019/feed/ 2
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
Capture The Big Moves! (Updated 2023) https://easylanguagemastery.com/indicators/capture-the-big-moves/?utm_source=rss&utm_medium=rss&utm_campaign=capture-the-big-moves https://easylanguagemastery.com/indicators/capture-the-big-moves/#comments Mon, 03 Jul 2023 10:00:00 +0000 http://systemtradersuccess.com/?p=153

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

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

How It Works

We will start with a well-known indicator: the Relative Strength Indicator (RSI). The goal is to identify major bull market and bear market regimes. In his article, Peter does this by simply using an RSI indicator on a weekly chart and identifying two unique thresholds. Peter noticed that during bull markets, the RSI rarely goes below the value of 40.

On the other hand, during a bear market, the RSI rarely rises above the value of 60. Thus, when the RSI crosses these thresholds, you can determine the beginning and end of bull/bear markets.

For example, in the bear market during the financial crisis of 2008, the weekly RSI indicator did not rise above 60 until August of 2009. This signaled the start of a new bull trend. The next bear trend will be signaled when the weekly RSI falls below 40.

With these simple rules, you can determine bull and bear markets for the S&P cash index market.

  • Bull Markets RSI Often Above 60
  • Bear Markets RSI Often Below 40

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

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

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

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

Testing Lookback Periods

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

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

Lookback Period vs Net Profit

The above chart shows rising profit as the lookback period increased from 2 to 10. Then the growth slows down. You can make a case for a stable region between 9 and 24; the midpoint is about 16. Feel free to experiment on your own and pick a different value. The main point here is this: all the values produce positive results, and a wide range of values at the upper end of our scale generate excellent results. This makes me believe that this indicator is robust in signaling significant market changes.

Testing Environment

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

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

Results

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

CaptureBigMovesPerformance_2022_06_13

Capture Big Moves Performance 2022-06-13

Notice the short side loses money. I would guess this tells us over the life of the market, there is a strong upside bias. Below is the equity curve.

Capture Big Moves EQ Graph 2022-06-13

Capture Big Moves EQ Graph 2022-06-13

Using this indicator, we come up with the following turning points for significant bull and bear markets for the US indices. The blowup of the dot-com bubble happened in 2000, and we got out on October 14, 2000. The indicator then told us to go long on May 10, 2003. We then ride this all the way up to the financial crisis getting out of the market on January 12, 2008. Then on June 15, 2009, we went long. Overall, not too bad!

Does It Work Today?

Here is what the strategy looks like when applied to the price chart over the past few years. I also painted the price bars based on the RSI signal. Light blue price bars mean we are in a bull market, and red price bars represent a bear market.

Capture The Big Moves Recent Current Signal 2023-06-29

Capture The Big Moves Recent Current Signal 2023-06-29

The price action of 2019 and 2020 (Covid-19 Event) saw a sharp selloff, resulting in this indicator reacting slowly from a Bull-to-Bear transition. So, this strategy lost money on the long side and short side. Classic whipsaw behavior.

Will these sudden sell-offs and sharp rebounds continue into the future? I really don't know. But let's look at the most recent sell signal in 2022.

Sell Signal March 5, 2022

This signal resulted in booking a profit from the long trade. At the time of this writing in June of 2022, this looks like a reasonable exit point if the market continues to fall over the coming months. But we don't know what will happen at this point.

Buy Signal June 16, 2023

This signal resultsed in a loss on the short side. The downturn in the market which triggered and sell signal that started on March 5, 2022 turned out to be rather shallow.

Capture The Big Moves Recent Signals 2023-06-29

Capture The Big Moves Recent Signals 2023-06-29

How can this be used in your trading?

Perhaps you can use this as a basis for a long-term swing strategy. For example, maybe this is an indicator to let you know when to go long or liquidate your long positions within your 401(k) and other retirement accounts.

Keep in mind that short trades are not profitable. In my opinion, you're better off stepping aside during these short times. That is, close long positions and move to cash without attempting to short. Nothing wrong with being on the sidelines.

The strength of such a system is not in how much money you can make compared to buying and holding. The strength is avoiding drawdowns and providing a mechanism to start buying back into the market, so you don't miss the next bull market.

Or perhaps if you are a discretionary trader, you can use this to focus on taking trades in the primary direction of the indicator. Maybe when the RSI indicator signals a bull market, you may want to view this as another confirmation or green light to pursue whatever investment strategy you prefer. I thought it was an exciting and novel way to look at the RSI indicator.

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

Where Are We Now?


Bull Market Signal Since June 16, 2023


Recent market behavior as we go into the Summer of 2023 is signaling Bull Market. The signal was triggered on the week of June 16, 2023What do you think? Is a new bull marketing forming? Will it last?


]]>
https://easylanguagemastery.com/indicators/capture-the-big-moves/feed/ 27
When To Go Short: S&P Intraday Price Study (Update for 2022) https://easylanguagemastery.com/building-strategies/when-to-go-short-sp-intraday-price-study/?utm_source=rss&utm_medium=rss&utm_campaign=when-to-go-short-sp-intraday-price-study https://easylanguagemastery.com/building-strategies/when-to-go-short-sp-intraday-price-study/#respond Mon, 04 Jul 2022 10:00:56 +0000 http://systemtradersuccess.com/?p=4241

There are many opportunities to find a trading edge with intraday systems, and we will explore the very first step you should take.

This article will be an extension of a previous article where we performed an intraday price study. We do this by exploring different market sessions to determine if we can find an edge for a possible intraday trading system. If you have not read the previous article, When To Go Long, I urge you to read this because we will jump in and explore the same concept on the short side.

As a reminder, here are the five market sessions we will be looking at.

Five Market Sessions

  1. Pre-Market, 06:30 to 08:30
  2. The Open, 08:30 to 10:30
  3. Midday, 10:30 to 12:30
  4. The Close, 12:30 to 15:00
  5. Post-Market, 15:00 to 19:00

We will use the same trading principles used in the previous article. The only difference is we will be shorting the market instead of going long.

I will use a 10-period RSI for the mean reversion entry rule and enter a short position when the value is above 75.

If ( RSI( Close, 10 ) > 75 ) Then
   
Sellshort("SE Mean") next bar at market;

For the trend following the entry rule, I will use the 10-period momentum calculation and open a short position if the momentum is below zero.

If Momentum( Close, 10 ) < 0 Then 
   Sellshort("SE Momentum") next bar at market;

I will also use a simple 200-period moving average applied to the daily chart to act as a regime filter. A single trade is entered, and the position is closed at the end of the market session as defined above.

We are allowing only one trade per day. Slippage and commissions are not deducted, and no stops are used. I'll be testing using 15-minute data from 2000 - 2021. 

Trend Following Testing

BEAR MARKET: We're going to open a trend following trade when the momentum is below zero and when price is in a bear market. (daily price trading below the 200-day SMA).

Winner: Post-Market

Session

Avg NP / Trade ($)

TF Bear: Mid Day

12.26

TF Bear: Post-Market

17.42

TF Bear: Pre-Market

2.05

TF Bear: The Close

5.73

TF Bear: The Open

-15.38

BULL MARKET: I will reverse the regime filter, so we will take trades during a bull market. That is, we will be opening new trades when the price is trading above the 200-day simple moving average. I would not expect this to show great results. Shorting the stock index market during a bull market is very difficult.

Winner: Pre-Market is the clear winner. However, it's a meager value, and notice all the other sessions are negative. Shoring during a bull market is difficult!

Session

Avg NP / Trade ($)

TF Bull: Pre-Market

6.51

TF Bull: The Open

-2.55

TF Bull: Mid Day

-6.54

TF Bull: The Close

-12.13

TF Bull: Post-Market

-8.16

Testing Mean Reversion Characteristic

BEAR MARKET: Now, I will test our mean-reversion trading system rules over the five different periods. Trades are only opened during a bear market. 

Winner: Post-Market. The Pre-Market is the clear winner. Notice that most other sessions are positive, but only The Open is in the double digits.

Session

Avg NP / Trade ($)

MR Bear: Pre-Market

4.12

MR Bear:The Open

34.27

MR Bear: Mid Day

3.27

MR Bear: The Close

-37.13

MR Bear: Post-Market

65.69

BULL MARKET: Let’s now look at our mean-reversion trading strategy during a bull market. 

Winner: Pre-Market. Again, we can see shorting in a bull market is difficult.

Session

Avg NP / Trade ($)

MR Bull: Pre-Market

21.54

MR Bull: The Open

-8.10

MR Bull: Mid Day

-25.52

MR Bull: The Close

-19.15

MR Bull: Post-Market

3.08

Conclusions

I took all the results from above and put them into a single table, below. Now you can sort by Average Net Profit Per Trade by toggling the "triangle" on the column header. 

Session

Avg NP / Trade ($)

MR Bull: Pre-Market

21.54

MR Bull: The Open

-8.10

MR Bull: Mid Day

-25.52

MR Bull: The Close

-19.15

MR Bull: Post-Market

3.08

MR Bear: Pre-Market

4.12

MR Bear: The Open

34.27

MR Bear: Mid Day

3.27

MR Bear: The Close

-37.13

MR Bear: Post-Market

65.69

TF Bull: Pre-Market

6.51

TF Bull: The Open

-2.55

TF Bull: Mid Day

-6.54

TF Bull: The Close

-12.13

TF Bull: Post-Market

-8.16

TF Bear: Pre-Market

2.05

TF Bear: The Open

-15.38

TF Bear: Mid Day

12.26

TF Bear: The Close

5.73

TF Bear: Post Market

17.42

By sorting the average net profit per trade from highest to lowest, we can see what bubbles up to the top. We can presume that these are the best opportunities for building an intraday short only trading system.

The best performing sessions are.

  1. Mean Reversion: Bear: Post-Market
  2. Mean Reversion Bear: The Open
  3. Mean Reversion Bull: Pre-Market

Mean Reversion is the better strategy as all the top-performing strategies are mean reversion. Furthermore, shorting in a bear market takes the top two positions. The third position is interesting. It's shoring during a bull market.

Notice that shorting the Pre-Market during both a bull and bear market appears to hold an edge. Interesting.

Mean Reversion: Bear Market: Post-Market

Backtested Results: Here we can see the vast bulk of the profit happened on a handful of trades in 2022. So, I would not put too much value into trading this session. It looks like a few excellent trades biased the results. Of course, this good fortune may continue forward into 2022 and beyond.

Mean Reversion: Bear Market: The Open

Backtested Results: In this session we can see we have a climbing equity curve. This tells me we might have an an edge for a mean revering strategy during this session.

.

Mean Reversion: Bull Market: Pre-Market

Backtested Results: This is the best looking equity curve out of the three. This looks like the strongest session where a mean reversion strategy might be developed. Ironically, it's shorting during a bull market!

Conclusions

Remember, the strategies presented in this article are not viable trading systems as they currently stand. The strategies in this article are market studies! You can’t expect these simple trading strategies to produce results with real money.

These are nothing more than indicators to point us in the right direction. However, this article and the previous article demonstrate a way to analyze the market in an attempt to find an edge.

Can an intraday trading system be developed from the information presented in this article? Maybe. It will depend upon many factors. The point here is that this gives us a way to narrow our focus to a place to start.

Good luck, and let us all know, in the comments below, if you found this helpful or if you had success with building a trading system. 

]]>
https://easylanguagemastery.com/building-strategies/when-to-go-short-sp-intraday-price-study/feed/ 0
A Simple Trading System For Trading In A Bear Market https://easylanguagemastery.com/strategies/simple-shorting-strategy/?utm_source=rss&utm_medium=rss&utm_campaign=simple-shorting-strategy https://easylanguagemastery.com/strategies/simple-shorting-strategy/#comments Mon, 23 May 2022 10:00:10 +0000 http://systemtradersuccess.com/?p=4307

The major stock index markets are below their 200-day moving average. That's bearish!

A bear market can be a trader's worst nightmare. Prices are falling, volatility is high, and everyone seems to be selling. How can you make money in this type of market? One approach is to short counter-trend rallies in the stock index futures markets. Does such a system exist?

We'll review a simple shorting strategy in this article and see if we. Can take advantage of the downtrend and potentially make some profits. So, how does it work? Let's take a look.

Over the years, I've looked at several straightforward long strategies published in the book "Short Term Trading Strategies That Work" by Larry Connors and Cesar Alvarez. Those articles include the following long strategies:

Buried within Connors and Alvarez’s book, you will find one simple shorting strategy used on the major market indices. I will review this strategy in this article and see if we can improve it.

A Simple Shorting Strategy

The rules of this system are very simple.

  • Price must be below its 200 day moving average.
  • If the instrument closes up for four or more days in a row, sell short at close.
  • Cover your position when price closes below a 5-day SMA at open of next bar.

The trading model is straightforward and attempts to fade strong bullish moves when the market sentiment is bearish. By only taking trades when the market is below its 200-day SMA, we ensure bears are in control. We then attempt to sell into short-term bullish strength as defined by four days of consecutive market advances.Below is a screenshot showing example trades on the E-mini S&P. Click the image for a larger view.

Simple Shorting Strategy Trade Examples

Simple Shorting Strategy Trade Examples

Unless otherwise stated, all the tests performed in this article will be based on the following assumptions:

  • Starting account size of  $100,000.
  • Dates tested are from 2000 through May 12, 2022
  • There are no deductions for commissions and slippage.
  • There are no stops.
Simple Shorting Strategy Equity Curve

Simple Shorting Strategy Equity Curve

Simple Shorting Strategy Annual Returns

Simple Shorting Strategy Annual Returns

Not very impressive, with only 26 trades since the year 2000 we only generate 3.51% return on our capital. But this is expected as shorting is very difficult for the stock index markets.

The stock market indexes have an upside bias (trading above the 200-day SMA), so this strategy does not have the opportunity to open many trades. Thus as the strategy stands today, we're not capturing enough profit to make it worth pursuing. This is a similar result I wrote about in this article, “The Death Cross – What You Need To Know.

While I don’t expect much change, I loaded this strategy on the major futures index markets (NQ, YM, RTY). Below are are the results.

Simple Shorting Strategy

ES

NQ

YM

RTY

Total Net Profit

$12,950

-$2,465

$14,260

$18,460

Profit Factor

2.80

.81

2.34

6.13

Total No Of Trades

26

22

31

31

NP/DD

2.1

.11

2.9

2.7

Avg.Trade Net Profit

$487.08

-$112.05

$460.00

$595.48

Max Drawdown (intraday)

$6,225

$21,700

$4,995

$6,830

The clear winner is the RTY market. It has a wonderful looking equity curve, pictured below, but of course, it still suffers form lack of trades.

Simple Shorting Strategy Equity Curve RTY

Simple Shorting Strategy Equity Curve RTY

Generating More Trades

The main problem with this strategy is the lack of trades. Can we generate more trades? I think so.

The original rule to open a new position is to look for 4 consecutive up days. So, we're looking for a counter-trend rally but, why four days? Why not three days or five days? Let's make this entry rule a bit more dynamic.

Larry Connors is well known for popularizing the 2-period RSI. The well-known rule to go long the stock index market when the 2-period RSI goes below 20 is a solid buy signal during a bull market. Let's reverse this idea for a bear market.

We will make an important change. Because bear markets tend to be much more volatile, I'm going to double the RSI look back from two to four. I think a 2-period look back will fire off too frequently. In bull markets, we can have strong countertrend rallies and we don't want to short too soon into those rallies.  

So, our sell short rules will now look like this:

  • Price must be below its 200 day moving average.
  • The 4-period RSI must be above 75.

Let's look at the two best candidates from the original rules (ES and RTY) after applying this new entry rule.

ES With RSI(4)

We can see we did generate more trades. We've gone from 26 to 44. Sill not great, but an improvment.

Simple Shorting Strategy Equity Curve ES RSI

Simple Shorting Strategy Equity Curve ES RSI Entry

RTY With RSI(4)

Yes, we've added more trades here as well. We've gone from 31 to 50. We've lost our beautiful-looking equity curve, but we have more trades, and we're still making new equity highs going into 2022.

Simple Shorting Strategy Equity Curve RTY RSI

Simple Shorting Strategy Equity Curve RTY RSI Entry

Simple Shorting Strategy With RSI(4) Entry

ES

RTY

Total Net Profit

$31,850

$19,500

Profit Factor

3.59

2.36

Total No Of Trades

44

50

NP/DD

3.5

3.1

Avg.Trade Net Profit

723.86

$390.00

Max Drawdown (intraday)

$9,225

$6,2903

Conclusion

Can we make money shorting the market? Yes, but the results are not overly impressive with this strategy. It's great we found a simple technique to increase the number of trades, but it might be best to sidestep that bear market and find other opportunities elsewhere. 

You might be wondering, is this system tradable with real money? Not yet! I think this has potential but remember, there are no stops. With a bit of work on your part, you could trade something very similar to what's presented here.

]]>
https://easylanguagemastery.com/strategies/simple-shorting-strategy/feed/ 11
Trade Recorder Function And Strategy https://easylanguagemastery.com/development-tools/trade_recorder_function/?utm_source=rss&utm_medium=rss&utm_campaign=trade_recorder_function https://easylanguagemastery.com/development-tools/trade_recorder_function/#comments Mon, 12 Apr 2021 10:00:55 +0000 http://eminiedges.com/blog/?p=60

When developing, testing, or simply tracking an existing trading system it can be helpful to have each individual trade exported to a text file. Such data can be useful in analyzing the system performance in Excel. For example, the data can be used to calculate the trading system’s Expectancy and Expectancy Score. Or, the data could be used within a Monte Carlo simulation to give you a better idea of how the system may behave when different position sizing models are applied. In this article I’m going to demonstrate two EasyLanguage programs that can be used to export your trade history to an Excel file

Another common use for exporting your trades to a text file is importing your trades into a third party application. For example, you may want to import them into a Monte Carlo program or an application like Build Alpha to analyze and attempt to improve the performance. Often these third party tool want you to import your trades in a specific format. Well, if you know EasyLanguage you can do just that!

What Will We Track?.

What kind of information is tracked within the Excel document? There are several important pieces of information recorded, but one in particular can be very useful when computing the Expectancy and Expectancy Score. Below is an example of the file generated along with a description of each column.


Trade Recorder Results

  • Date and Time Open – The date and time when the trade was opened.
  • Date and Time Closed – The date and time when the trade was closed.
  • P&L – The profit or loss of the trade. Commissions and slippage are removed if you provided such information within the strategy properties.
  • Risk – Your initial stop value in dollars.
  • Volat – Volatility of the market in dollars when the trade was opened.
  • MAE – Maximum adverse excursion. This is the amount of heat your position took while open.
  • MFE – Maximum favorable excursion. This is how much money was left on the table after the position was closed.
  • BARS – Number of bars your position was open.
  • P&L (R) – Your P&L measured in units of risk (R).

Most of the information recorded are straight forward. However, the P&L (R) column may not be familiar for some people. The concept of measuring your profit in units of risk was popularized by Van Tharp in his book, Trade Your Way To Financial Freedom. A unit of risk is defined by your initial stop value which is called your Risk (R). Once a trade is closed we can express your P&L in units of risk by dividing the P&L value by R

P&L (R) = P&L / R

For example, let’s say your trading system has a fixed stop loss of $300. This value represents your R. Let’s also say your trade closes out with a profit of $500. This produces a P&L expressed in risk units of…

P&L (R) = $500 / $300
P&L (R) = 5/3

P&L (R) = 1.66

This means your P&L was $1.66 for every $1.00 you risked. Put it another way, your profit was 1.66 times what you risked. Why would you care to express your P&L in this form? Good question. 

After many trades you can plot a scatter graph of your P&L (R) values. This is somewhat helpful. A healthy scatter graph of P&L (R) values should have very few if any plots beyond negative one and should have a good number of plots well above positive one. But perhaps a more interesting number is the average of your P&L (R) values which is your Expectancy. If you will recall, within a previous article I showed you how to estimate expectancy. However, by using this method of calculation we are actually computing the true expectancy of our trading system. This is easy with the use of Trade Recorder because once you have your trades listed, you simply take the average of the P&L (R) and you have your Expectancy. Simple! From the Expectancy number you can then compute the Expectancy Score. If you’re not familiar with either Expectancy or Expectancy Score please review this article.

Trade Recorder Function

The first program is a TradeStation function called Trade Recorder Function. This was originally released in the fall of 2011 but has now been updated for 2021

The Trade Recorder Function allows you the most flexibility. It’s a function that can be added to any trading system. Simply place the function at the end of your strategy code and populate the input parameters within the required fields.

Here is an example of using Trade Recorder Function in your own code:

RetVal = TradeRecorder( WriteToFileFlag, FileName, SystemName, SystemVersionNumber, StopLoss$, ATR );

WriteToFileFlag is a switch that allows you to enable or disable the TradeRecorder function. Set to true and all trades are recorded to the Excel file. Set to false and none of the trades are sent to a file.
FileName is the filename and location of where to put the generated Excel file.
SystemName is the name of the system you are recording.
SystemVersionNumber is the version of the system you are recording.
StopLoss$ is the total dollar amount you are risking on a single trade.
ATR is the volatility measured at time of opening the position. I would like to use an Average True Range.

Here is an example of a Trade Recorder Function being called.

RetVal = TradeRecorder( true, “C:\breakout_test”, “Open Range Breakout”, “1.0”, myStop * numContracts, myATR );

The return value is meaningless. All TradeStation functions must return something. In this case, Trade Recorder Function always returns a zero. Once you have generated your results you can simply open the file with Excel or similar program.

EasyLanguage Trade Recorder Strategy

The second EasyLanguage program is a strategy called Trade Recorder Strategy which will allow you to record the progress of a trading system even if you don’t have access to the strategy code.This is a strategy which can be loaded into a chart which contains the strategy you wish to track. In essence, you are running two strategies at the same time (in parallel). However, Trade Recorder Strategy does not generate buy and sell signals. It only monitors the trades generated by the other strategy you are testing.

Note, one of the input parameters you will need to enter is the initial stop loss value of the system you are tracking. If you are planning on using this Trade Recorder Strategy on an existing trading system, you will have to know what the stop loss value is. This might not be possible if the trading system uses a variable or dynamic stop loss. If you do not know the initial stop loss value you can do two things:

  1. Use the trading system’s average loss. Simply review the system’s performance report and find the average loss value and use this number as the initial stop loss value. By doing this however, you are now estimating your expectancy and not computing the true expectancy. But your value will be a good estimate and that’s  better than nothing.
  2. If you have access to the code you can use the Trade Recorder Function. Using the function provides you with a lot more flexibility including the ability to plug-in the exact stop loss value even if it varies on each trade. This will allow you to calculate the true expectancy of your system. 

The second option is obviously a better idea for system developers who have access to the trading system code. However, if you don’t have access to the code you will have to use the first option.

Conclusion

With these two tools system developers can better understand their trading systems. All the files in this article are available as free EasyLanguage downloads. If you found an error in any of the files or have an idea to improve them, please leave your comments below.

]]>
https://easylanguagemastery.com/development-tools/trade_recorder_function/feed/ 11
The One Thing Before Building A Intraday Trading System https://easylanguagemastery.com/building-strategies/step-one-in-building-an-intraday-trading-system/?utm_source=rss&utm_medium=rss&utm_campaign=step-one-in-building-an-intraday-trading-system https://easylanguagemastery.com/building-strategies/step-one-in-building-an-intraday-trading-system/#comments Mon, 13 Jul 2020 10:00:19 +0000 http://systemtradersuccess.com/?p=3658

If you have been reading EasyLanguage Mastery for a while you’re probably familiar with how I develop trading systems. The very first step is to come up with a simple idea to act as the seed or core of your trading system. I call this your Key Idea. This key idea is a simple observation of market behavior. This observation does not need to be complex at all. In fact, they are often very simple.

For example, here is a key idea: most opening gaps on the S&P market close if the gaps are less than 4 points. This key idea is very simple, and testable. It is from such observation that I’ll often start to build a trading system from.

In this article I want to show you a tool I use to help test key ideas on an intraday chart. Building trading systems on intraday charts (day-trading systems) are some of the more difficult systems to develop when compared to daily charts. First, you must deal with more market noise but even more dangerous are slippage and commissions. Why? Your potential profit per trade is small on a day trading system thus, both commissions and slippage take a bigger bite out of your profits (as a percentage of your P&L). This produce drag on the performance of your system much like a strong headwind slows your advance. In short, it’s more difficult!

The Key Idea

For this example let’s create a simple trend following strategy for the Euro currency futures (EC) market on a 5-minute chart. We’ll use the extreme readings on the RSI indicator as our signal. Because we are using RSI as a trend indicator that means we are looking to enter the market when RSI gives us an extreme reading. That is, go-long at the oversold region and go-short at the lower region.

  • Buy when nine period RSI value above 80
  • Sell Short when nine period RSI value below 20

This might be a little different than how most people would use RSI. Most of the time, it seems anyway, you would fade the extremes. However, when it comes to the markets unconventional can be beneficial. As for the extreme values, those are un-optimized numbers. I just picked them off the top of my head in hopes of looking for a strong swing in either direction. Also, I picked a value of nine for the RSI look-back period because I wanted it to be more sensitive than the default 14 that is often used. (The value of nine really has no significance. It was not optimized and I could have very well picked 7 or 10. I just simply picked it.)

Below is the EasyLanguage code for the key idea.

MyRSI = RSI( Close, RSILookBack );

If ( MyRSI < ShortZone ) Then
begin
   GoShort = true;
   GoLong = false;
End

Else If ( MyRSI > BuyZone ) Then
Begin
   GoShort = false;
   GoLong = true;
End;

If ( MP = 0 ) Then
Begin
   If ( GoShort and BullTrend ) Then Sellshort ("RSI Short") next bar market
   Else If ( GoLong and BearTrend ) Then Buy("RSI Buy") next bar at market;
End;

If you code this basic concept up and test it from 08:30 to 15:00 (central) on the EC market what do you think you’ll get? That’s right, a losing concept with an ugly equity curve.

Clearly, we don’t want to trade our system at any time during the U.S. day session. We want to focus when EC is most likely to show strong trending characteristics. If the price of EC is strong enough to push the RSI value above 80 we want the price to continue climbing. So, what market session is best suited for this RSI trend system? Or are all market sessions hopeless for this simple trading concept? Let’s find out.

The Session Test

When designing a day trading system one of the first steps I want to perform is to test which market session will likely produce the best results. We are all aware that different sessions exist for any given market. For example, when dealing with the S&P E-mini we have a pre-market session - the morning session, lunch time session, and an afternoon session. Sometimes you can see distinct characteristics within each session.

So, when I’m developing a trading system for day trading I don’t want to blindly trade during every session. I want to be more targeted in my approach. There will be most likely a particular session or two where my key idea will do better than the other sessions. In order to test our key idea vs. different sessions I need to create an EasyLanguage function that can isolate these sessions and execute the key idea individually over those sessions only.

This is where my “Session Testing” code comes into play. Session Testing is an EasyLanguage function that I wrote to help me in this task of testing various intraday sessions. Using TradeStation’s optimizer I can test my idea across different combinations of sessions and discover how the key idea holds up across each session. Here are the basic sessions:

  1. “Pre-Market” Between 05:30 and 08:30
  2. “Open” Between 08:30 and 9:00
  3. "Morning" Between 9:00 and 11:30
  4. “Lunch” Between 11:30 and 13:15
  5. “Afternoon” Between 13:15 and 14:30
  6. “Close” Between 14:30 and 15:15
  7. “Post-Market” Between 15:00 and 18:00
  8. “Night” Between 18:00 and 05:30

From this list of basic sessions I created several more “sessions” based upon combinations of the above.

  1. “Pre-Market” + “Open”
  2. “Pre-Market” + “Open” + “Morning”
  3. “Open” + “Morning”
  4. “Open” + “Morning” + “Lunch”
  5. “Lunch” + “Afternoon”
  6. “Lunch” + “Afternoon” + “Close”
  7. “Daily Session”
  8. “Night” + “Pre-Market”
  9. “Morning” + “Afternoon”

The 17 different sessions I came up with may not please everyone. Perhaps you have a contrasting idea on how to break up the different sessions and with the code provided you can simply change them to your liking. For example, if you are interested in the European markets and trade those times, you can create your own sessions based around the European markets.

Session Test Function

The session testing function is really simple. You place it within your strategy and pass into the function the session number you wish to test. Below is an example of testing session 1 – what I’m calling pre-market.

TradeFlag = SessionTest( 1 );

The variable TradeFlag will be set to a Boolean value based upon if the current time is pre-market (true) or not (false). Now we can use TradeFlag as a switch to enable/disable our trading as demonstrated below.

If ( TradeFlag ) Then
Begin
// Trade Logic goes Here
End;

What’s going on inside of the function? It’s rather simple as it’s nothing more than a bunch of if-then statements testing the current time. Below is a code, snip-it to give you an idea of what it looks like.

If ( SessionToTest = 1 ) And ( Time >= PREMARKET ) And ( Time < THE_OPEN ) Then TradeFlag = true

Else If ( SessionToTest = 2 ) And ( Time >= THE_OPEN ) And ( Time < MORNING ) Then TradeFlag = true

If ( SessionToTest = 3 ) And ( Time >= MORNING ) And ( Time < LUNCH ) Then TradeFlag = true

Else If ( SessionToTest = 4 ) And ( Time >= LUNCH ) And ( Time < AFTERNOON ) Then TradeFlag = true

Here is our code with the session test function applied.

If ( TradeFlag ) Then
Begin

   MyRSI = RSI( Close, RSILookBack );

   If ( MyRSI < ShortZone ) Then
   begin
      GoShort = true;
      GoLong = false;
   End
   Else If ( MyRSI > BuyZone ) Then
   Begin
      GoShort = false;
      GoLong = true;
   End;

   If ( MP = 0 ) Then
   Begin
      If ( GoShort and BullTrend ) Then Sellshort ("RSI Short") next bar market
      Else If ( GoLong and BearTrend ) Then Buy("RSI Buy") next bar at market;
   End;

End;

Testing All Sessions

Next let’s see what happens when I run TradeStation’s optimizer over each of the sessions. In doing so TradeStation will systematically execute my key idea strategy over each market session and record the trading results. This can be done by simply creating an input value to act as the session number to test. Then you simply optimize over the values 1-17.

After all the sessions have been analyzed I can generate a bar graph representing the P&L for each session. Below is the Net Profit graph which depicts the total net profit from our testing. By the way, we were testing this strategy from January 1, 2003 to December 31, 2011. This time-span covers both bull and bear markets. It’s important to test your key idea over a wide range of market conditions. Slippage and commissions are not factors into these results.

In this case we can see session input value number 12 produces the best net profit. This input value is actually a combination of Open, Morning, and Lunch sessions. It’s during these times EC market apparently demonstrates strong trending characteristics that we might be able to take advantage of with our key idea.

Let’s now isolate the session input value to 12 and execute our key idea on this specific time. For this test I will deduct $18.50 per round trip for slippage and commissions. Below is the equity graph of our key idea along with some performance numbers.

There is no optimization here. The code simply trades based off un-optimized RSI signals and the results look promising. Below is the Trade Summary Report.

Please note I have no stops or targets within my test strategy. Instead the strategy simply enters a trade if the proper condition is met and the trade is exited only at the close of the session. That’s it. Remember, I’m not testing a trading strategy. I’m testing a key idea vs. different market sessions. My goal is to locate the best possible market sessions for my key idea. In this case, which session holds the strongest trending characteristic? Once a session(s) has been identified only then will I continue to develop a complete strategy (containing stops, targets, and other rules) tailored to the top session(s).

Conclusion

There you have it. This type of RSI trend following concept should be developed for the Open, Morning, and Lunch sessions. This makes sense. The big volume and big trends often appear during the U.S. day session. This is also corroborated from a previous Best Times To Day Trade, where I explored the hourly range of the Euro Currency market. In that study we can see that the hours between 08:00 and 11:00 (Central) have the highest price movement of the EC market.

I would like to point out again, this is not a trading system. What we did in this article was to validate our key idea. The code presented in this article does not have stops, a regime filter, volatility filters, profit targets, or any number of other checks and balances we might see in a true trading system. In fact, take a look at the average profit per trade. It’s $15 after slippage and commissions which is too low in my opinion. I would like to see this closer to $50 per trade or higher.

]]>
https://easylanguagemastery.com/building-strategies/step-one-in-building-an-intraday-trading-system/feed/ 12
Intermarket Divergence – A Robust Method for Signal Generation https://easylanguagemastery.com/building-strategies/intermarket-divergence-robust-method-signal-generation/?utm_source=rss&utm_medium=rss&utm_campaign=intermarket-divergence-robust-method-signal-generation https://easylanguagemastery.com/building-strategies/intermarket-divergence-robust-method-signal-generation/#comments Mon, 26 Aug 2019 10:00:00 +0000 http://systemtradersuccess.com/?p=7148

Many markets are interrelated. These interrelationships can offer predictive capabilities for many markets. The study of these interrelationships is called intermarket analysis. In this article, I will briefly explain a robust method for generating robust signals for a wide range of markets. I will also offer a free TradeStation tool to help you explore intermarket relationships.

Standard correlations between markets are not useful if our goal is to either predict future prices or generate profitable signals because current correlation does not tell us anything about future prices. A methodology we originally developed in the mid-1990s called intermarket divergence allows us to gauge the predictive power of an intermarket relationship and produce 100% objective signals. During the past 17 years we have used this methodology to develop trading systems which have produced robust and reliable trading signals even 17 years after the models were originally developed without any re-optimization. Other methodologies of processing intermarket relationships to develop trading signals might perform as well during in-sample periods, but do not perform as well during walk forward periods and during real trading.

A widely known intermarket relationship is the one between the S&P 500 and the 30 year Treasury bond. Bond prices generally are positively correlated with the S&P 500 (while yields are negatively correlated), although this is not always true, bonds should generally lead stocks at turning points. Another important fact is that one of the best trades you can make in the S&P 500 is when 30 year Treasury bond diverge from the S&P 500; for example, when (a) bonds are rising and the S&P 500 is falling, buy the S&P 500 and (b) bonds are falling and the S&P 500 is rising, sell S&P 500. Although this relationship has broken down over the past few years, its long term existence is of historical importance to the science of intermarket analysis.

Simple But Powerful Method of Market Predictions


We will use classic mechanical methods for trading intermarket relationships, applying them to 30 year Treasury bond using a concept called "intermarket divergence," (first coined in 1998) which is when a traded market moves in an opposite direction to what is expected. For example, if we trade the S&P 500, 30 year Treasury bond rising and the S&P 500 falling would be divergence since these are positively correlated. If we were trading the 30 year Treasury bond, both bonds and gold rising would classify as divergence since they are negatively correlated. We will define an uptrend as when prices are above a moving average and a downtrend as when they are below the moving average. Now we can predict with some reliability the future direction of bonds, stocks, gold, crude and even currencies using this simple intermarket divergence model. Pseudo code for this basic model is as follows:

Price relative to a simple moving average

Let InterInd = Close of Intermarket - Average (Close of Intermarket,N)
Let MarkInd = Close Traded Market - Average (Close of Traded Market,M)

Positive correlation

If InterInd > 0 and MarkInd < 0 then buy at next bars open
If InterInd < 0 and MarkInd > 0 then sell at next bars open

Negative correlation

If InterInd < 0 and MarkInd < 0 then at buy at next bars open
If InterInd > 0 and MarkInd > 0 then sell at next bars open

This simple concept represented above has proven to be a robust methodology for predicting future price action using intermarket analysis. In 1998, I published a simple intermarket based system for trading 30 year Treasury bond futures. This model used 'The NYSE Utility Average (NNA)', which was a basket of Utility stocks. The NNA was discontinued in 2004. Another utility index which also worked fairly well was the Philadelphia Electrical Utility index which was used as a replacement for NNA in our research. Back in 1998, when I did the original research and article, both indexes worked similarly, but NNA had a longer price history than UTY did. The original analysis using NNA was done as follows. We used a positive correlated intermarket divergence model and a moving average of eight days for 30 year Treasury bond and 18 days for NNA. We tested over the period Jan 1, 1988 to Dec 31, 1997. We did not deduct anything for slippage and commission. My original published results were as follows:

Net profit: $111,293.00
Trades: 126
Win %: 60%
Average trade: $883.38
Drawdown: $-8,582.00
Profit factor: 2.83

Now let us see how UTY worked during this same period using the original set of parameters used with NNA. This set of parameters was suboptimal for UTY but we are using the NNA set of parameters for consistency to show the robustness of our model.

Total Net Profit: $83,557.98
Total # of trades: 141
Percent Profitable: 58.87%
Avg. Trade (win & loss): $592.61
Max intraday drawdown: ($11,722.50)
Profit Factor: 2.03

Out-of-Sample Results

Let us study just the out-of-sample period with a first trade after 01/01/1998 to 10/25/2011.

Total Net Profit: $129,166.32
Total # of trades: 257
Percent Profitable: 61.87%
Avg. Trade (win & loss): $502.59
Max intraday drawdown: ($26,133.36)
Profit Factor: 1.67

We can see these out-of-sample results are very similar to the results over the whole period and the average trade differs by less than 20% between the in-sample and out-of-sample period. Let us look at the year by year out-of-sample results (see Table I).

Table I

We have seen that intermarket divergence is a powerful concept. When an intermarket divergence occurs we stay in that position until an opposite divergence occurs. One question is, “Why does this divergence concept work?” Also, what is interesting is that my research shows that the zero crossing is significant, we cannot improve the results of intermarket divergence by using a non-zero threshold. It is my belief that this concept works as an arbitrage play. Since we do not know the relative equilibrium between the traded market and underlying market, for example in the case of Treasury bonds and UTY, divergence is the only confirmed mispricing; we have in terms of a reliable arbitrage play. We know that this cannot be the most efficient signal. We can see by studying our Treasury bond trades that some trades are early; for others we give back large percentage of open profits and sometime large winning trades can become losers, even though intermarket divergence still produces outstanding results.

Here, we have a very profitable trade but we gave back almost all of the profit and then the market moved back in the direction of the trade. This shows a problem with intermarket divergence namely “Reversal Strategy” which is always in the market. There are other cases including (a) a winning trade ending up as a losing one and (b) trades which never become profitable. Despite these issues our results are amazing. One solution to this problem is to build a finite state machine which covers all possible states of the intermarket relationship during the process of going from ‘long to short’ or ‘short to long’. My research has shown that this state map of all possibilities is the key in greatly improving the performance of these simple divergence models. We can also create a state map which will allow us to combine multiple intermarkets against a market we are trading. Correlation and forward correlations analysis between markets can also be used to filter and improve these models. Sometimes correlation analysis can make the long term out-of-sample performance less robust if it is not integrated carefully. Hence, it is important to do the surface analysis discussed earlier to make sure that the correlation relationships we are looking at are robust and stationary.

Conclusion

Intermarket divergence is not something which just works on the bond market. It works on a broad range of markets from bonds, to stock groups, to currencies; even markets like gold, crude, live cattle and copper.

Intermarket analysis is an exciting area of market production. New methodologies of representing these relationships will help not only classic trading system development but also using advance technologies as for example using a finite state model can allow machine learning methods to easily see patterns which can be used to build more reliable models.

Build robust and profitable systems that predict market turning points with this tool.

-- Murray Ruggiero from Using EasyLanguage.

Intermarket Analysis
Made Easy!

For TradeStation and MultiCharts.


Quickly Build ROBUST and PROFITABLE Trading Systems

Free Tool

Murray Ruggiero has also made a free version of Intermarket Divergence Pro which allows you to test and prototype Intermarket strategies. You can download your free copy by joining the EasyLanguage Mastery newsletter.

This article was created based upon the paper, Intermarket Divergence, which was published within Computational Intelligence for Financial Engineering & Economics (CIFEr), 2012 IEEE Conference on March of 2012.

]]>
https://easylanguagemastery.com/building-strategies/intermarket-divergence-robust-method-signal-generation/feed/ 23
A Simple S&P System https://easylanguagemastery.com/strategies/simple-sp-system/?utm_source=rss&utm_medium=rss&utm_campaign=simple-sp-system https://easylanguagemastery.com/strategies/simple-sp-system/#comments Mon, 18 Feb 2019 11:00:30 +0000 http://systemtradersuccess.com/?p=6439

In a past article, Trading Ideas And Systems: Keep It Simple, Smart Guy, highlighted the virtues of building simple trading systems. Simple trading systems have a lot of advantages namely, being robust. In this article I want to provide the EasyLanguage code for the concept provided in the orginal article. It’s a fine example of following the keep-it-simple mantra and just might inspire you to create a profitable system.

Simple S&P Futures System

The first system is based upon the concept provided in last week’s article. The rules are provided below.

System Rules

  • If today’s close is less than the close 6 days ago, buy (enter long).
  • If today’s close is greater than the close 6 days ago, sell (exit long).

Below is a screenshot of the system in action on the daily chart of the E-mini S&P futures contract.

Environmental Settings

I coded the above rules in EasyLanguage and tested it on the E-mini S&P futures market going back to 1998. Before getting into the details of the results let me say this: all the tests within this article are going to use the following assumptions:

  • Starting account size of $25,000
  • Dates tested are from January 1, 2000 through December 31, 2018
  • One contract was traded for each signal
  • The P&L is not accumulated to the starting equity
  • $30 was deducted per round trip for slippage and commissions
  • There are no stops

Baseline Results

Below is the equity curve for trading the E-mini futures contract based upon the rules as defined above. The equity curve looks very similar to the one from the original article. Below the equity curve is the weekly drawdown as a percentage of equity. We can see it reaches down in to the 40% range.

Baseline

Net Profit

$58,895

Profit Factor

1.33

Total Trades

421

%Winners

70.8%

Avg.Trade Net Profit

$139.89

Annual Rate of Return

6.65%

Max Drawdown(intraday)

$37,457

Would anyone really trade this? Of course not, but that’s not the point. The point is simple rules can be rather powerful and be the start of a great system. Can we take this trading concept and take it to a few more steps closer to a real system? Let’s see…

Bull/Bear Regime Filter

You can probably guess this would be my first line of attack. That is, broadly divide the market into two distinct modes: bullish or bearish. Often a simple indicator such as a simple moving average applied to a daily bar chart can be very effective in dividing a market into a bullish or bearish regime. The idea in this case is to only take long trades when we are in a bull market. I will be using a simple moving average to act as my regime filter.

In this case I'm gonig to use a 200-day simple moving average for the bull/bear regime filter. After applying the regime filter we get the following results:

Baseline

Regime Filter

Net Profit

$58,895

$49,957

Profit Factor

1.33

1.52

Total Trades

421

286

%Winners

70.8%

74.1%

Avg.Trade Net Profit

$139.89

$174.68

Annual Rate of Return

6.65%

6.03%

Max Drawdown(intraday)

$37,457

$15,537

So, does this look like an improvement? While we make less money, the system is more effective overall, in my opinion. The profit factor increases as does the average net profit per trade. We also reduce the max drawdown by a lot. I would guess we are eliminating a number of losing trades by only taking trades during a bull market.

Volatility Filter

Another way to divide the market is through volatility. Markets go through periods of rising volatility and falling volatility. In general, market volatility rises and peeks as the market falls and makes new lows. Some systems do well during these high volatility times while others do better during more quiet times. How are we going to measure volatility? We’re going to use the VIX index.  The VIX is a popular measure of the implied volatility of S&P 500 index options and is often called the fear index. In general, the VIX represents a measure of the market’s expectation of volatility over the next 30 days. The VIX has an inverse relationship to the price action on the S&P. Thus, we often see the VIX making new highs as the market is making new lows.

I’m going use the VIX in a very simple manner. I’m going to take the average of the daily VIX value over a number of days to create a simple moving average. Trade will only be opened when the current VIX is below the moving average. This should help the system by only taking trades when the VIX is likely to be falling.

But what value to use for the look-back? Using TradeStation’s optimization feature I’m going to test look-back values between 5 – 60 in increments of 5. The results are depicted in the bar graph below where the net profit is on the y-axis and the look-back period is on the x-axis.

The value 30 looked like a reasonable value to pick. The results of using 30 for the simple moving average for the VIX is below.

Baseline

Regime Filter

Volatility Filter

Net Profit

$58,895

$49,957

$34,427

Profit Factor

1.33

1.52

1.42

Total Trades

421

286

252

%Winners

70.8%

74.1%

59.4%

Avg.Trade Net Profit

$139.89

$174.68

$136.62

Annual Rate of Return

6.65%

6.03%

4.62%

Max Drawdown (intraday)

$37,457

$15,537

$18,560

Like the regime filter we see an improvement in profit factor, and drawdown from the baseline. But when comparied to the Regime Filter, this volatility filter underperforms in my opinion. 

Just for curiosity I performed one more test with VIX. That involved inverting the filter. That is, only take trades when VIX is above its moving average. Below are the results. 

Baseline

Regime Filter

Volatility Filter

Volatility Filter (inverted)

Net Profit

$58,895

$49,957

$34,427

$42,245

Profit Factor

1.33

1.52

1.42

1.29

Total Trades

421

286

252

291

%Winners

70.8%

74.1%

59.4%

72.2%

Avg.Trade Net Profit

$139.89

$174.68

$136.62

$145.17

Annual Rate of Return

6.65%

6.03%

4.62%

5.28

Max Drawdown (intraday)

$37,457

$15,537

$18,560

$26,460

I think the inverted run shows the least improvement against the baseline. It's also clearly not as good when compared to the standard Volatility Filter. What I really don't like is the increased drawdown and reduction in profit factor. More money is made with the inverted volatility filter vs the standard voltaility filter but, at a cost!

Overall, I like the equity curve and performance of the Regime Filter over the VIX Filter. Both represent an improvement over the baseline concept and demonstrate how simple concepts can produce positive results. Added one of the filters to the baseline concept was a “next step” to a potential profitable system. Clearly, more work needs to be done

]]>
https://easylanguagemastery.com/strategies/simple-sp-system/feed/ 10
Two Dimensional Market Environment Filter https://easylanguagemastery.com/building-strategies/two-dimensional-market-environment-filter/?utm_source=rss&utm_medium=rss&utm_campaign=two-dimensional-market-environment-filter https://easylanguagemastery.com/building-strategies/two-dimensional-market-environment-filter/#comments Tue, 25 Dec 2018 11:00:51 +0000 http://systemtradersuccess.com/?p=2567

In this article I’m going to demonstrate a technique to help adapt your trading systems to the changing market conditions. In a previous article entitled, “Trend Testing Indicators“, I tested several indicators that could be used to divide the market into two modes: bullish and bearish. These two modes were then used to dictate how the trading system should execute its trades. For example, during a bull mode only open long trades. During a bear mode only open short trades. In essence, we made our system adapt to the given market conditions. However, we can take this concept further by looking at a different market characteristic: trend strength.

A market may be in a bull regime, but how strong is the trend? Is the market rising fast or is it range bound? We would like to know if the market is trending strong or not because we would like to trade them differently. It’s clear a range bound market that should be traded differently than a trending market. In general you may want to hold an open position longer if the trend is strong. By measuring the strength of the trend we can further divide the market to make our trading system more adaptive. By introducing trend strength we now create four distinct market environments that can be used to determine how an automated system trades.

Four Market Environments

Bull Market

Bear Market

Weak Trend

1

2

Strong Trend

3

4

In this article I’m going to create  a simple strategy that will focus on the market environments one and three. That is, we will look at a weak-trending bull market and a strong-trending bull market.

Trading Environment

Our strategy will be coded in EasyLanguage and tested on the SPY ETF going back to 1993. All the tests within this article are going to use the following assumptions:

  •  Starting account size of  $50,000.
  •  Dates tested are from 2006 through December 31, 2019
  •  1 Contract per trade
  •  The P&L is not accumulated to the starting equity.
  •  There are no deductions for commissions and slippage.
  • No Stops

The Baseline System

For the buy and sell signal I’m going to use the very familiar 2-period RSI Strategy from the book, ”Short Term Trading Strategies That Work”, by Larry Connors and Cesar Alvarez. The system only goes long. There is no shorting. This strategy goes long in the S&P 500 E-mini when the market experiences a pullback in a long-term uptrend. Based on our previous article, “Trend Testing Indicators“, we determined the smoothed ROC indicator which may be an effective market regime filter. So we will use a 200-period ROC calculation to determine if we are within a bull market. The 2-period RSI is used to locate pullbacks (entry points) within our bull market. An RSI value below a 10 will tell our system to open a new long position. We exit the trade when the 2-period RSI rises above 65 . The rules are:

  • 200-Period ROC calculation must be above zero.
  • Buy on close when RSI(2) is below 10.
  • Exit when RSI(2) is above 65.

This system is applied to a daily bar chart going back to 2006.

Looking at the trading rules, you can see that the Baseline System has a market mode filter (the 200-day smoothed ROC) to identify the overall bullishness or bearishness of the market. But we make no distinction between a strong trending bull market and weak trending bull market. If we are in a strong bullish market it makes sense to hold on to our trade in an attempt to capture a bigger move. On the other hand, if we are not in a strong trending market we may want to exit our long position rather quickly. Yet, our Baseline System always sells when a 2-period RSI rises above 65. The exit makes no adjustment for the trendiness of the market.

Introducing Trend Strength

Let’s use Trend Strength Indicator to gauge the trend strength of the market. Trend Strength Indicator (TSI) can be found over at Engineering Returns (no longer around). You can also download the code at the bottom of this article. Let’s also define a strong trend as >= 1.65 and a weak trend as < 1.65. These are not optimized numbers. They are simply a generalization from experience.

Now, let’s modify our exit parameter to hold longer during a strong trend. We’ll exit when a 2-period RSI rises above 95. This should allow us to hold our position longer and capture more profit during a strong trend.

The TSI indicator is provided as a download within the TradeStation ELD and within the Text File found within the download section at the conclusion of the article.

Our new bull market exit rules look like …

  • If TSI >= 1.65 Exit when RSI(2) of the close of current day is above 95

Below is a snapshot of several trades where the market trend changes from non-trending to trending. You can see that during a trending market we are holding the trade longer simply by requiring the RSI(2) value to rise above 95. The trades on the left half of the image are non-trending trades (LE_nt) while the two trades on the right half of the image are trending trades (LE_t).

Let's also change our entry rules based upon the trend strength. If we are experiencing a strong trend we want to make our entry rules a bit looser. That is, we expect pullbacks to be shallower when a market in trending strongly. So, we'll make our 2-period RSI threshold 25 instead of 10. This will allow us to enter shallower pullbacks during a strong trending market.

Now let’s take a look at the performance of this strategy.

1S VS 2D Filter

1D Filter

2D Filter

Net Profit

$10,575

$32,513

Profit Factor

1.19

1.60

Total Trades

111

88

%Winners

74%

72%

Avg.Trade Net Profit

$95

$369

Consective Losers

3

3

Annual Rate of Return

1.45%

3.79%

Net Profit / Drawdown

0.59

1.66

By introducing a simple trend strength indicator and making our strategy adapt to the trend strength, we generate more net profit and more profit per trade. We do decrease the number of trades as well. This is a good improvement and it demonstrates that we are on the right track by holding our position longer during a strong trend.

What if we simple hold all our traders (strong trend or not ) with our strong trend exit method?

1D Filter

2D Filter

Always 

Net Profit

$10,575

$32,513

Enter your text here...

Profit Factor

1.19

1.60

Cell

Total Trades

111

88

Cell

%Winners

74%

72%

Cell

Avg.Trade Net Profit

$95

$369

Cell

Consective Losers

3

3

Cell

Annual Rate of Return

1.45%

3.79%

Cell

Net Profit / Drawdown

0.59

1.66

Cell

Conclusion

There you have it. A strategy that adapts to several different market conditions. I did not cover the bear market regime, but you’re certainly free to explore that. Likewise, you can expand this concept to create a strategy that more drastically changes its trading behavior based on which of the four market environments we defined. Maybe during a strongly trending bull market you will want to use a completely different exit method than used during a non-trending market. In closing, this should provide some idea on how you can use two different types of indicators to divide the market into four different market environments.

]]>
https://easylanguagemastery.com/building-strategies/two-dimensional-market-environment-filter/feed/ 16