Market Studies – Helping you Master EasyLanguage https://easylanguagemastery.com Helping you Master EasyLanguage Wed, 14 May 2025 14:21:19 +0000 en-US hourly 1 https://wordpress.org/?v=7.0.1 https://easylanguagemastery.com/wp-content/uploads/2019/02/cropped-logo_size_icon_invert.jpg Market Studies – Helping you Master EasyLanguage https://easylanguagemastery.com 32 32 The S&P Overnight Edge (Update for 2025) https://easylanguagemastery.com/getting-started/the-sp-overnight-edge-update-for-2025/?utm_source=rss&utm_medium=rss&utm_campaign=the-sp-overnight-edge-update-for-2025 https://easylanguagemastery.com/getting-started/the-sp-overnight-edge-update-for-2025/#respond Wed, 14 May 2025 13:13:12 +0000 https://easylanguagemastery.com/?p=535653 The overnight trading action of the S&P has a decisive edge. Did you know that a lot of the gain of the S&P happens at night? This provides a unique opportunity to build a trading system. 

But is that edge still holding up?

The overnight edge of the S&P is something I’ve written about before. If you’re not familiar with it, you can check out the article, “The Overnight Edge.”

Here’s a quick refresher.

I put together a trading system to test the overnight edge by buying at the current close and closing out the trade at the next day’s open. So, our trade is in play during the overnight session. On the flip side, I’ve also tested holding a trade only during the day by buying at the open and selling at the close. If you want to dive deeper into the details, just head over to the article I mentioned earlier.

S&P Points During Overnight Since 2020

What I want to focus on is what has it been doing recently. So, let’s take a look at the results since 2020.

  • January 1, 2020 to May 14, 2025
  • No slippage or commission cost deducted.
  • The symbol used was @ES.D.

So, let’s dive in and see what kind of action we can find during the day session. It’s always exciting to explore new possibilities and see if we can uncover some profitable patterns. Worst case scenario, we learn a thing or two along the way, right?

S&P Points Gained During Day Since 2020

In contrast to the Overnight equity curve we can see new equity highs being made here. Thus, it looks like S&P gains are happening more often during the day session.Let’s put the results in a table to better compare. 

Holding Overnight

Holding During Day

Net Profit

$44,562

$53,037

Profit Factor

1.08

1.07

Total Trades

1147

1147

Avg.Trade Net Profit

$38.85

$46.24

Max Drawdown

$50,250

$45,325

NP vs. DD

0.9

1.1

Let’s add a 200-bar simple moving average to act as a regime filter. We’ll take long trades only when price is above the 200-bar simple moving average. 

Holding Overnight

Holding During Day

Overnight W/Regime

Holding Day W/Regime

Net Profit

$44,562

$53,037

$72,850

$7,087

Profit Factor

1.08

1.07

1.22

1.01

Total Trades

1147

1147

850

850

Avg.Trade Net Profit

$38.85

$46.24

$85.71

$8.34

Max Drawdown

$50,250

$45,325

$33,313

$34,412

NP vs. DD

0.9

1.1

2.2

0.2

Adding the regime filter did help the Night Session but it hurt the Day Session. Interesting! For the Day session we reduce the average profit per trade and the total net profit. On the other hand, with the night session we see nice improvements with the metrics.

Trading during the night session when the S&P is in a bull phase, looks promising. However, trading during the day does not look so hot. In short, this may suggest that the edge is in holding during the over night session.

Below is the equity curve of of taking long trades during the Night Session when the S&P is in bull phase.

What About Shorting?

With a little research I was able to test the optimal shorting is shorting the Day Session during Bear Markets (Below 200-day simple moving average).Below is a table containing the best shorting setup and the best long setup.

Short Day Session During Bear Markets

Long Night Session During Bull Markets

Net Profit

$28,288

$72,850

Profit Factor

1.13

1.22

Total Trades

297

850

Avg.Trade Net Profit

$95.24

$85.71

Max Drawdown

$20,250

$33,313

NP vs. DD

1.4

2.2

What Can I Do With This Info?

The above strategies  are not trading systems. They are market studies to help point us in the right direction. They’re more like our trusty market compasses, pointing us in the right direction and giving us some clues about where we might want to focus our trading system-building efforts.The data is clear: since 2020, the S&P gains have tilted toward the day session, but only on the surface. Once we factor in market regime using a 200-bar simple moving average, the overnight session during bull markets becomes the standout performer—yielding a 2.2 Net Profit to Drawdown ratio and over $72K in net profits. That’s a dramatic improvement over the raw overnight edge or day trading alone.On the flip side, the best shorting opportunity appears in the day session during bear markets. This regime-aware approach reveals that profitable edges in the S&P aren’t just about time of day—they’re about context. The market environment (bull vs. bear) plays a critical role in whether the edge appears or vanishes.So what does this mean for the average retail algo trader?

  1. Divide and Conquer Your Strategy Design. Build separate systems for long and short trades—don’t lump them together. Focus your long entries on the overnight session during bull markets, and your short entries on the day session during bear markets. This alone can eliminate a ton of noise and increase strategy robustness.
  2. Use Market Regime as a Gatekeeper. A simple 200-bar moving average filter turned a mediocre strategy into a high-performing one. This is a powerful reminder: market regime filtering is not optional—it’s essential. It sharpens the edge and smooths the equity curve.
  3. Reconsider When You Trade. Most retail traders default to day session strategies because that’s when markets are “active.” But this study shows that some of the most profitable, lowest-drawdown opportunities exist when you’re asleep. A VPS and automated execution can help you capitalize on this overlooked edge.
  4. Non-Obvious Opportunity: Portfolio Timing Allocation. If you’re building a portfolio of systems, you might consider **segmenting exposure based on session and regime**, rather than spreading capital evenly. For instance, overweight your portfolio toward the long overnight strategy when in a bull market, and shift exposure to short day strategies during bear markets. This dynamic capital allocation could significantly enhance returns and reduce drawdowns.

The takeaway? Don’t just build “an S&P strategy.” That’s too vague. Build for session and regime. You’ll uncover edges others ignore—and in a market as competitive as the S&P, that might make all the difference.

]]>
https://easylanguagemastery.com/getting-started/the-sp-overnight-edge-update-for-2025/feed/ 0
Is The Christmas Season Bullish For U.S. Markets? https://easylanguagemastery.com/market-studies/christmas-trade/?utm_source=rss&utm_medium=rss&utm_campaign=christmas-trade https://easylanguagemastery.com/market-studies/christmas-trade/#comments Mon, 16 Dec 2024 11:00:00 +0000 http://systemtradersuccess.com/?p=2821

With the Christmas season upon us, I thought it would be interesting to review how the S&P behaves in the days just before Christmas. Do the days just before this holiday tend to be bullish, bearish, or neutral?

To test the market behavior just before the Christmas holiday I will use the S&P Cash index back in 1960. I will create an EasyLanguage strategy that will enter a trade X days before Christmas and close that trade on the opening of the first trading day after Christmas. Each trade will dedicate $100,000 to purchase shares. Stops, and both commissions and slippage are not utilized in this study.

Ten Days Before Christmas

First let's look at the 10 days before Christmas. What happens if we enter a trade X days before Christmas and close that trade on the open after Christmas? By using TradeStation's optimize feature I can systematically test each day over the historical data. The results of each test is the generated P&L for each iteration and is depicted in the bar graph below. Looking at the graph, each bar on the x-axis represents the number of days before Christmas.

It appears that the 10 days before Christmas all show positive P&L. In general, the longer you're holding period before Christmas the better.

Ten Days After Christmas

Using a similar trading system, I will look at entering a trade on open of trading day following Christmas and holding that trade for X days. Below is a bar graph showing the days 1-10 after Christmas. Again, each bar represents P&L and the x-axis is the number of days the trade is held.

Historically, all days after Christmas in our study have returned positive results. Unlike the 10 days before Christmas, in this case it appears there is not much gain for holding beyond five days.

The Christmas Trade

Based on the information above, which seems to show a strong bullish biased for the days immediately before and after Christmas, I'm going to create another strategy that will open a trade five days before Christmas and closes that trade five days after Christmas. I picked five days simply because it was the middle value (1-10) for the days before and after Christmas we tested. Last year's Christmas Trade (December 2022) was a losing trade. It's pictured below.

Christmas Trade 2023

Christmas Trade 2023

When you combine all the trades going back to 1960 we get the following equity curve and performance, below. The last equity peek was in 2021.

Christmas Trade Equity Curve

Conclusion

There certainly does seem to be a very strong bullish tendency around Christmas. The most recent action looks a little more flat. However, we did have a new equity high in 2021.

Can you take advantage of this in your trading? Perhaps. Remember, the code with this article is not a complete trading system, but an indicator to help me gauge the market behavior around the Christmas holiday. If you have trading systems or trade a discretionary method around these days before and after Christmas, you might use this knowledge to ignore short signals, or modify your exit based upon what we learned. 

]]>
https://easylanguagemastery.com/market-studies/christmas-trade/feed/ 5
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
A Cool And Easy Way To Analyze Chart Patterns With TradeStation https://easylanguagemastery.com/market-studies/a-cool-and-easy-way-to-analyze-chart-patterns-with-tradestation/?utm_source=rss&utm_medium=rss&utm_campaign=a-cool-and-easy-way-to-analyze-chart-patterns-with-tradestation https://easylanguagemastery.com/market-studies/a-cool-and-easy-way-to-analyze-chart-patterns-with-tradestation/#respond Mon, 17 Jun 2024 10:00:15 +0000 http://easylanguagemastery.com/?p=20789

Have you every tested different combinations of closing or opening relationships to uncover the following days probability of either closing up or down.  I am sure you have tested selling after two down closes or just the opposite:  buying after two up closes.  Testing the relationship between two days is easy but when you go beyond just two then the programming can become very difficult.

The inefficient way:


if c > c[1] and c[1] > c[2] and c[2] > c[3] then
buy somewhere tomorrow

What if you wanted to test different combination of up/down closes then you would need to go into the code and make the changes like...


if c < c[1] and c[1] > c[2] and c[2] > c[3] then
buy somewhere tomorrow

you would then need to verify, run and keep track of results. This is really a pain. I have come up with an easy way to accomplish looking at many patterns and letting the computer keep track of the results.

What you need is a simple and dynamic way to change the patterns based on each individual run. We know we can use TradeStation’s optimizer to create multiple runs. Now all we need is a way for TradeStation, based on the run number, to change the pattern or pattern number.

The following code does this:

value1 = patternTests - 1;

if(value1 > 0) then
begin

if(mod(value1,2) = 1) then patternBitChanger[0] = 1;
value2 = value1 - patternBitChanger[0] * 1;

if(value2 >= 8) then begin
patternBitChanger[3] = 1;
value2 = value2 - 8;
end;

if(value2 >= 4) then begin
patternBitChanger[2] = 1;
value2 = value2 - 4;
end;
if(value2 = 2) then patternBitChanger[1] = 1;
end;

Do you remember binary based systems where 0 – off and 1 – on? If you don’t remember its OK. Here is a quick review for everyone.

0 0 0 0 pattern = 0
0 0 0 1 pattern = 1
0 0 1 0 pattern = 2
0 1 0 0 pattern = 4
1 0 0 0 pattern = 8

Each 1 or 0 is a placeholder and its placeholder is a bit than can either be on or off. The leftmost bit is 1’s place. The next bit is the 2’s place. The next bit is the 4’s place. And finally the rightmost bit is the 8’s place. So if we plug in 1 1 1 1 we get (8 + 4 + 2 + 1) = 15. If we start counting at 0 [ 0 0 0 0 ] then we can represent 16 distinct patterns with our four bits. Following?

So using this bit scheme and TradeStation’s optimizer we can run 16 different patterns sequentially. Now how do we get the bit pattern scheme to relate to the last four day’s close to close relationships. This is where the eloquence continues [if I have to say so myself]. EasyLanguage has a library of powerful string functions. One of those is the ability to concatenate or add a string to a string.

Let’s pretend we are the computer and we are optimizing thru 16 different runs. Let’s call the first run [0 run]. In our tests 1’s will be represented by “+” and 0’s by “-“. Using our 4 bit scheme how to we represent the number 0? Zero means no bits are on so 0 = [0 0 0 0]. If we translate our bits to a string where 1’s are “+” and 0’s are “-” then we get “- – – -“]. Right? If a “+” represents an up close and “-” represents a down close then the string “- – – -” would indicate four straight down closes.

Run 0 = 0 0 0 0 = ” – – – – ” – four straight closes down
Run 1 = 0 0 0 1 = ” – – – + ” – three straight closes down followed by 1 up close
Run 2 = 0 0 1 0 = ” – – + – ” – two straight closes down, one up close, one down close
Run 3 = 0 0 1 1 = ” – – + + ” – two straight closes down, two straight closes up



Run 15= 1 1 1 1 = ” + + + + ” – four straight closes up

Following this scheme we can easily check out 16 different 4 day patterns. Let’s see what pattern is the most prolific on the long side. What do you guess – maybe after 4 consecutive down closes?

Simply buying the next bar’s open and exiting two days later, let’s see which pattern is king. Here is the pattern and its profit/loss:

Pattern

Binary Pattern

P&L

Pattern String

0

0000

$12,187

– – – – 

1

0001

$14,150

– – – + 

2

0010

$7,687

– – +–

3

0011

$5,425

– – + + 

4

0100

$2,412

– + – –

5

0101

$6,887

- + - +

6

0110

$7,500

– + + –

7

0111

$9,762

– + + +

8

1000

$13,850

+ – – – 

9

1001

$10,225

+ – – +

10

1010

-$12.0

+ – + –

11

1011

$7,700

+ – + +

12

1 1 0 0

$11,025

+ + – –

13

1101

$4,975

+ + – +

14

1110

-$1,312

+ + + –

15

1111

-$1,000

+ + + + 

Well it seems they were mostly winners but you shouldn’t buy after ” + + + + “ or "+ + + -". Pattern ” – – – +” was the best followed by ” + – – – “.

Oh yeah this was tested in the ES over the past five years so we are probably witnessing a bullish bias. Let’s see if we sell using the same patterns.

Pattern

Binary Pattern

P&L

Pattern String

0

0000

-$12,187.5

– – – – 

1

0001

-$14,150

– – – + 

2

0010

$7,687

– – +–

3

0011

-$5,425

– – + + 

4

0100

-$2,412

– + – –

5

0101

$6,887

- + - +

6

0110

-$7,500

– + + –

7

0111

-$9,762

– + + +

8

1000

-$13,850

+ – – – 

9

1001

-$10,225

+ – – +

10

1010

$12

+ – + –

11

1011

-$7,700

+ – + +

12

1 1 0 0

-$11,025

+ + – –

13

1101

-$4,975

+ + – +

14

1110

$1,312

+ + + –

15

1111

$1,000

+ + + + 

Well the bullish bias is definitely evident. The best 4 day pattern to sell the next bar is to wait for 4 consecutive up closes or 3 consecutive up closes followed by 1 down close.

Is there anything to this pattern recognition? I think it can be used to filter trades and that’s about it. We tested a four day pattern for illustration purposes only but that might be too many. A two day pattern might work better. Please check this out and let me know.

Here is the program in its entirety:

input: patternTests(14),orbAmount(0.20),LorS(1),holdDays(0),atrAvgLen(10);

var: patternTest(""),patternString(""),tempString("");
var: iCnt(0),jCnt(0);
array: patternBitChanger[4](0);

{written by George Pruitt -- copyright 2006 by George Pruitt
This will test a 4 day pattern based on the open to close
relationship. A plus represents a close greater than its
open, whereas a minus represents a close less than its open.
The default pattern is set to pattern 14 +++- (1110 binary).
You can optimize the different patterns by optimizing the
patternTests input from 1 to 16 and the orbAmount from .01 to
whatever you like. Same goes for the hold days, but in this
case you optimize start at zero. The LorS input can be
optimized from 1 to 2 with 1 being buy and 2 being sellshort.}

patternString = "";
patternTest = "";

patternBitChanger[0] = 0;
patternBitChanger[1] = 0;
patternBitChanger[2] = 0;
patternBitChanger[3] = 0;

value1 = patternTests - 1;

if(value1 > 0) then
begin

if(mod(value1,2) = 1) then patternBitChanger[0] = 1;
value2 = value1 - patternBitChanger[0] * 1;

if(value2 >= 8) then begin
patternBitChanger[3] = 1;
value2 = value2 - 8;
end;

if(value2 >= 4) then begin
patternBitChanger[2] = 1;
value2 = value2 - 4;
end;
if(value2 = 2) then patternBitChanger[1] = 1;
end;

patternString = "";

for iCnt = 3 downto 0 begin
if(patternBitChanger[iCnt] = 1) then
begin
patternTest = patternTest + "+";
end
else
begin
patternTest = patternTest + "-";
end;
end;

for iCnt = 3 downto 0
begin
if(close[iCnt]> close[iCnt+1]) then
begin
patternString = patternString + "+";
end
else
begin
patternString = patternString + "-";

end;
end;

if(barNumber = 1) then print(elDateToString(date)," pattern ",patternTest," ",patternTests-1);
if(patternString = patternTest) then begin

// print(date," ",patternString," ",patternTest); //uncomment this and you can print out the pattern
// if(LorS = 2) then SellShort("PatternSell") next bar at open of tomorrow - avgTrueRange(atrAvgLen) * orbAmount stop;
// if(LorS = 1) then buy("PatternBuy") next bar at open of tomorrow + avgTrueRange(atrAvgLen) * orbAmount stop;

if(LorS = 2) then SellShort("PatternSell") next bar at open;
if(LorS = 1) then buy("PatternBuy") next bar at open;

end;

if(holdDays = 0 ) then setExitonClose;
if(holdDays > 0) then
begin
if(barsSinceEntry = holdDays and LorS = 2) then BuyToCover("xbarLExit") next bar at open;
if(barsSinceEntry = holdDays and LorS = 1) then Sell("xbarSExit") next bar at open;
end;

-- George Pruitt from GeorgePruitt.com.

Update by Jeff Swanson 

While the code is available here in the article, Join our weekly newsletter (see below) to get an example TradeStation WorkSpace and the source code as an ELD.

]]>
https://easylanguagemastery.com/market-studies/a-cool-and-easy-way-to-analyze-chart-patterns-with-tradestation/feed/ 0
How To Test And Optimize Turn Of The Month Seasonality https://easylanguagemastery.com/market-studies/how-to-test-and-optimize-turn-of-the-month-seasonality/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-test-and-optimize-turn-of-the-month-seasonality https://easylanguagemastery.com/market-studies/how-to-test-and-optimize-turn-of-the-month-seasonality/#respond Mon, 08 Apr 2024 10:00:00 +0000 https://easylanguagemastery.com/?p=533920

Historical evidence suggests a potential seasonal pattern around the end of the month in the markets.

If you have been involved with the markets for even a short period of time, you have heard about this trade.  Buy N days prior to the end of the month and then exit M days after the end of the month.  This is a simple test to perform if you have a way to determine the N and the M in the algorithm.  You could always buy on the 24th of the month, but the 24th of the month may not equal N days prior to the end of the month. 

Simple approach that doesn’t always work – buy the 24th of the month and exit the 5th of the following month.

if dayOfMonth(d) = 24 then buy next bar at open;

if marketPosition = 1 and dayOfMonth(d) = 5 then sell next bar at open;

If you have been involved with the markets for even a short period of time, you have heard about this trade. Buy N days prior to the end of the month and then exit M days after the end of the month. This is a simple test to perform if you have a way to determine the N and the M in the algorithm. You could always buy on the 24th of the month, but the 24th of the month may not equal N days prior to the end of the month.

Simple approach that doesn’t always work – buy the 24th of the month and exit the 5th of the following month.

if dayOfMonth(d) = 24 then buy next bar at open;

if marketPosition = 1 and dayOfMonth(d) = 5 then sell next bar at open;

Before we get into a little better coding of this algorithm, let’s see the numbers. The first graph is trading one contract of the ES futures once a month – no execution fees were applied. The same goes for the US bond futures chart that follows. Before reading further please read this.

CFTC-required risk disclosure for hypothetical results:

Hypothetical performance results have many inherent limitations, some of which are described below. No representation is being made that any account will or is likely to achieve profits or losses similar to those shown. in fact, there are frequently sharp differences between hypothetical performance results and the actual results subsequently achieved by any particular trading program.

One of the limitations of hypothetical performance results is that they are generally prepared with the benefit of hindsight. In addition, hypothetical trading does not involve financial risk, and no hypothetical trading record can completely account for the impact of financial risk in actual trading. For example, the ability to withstand losses or to adhere to a particular trading program in spite of trading losses are material points which can also adversely affect actual trading results. There are numerous other factors related to the markets in general or to the implementation of any specific trading program which cannot be fully accounted for in the preparation of hypothetical performance results and all of which can adversely affect actual trading results.

Buying N days before EOM and Selling M days after EOM
Ditto!

No Pain No Gain
Looking into the maw of draw down and seeing the jagged and long teeth.

Draw down as a percentage of account value.

Detto!

The bonds had more frequent draw down but not so deep. These teeth can cause a lot of pain.

Well, George what is the N and M?
I should have done M days before and N days after to maintain alphabetic order, but here you go.

ES: N = 6 AND M = 6

US: N =10 AND M = 1

How did you do this?
Some testing platforms have built-in seasonality tools, but, and I could be wrong I didn’t find what I needed in the TradeStation function library. So, I built my own.

A TradingDaysLeftInMonth function had to be created. This function is a broad swipe at attempting to determining this value. It’s not very smart because it doesn’t take HOLIDAYS into consideration. But for a quick analysis it is fine. How does one design such a function? First off, what do we know to help provide information that might be useful? We know how many days are in each month (again this function isn’t smart enough to take into consideration leap years) and we know what day of the week each trading day belongs to. We have this function DayOfWeek(Date) already in EasyLanguage. And we know the DayOfMonth(Date) (built-in too!) With these three tidbits of information, we should be able to come up with a useful function. Not to mention a little programming knowledge. I was working on a Python project when I was thinking of this function, so I decided to prototype it there. No worries, the algorithm can be easily translated to EasyLanguage. And yes, I could have used my concept of a Sandbox to prototype in EasyLanguage as well. Remember a sandbox is a playground where you can quickly test a snippet of code. Using the ONCE keyword, you can quickly throw some generic EasyLanguage together sans trade directives and mate it to a chart and get to the nuts and bolts quickly. I personally like having an indicator and a strategy sandbox. Here is a generic snippet of code where we assume the day of month is the 16th and it is a Monday ( 2 – 1 for Sunday thru 7 for Saturday) and there are 31 days in whatever month.

currentDayOfWeek = 2;
currentDayOfMonth = 16;
loopDOW = currentDayOfWeek;
daysInMonth = 31
#create the calender for the remaining month
tdToEOM=0; #total days to EOM
for j in range(currentDayOfMonth,daysInMonth+1):
if loopDOW != 1 and loopDOW != 7:
tdToEOM +=1;
print(j," ",loopDOW," ",tdToEOM)
loopDOW +=1;
if loopDOW > 7: loopDOW = 1; #start back on Monday

Create a synthetic calendar from the current day of month

I just absolutely love the simplicity of Python.  When I am prototyping for EasyLanguage, I put a semicolon at the end of each line.  Python doesn’t care.  Here is the output from this snippet of code.

Cur>Day DOWDay DaysLeftAccum.
-----------------------------------
16        2    1 Monday
17        3    2 Tuesday
18        4    3 Wednesday
19        5    4 Thursday
20        6    5 Friday
21        7    5 Saturday
22        1    5 Sunday
23        2    6 Monday
24        3    7 Tuesday
25        4    8 Wednesday
26        5    9 Thursday
27        6    10 Friday
28        7    10 Saturday
28        1    10 Sunday
30        2    11 Monday
31        3    12 Tuesday
On Monday 16th there were 12 Trading Days Left In Month Inclusive

Output of Python Snippet - use in EZLang.

I start out with the current day of the month, 16 and loop through the rest of the days of the month. Whenever I encounter a Sunday (1) or a Saturday (7) I do not increment tdToEOM, else I do increment.

Here is how the function works on a chart. Remember in TradeStation I am placing a market order for the NEXT BAR.

Counting the days until the EOM

This snippet of code is the heart of the function, but you must make in generic for any day of any month. Here it is in EasyLanguage – you will see the similarity between the Python snippet and its corresponding EasyLanguage.

array: monthDays[12](0);

monthDays[1] = 31;
monthDays[2] = 28;
monthDays[3] = 31;
monthDays[4] = 30;
monthDays[5] = 31;
monthDays[6] = 30;
monthDays[7] = 31;
monthDays[8] = 31;
monthDays[9] = 30;
monthDays[10] = 31;
monthDays[11] = 30;
monthDays[12] = 31;

vars: curDayOfMonth(0),curDayOfWeek(0),loopDOW(0),tdToEOM(0),j(0);

curDayOfWeek = dayOfWeek(d);
curDayOfMonth = dayOfMonth(d);

{Python prototype
tdToEOM=0;
for j in range(currentDayOfMonth,daysInMonth+1):
if loopDOW != 1 and loopDOW != 7:
tdToEOM +=1;
print(j," ",loopDOW," ",tdToEOM)
loopDOW +=1;
if loopDOW > 7: loopDOW = 1;
}

loopDOW = curDayOfWeek+1;
tdToEOM=0;

for j = curDayOfMonth to monthDays[month(d)]
begin
if loopDOW <> 1 and loopDOW <> 7 then
tdToEOM +=1; // tdToEOM = tdToEOM + 1;
loopDOW +=1;
if loopDOW > 7 then loopDOW = 1;
end;
TradingDaysLeftInMonth = tdToEOM;

EasyLanguage Function : TradingDaysLeftInMonth

I used arrays to store the number of days in each month. You might find a better method. Once I get the day of the month and the day of the week I get to work. EasyLanguage uses a 0 for Sunday so to be compliant with the Python function I add a 1 to it. I then loop from the current day of month through monthDays[month(d)]. Remember month(d) returns the month number [1…12]. A perfect index into my array. That is all there is to it. The code is simple, but the concept requires a little thinking. Okay, now that we have the tools for data mining, let’s do some. I did this by creating the following strategy (the same strategy that create the original equity curves.)

inputs: numDaysBeforeEOM(8),numDaysAfterEOM(10),movingAvgLen(100);
inputs: stopLossAmount(1500),profitTargetAmount(4000);

vars: TDLM(0),TDIM(0);

TDLM = tradingDaysLeftInMonth;
TDIM = tradingDayOfMonth;

if c >= average(c,movingAvgLen) and TDLM = numDaysBeforeEOM then
begin
buy("Buy B4 EOM") next bar at open;
end;

if marketPosition = 1 and barsSinceEntry > 3 then
begin
if TDIM = numDaysAfterEOM then
begin
sell("Sell TDOM") next bar at open;
end;
end;
setStopLoss(stopLossAmount);
setProfitTarget(profitTargetAmount);

EasyLanguage function driver in form of Strategy

A complete strategy has trade management and an entry and an exit. In this case, I added an additional feature – a trend detector in the form of a longer-term moving average. Let’s see if we can improve the trading system. Thank goodness for Genetic Optimization. Here is the @ES market.

Get your Pick ready to mine!

Smoothed the equity curve – took the big draw down out.

Genetically MODIFIED – Data Mining at its best!

Here are the parameters:

Did not like the moving average. Wide stop and wide profit objective. Days to EOM and after EOM stayed the same.

Bond System:

Bond market results.

If you like this type of programming check out my books at Amazon.com. I have books on Python and of course EasyLanguage. I quickly assembled a YouTube video discussing this post here.

Conclusion – there is something here, no doubt. But it can be a risky proposition. It definitely could provide fodder for the basis of a more complete trading system.


>> By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/market-studies/how-to-test-and-optimize-turn-of-the-month-seasonality/feed/ 0
Unlock the Power of the Money Flow Indicator https://easylanguagemastery.com/market-studies/unlock-the-power-of-the-money-flow-indicator/?utm_source=rss&utm_medium=rss&utm_campaign=unlock-the-power-of-the-money-flow-indicator https://easylanguagemastery.com/market-studies/unlock-the-power-of-the-money-flow-indicator/#comments Mon, 10 Apr 2023 10:00:25 +0000 https://easylanguagemastery.com/?p=532318

The Money Flow Indicator is a technical analysis tool used in trading that is available on the TradeStation platform. It's a momentum oscillator that compares negative and positive money flow values to create an output ratio between 0 and 100. The MFI is calculated using a formula considering price and volume data. 

Money Flow is a way to measure whether people are buying or selling a stock, or other investment. It looks at the investment's price and how much was purchased (volume) or sold in a certain period. If the price increases, the Money Flow is considered positive. But if the price goes down, the Money Flow is considered negative. 

Using both price and volume provides a different perspective from price or volume alone. The Money Flow indicator shows dramatic oscillations and can help identify overbought and oversold conditions.

How is It Calculated?

Money Flow is a technical indicator used in trading to measure the strength of buying or selling pressure in a security. 

Money flow uses the average price, derived from the high, low, and closing prices divided by three. This is also known as the typical price (TP).

TP = ( High + Low + Close )

Positive Money Flow (PMF) is calculated and summed for each of the last X number of bars with an average price greater than the previous bar and then divided by the Money Flow for all the bars specified in Length. 

if ( TP > TP[1] ) then
   MyMFSum = MyMFSum + ( TP * Volume )
AllMFSum = AllMFSum + ( TP * Volume )

Suppose the typical price of the current period is higher than that of the previous period. In that case, the resulting Money Flow value is considered positive and added to a sum (MyMFSum).

Conversely, suppose the typical price of the current period is lower than that of the previous period. In that case, the resulting Money Flow value is considered negative. In this case, the value is not added to the MyMFSum.

In other words, Money Flow compares the current period's typical price to the previous period's typical price to determine whether money flows into or out of the security has increased or decreased.

Building the Ratio

Once we have the sum of all the positive money flow values (MyMFSum), we create a ratio using the sum of all money flows in the denominator.

Money Flow Indicator = MyMFSum / AllMFSum * 100

So if we use the money flow index with a 10-period setting, we'll first get the sum of all positive money flow values for the past 10 days and divide it by the sum of all money flow values for the past 10 days.

Traders can use Money Flow with other technical indicators and analysis tools to identify potential trading opportunities and confirm price trends. By monitoring changes in the Money Flow, traders can gain insight into the sentiment of other market participants and adjust their strategies accordingly.

Using Money Flow to Generate Trading Signals

Traditionally, you can use Money Flow values above 80 and below 20 as a trigger.

For example, if the Money Flow falls below 80, you may take this as a short signal. If the Money Flow rises below 20, you may take this as a long signal. See the image below.

But this is one interpretation. Here is another way to think about it. Go long when the Money Flow rises above 80 and short when it falls below 20. See the image below.

However, these are not all possibilities. If you think about it, you can have various combinations of entry signals based on the upper and lower thresholds of the Money Flow Indicator. We could also introduce a midpoint value (50) that can act as a trigger.

For long trades, we could...

  • buy entering the overbought region
  • buy leaving the overbought region
  • buy crossing above the midpoint (50)

I would classify these signals as momentum trades. The Money Flow is at the higher end of its range, and we're going long. 

On the other hand, we could fade these values. 

  • buy entering the oversold region
  • buy leaving the oversold region
  • buy crossing below Midline (5)

How do we know which triggers to test? The answer is we don't. Thus we code up all of these into a switch statement using EasyLanguage. We then use TradeStation's optimization features to iterate over different buy/sell signal combinations to see which produces better performance.

The Money Flow Strategy

Below is the testing strategy to determine which buy/sell signals work best.

Input:
iBuyType(1),
iSellType(1),
iLookback(10);

vars:
MyMoneyFlow(0),
Oversold(20),
Midline(50),
Overbought(80);

MyMoneyFlow = MoneyFlow( iLookback );

Switch( iBuyType )
Begin
Case 1:
   if MyMoneyFlow Crosses above Overbought then buy next bar at market;
Case 2:
   if MyMoneyFlow Crosses below Overbought then buy next bar at market;
Case 3:
   if MyMoneyFlow Crosses above Midline then buy next bar at market;
Case 4:
   if MyMoneyFlow Crosses below OverSold then buy next bar at market;
Case 5:
   if MyMoneyFlow Crosses above OverSold then buy next bar at market;
Case 6:
   if MyMoneyFlow Crosses below Midline then buy next bar at market;
Default:
   Print("Invalid iBuyType Value");
End;

Switch( iSellType )
Begin
Case 1:
   if MyMoneyFlow Crosses above Overbought then Sellshort next bar at market;
Case 2:
   if MyMoneyFlow Crosses below Overbought then Sellshort next bar at market;
Case 3:
   if MyMoneyFlow Crosses above Midline then Sellshort next bar at market;
Case 4:
   if MyMoneyFlow Crosses below OverSold then Sellshort next bar at market;
Case 5:
   if MyMoneyFlow Crosses above OverSold then Sellshort next bar at market;
Case 6:
   if MyMoneyFlow Crosses below Midline then Sellshort next bar at market;
Default:
   Print("Invalid iSellType Value");
End;

The EasyLanguage code and TradeStation WorkSpace are available for you to download once you become an EasyLanguage Mastery Insider! It's free and you get access to all our code. See the bottom of this article for details.

Testing Environment

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

  • Starting account size of $100,000
  • In-sample dates are from 2006 through December 2020
  • Commissions & Slippage were not deducted
  • One contract was traded per signal
  • Overbought Threshold 80
  • Oversold Threshold 20
  • Midline Threshold 50

Testing Money Flow Heating Oil

I can now load my testing strategy onto a daily Heating Oil (@HO) chart and test it. I will optimize to input values. First, the Buy Type with values between 1-6. Next, the Sell Type with values 1-6. This will produce 36 different tests.

I organized the performance results by Perfect Profit Correlation, which measures the straightness of the equity curve. The best-performing settings for Heating Oil were Buy Type 6 and Sell Type 4.

Looking at the code for these input values...

  • Go long when the Money Flow crosses below the Midline.
  • Go short when the Money Flow crosses below the oversold region.

Here is an image of the Money Flow signals on the Heating Oil chart.

Below are the equity curve and performance report.

Nice! We found a potential starting point for a viable trading system. TradeStation recently released a micro contract for Heating Oil. Trading a daily system based around Money Flow may work.

Summary

In this article, I've explored the Money Flow Indicator, a technical analysis tool used in trading to measure the strength of buying or selling pressure in a security. Considering price and volume data, the Money Flow Indicator can help identify overbought and oversold conditions, providing traders with valuable insights into market sentiment. I've developed a testing strategy with various entry and exit triggers based on the Money Flow Indicator and tested it on the Heating Oil futures contract.

Conclusion

The testing strategy I've presented demonstrates that the Money Flow Indicator can effectively generate trading signals. By optimizing input values and examining various buy/sell signal combinations, traders can find the best-performing settings for their specific market. In the case of Heating Oil, going long when the Money Flow crosses below the Midline and going short when it crosses below the oversold region produced the best results.

Note this strategy is a testing strategy, not a complete trading system! The strategy is not for live trading but for helping you locate the best entry and exit triggers on the Money Flow Indicator. If you want to learn more about building trading systems, check out the article, How to Build Profitable Trading Systems.

To make this a complete strategy, you would need to add a stop value, test different filters, and then put the strategy through a validation process. 

Please join EasyLanguage Mastery Insider to download this article's EasyLanguage code and TradeStation WorkSpace.

]]>
https://easylanguagemastery.com/market-studies/unlock-the-power-of-the-money-flow-indicator/feed/ 2
Using Gap Zones To Improve The Overnight Edge https://easylanguagemastery.com/market-studies/using-gap-zones-to-improve-the-overnight-edge/?utm_source=rss&utm_medium=rss&utm_campaign=using-gap-zones-to-improve-the-overnight-edge https://easylanguagemastery.com/market-studies/using-gap-zones-to-improve-the-overnight-edge/#comments Sat, 11 Mar 2023 11:00:00 +0000 https://easylanguagemastery.com/?p=25991

In this article, I will see if applying Gap Zones to the Overnight Edge will improve performance. Gap Zones are a quick filter you can use for your strategies as well. The code used in this article is available for you to use!

This article is a continuation of a previous article, The Overnight Edge. As a quick recap of the previous article, many day traders discuss the advantages of closing out their positions at the end of the day. I created a simple market study that highlights a long edge in exploiting by holding through the overnight session. You can read about it here.

In the following study, we're only taking trades on the long side. Dates tested are from January 1, 2007 through January 11, 2023. Slippage and commissions are not deducted. We're trading the symbol @ES.D.

Let's get testing.

Gap Zones

My introduction to Gap Zones was many years ago when I got my hands on Scott Andrews's book, "Understanding Gaps." Scott is also known as "the Gap Guy," and as you can imagine, his book is all about gap trading.

What I want to focus on in this article is Scott's idea of Gap Zones. Gap Zones are a way to classify today's price action based upon what happened yesterday.

Below is a graphic taken from Scott's book where you can see there are ten different zones based upon yesterday's price action

Gap Zones as defined by Scott Andrews:

If the previous day was a down day:

  • Zone 1 - Today's Price is above yesterdays high
  • Zone 2 - Today's Price is between yesterdays open and high
  • Zone 3 - Today's Price is between yesterdays open and close
  • Zone 4 - Today's Price is between yesterdays close and low
  • Zone 5- Today's Price is below yesterdays low

If the previous day was an up day:

  • Zone 6 - Today's Price is above yesterdays high
  • Zone 7 - Today's Price is between yesterdays high and open
  • Zone 8 - Today's Price is between yesterdays open and close
  • Zone 9 - Today's Price is between yesterdays open and low
  • Zone 10 - Today's Price is below yesterdays low

Scott used this information to help filter gap trades for the current day. Depending upon today's Gap Zone, a given trade may tend to work out well or not. In some cases applying the Gap Zone as a filter dramatically proved trading performance. 

The question is, will it help us in the overnight session? 

Added The Gap Zone Code

First I'm going to create an input called GapZone which will be used to test each of the possible Gap Zones.

Input:GapZone(0);

If we set GapZone to zero, that will tell the strategy to ignore the Gap Zone filter. Otherwise, GapZone can hold the values 1-10 representing our ten Gap Zones.

Then, I'm going to create some variables to hold important price information.

TodaysOpen = open;
PrevClosed = close[1];
PrevOpen = open[1];
PrevHigh = high[1];
PrevLow = low[1];

I'm then going to use these variables to simply see what Gap Zone we're in based upon today's opening price. 

I'll also create a variable called TradeGapZone that will tell our strategy if today is a valid Gap Zone. For example, if we're testing Gap Zone 7 and today's price is Gap Zone 7 then TradeGapZone is set to true and trade is opened.

If ( PrevClosed < PrevOpen ) Then // Yesterday Down Day
Begin
   If ( TodaysOpen > PrevHigh ) and ( GapZone = 1 ) then

      TradeGapZone = true // Zone 1
   Else If ( TodaysOpen >= PrevOpen ) and ( TodaysOpen <= PrevHigh ) and ( GapZone = 2 )
      then TradeGapZone = true // Zone 2
   Else If ( TodaysOpen < PrevOpen ) and ( TodaysOpen >= PrevClosed ) and ( GapZone = 3 )

      then TradeGapZone = true// Zone 3
  Else If ( TodaysOpen < PrevClosed ) and ( TodaysOpen >= PrevLow ) and ( GapZone = 4 )

     then TradeGapZone = true // Zone 4
  Else If ( TodaysOpen < PrevLow ) and ( GapZone = 5 ) then

     TradeGapZone = true; // Zone 5
End
Else Begin // Yesterday Up Day
  If ( TodaysOpen > PrevHigh ) and ( GapZone = 6 ) Then

     TradeGapZone = true // Zone 6
  Else If ( TodaysOpen >= PrevClosed ) and ( TodaysOpen <= PrevHigh ) and ( GapZone = 7 ) Then

     TradeGapZone = true // Zone 7
  Else If ( TodaysOpen >= PrevOpen ) and ( TodaysOpen < PrevClosed ) and ( GapZone = 8 ) Then

     TradeGapZone = true // Zone 8
  Else If ( TodaysOpen >= PrevLow ) and ( TodaysOpen < PrevOpen ) and ( GapZone = 9 ) Then

     TradeGapZone = true // Zone 9
  Else If ( TodaysOpen < PrevLow ) and ( GapZone = 10 ) Then

     TradeGapZone = true; // Zone 10
End;

That's basically it.

The Over Night Edge on S&P Futures

Let's take a look at trading the overnight session on the @ES.D symbol. This test does not take into account slippage or commissions. There are no filters. We open a trade every night (15:15 PM Central) and close the market open (8:30 AM Central) the next day. Below is the equity curve.

You can see the equity curve rises nicely. But you can't trade this as the average profit per trade is about $21. Below are some important performance metrics.


Overnight Edge

Trades

3,447

NP

$82,553

NP/DD

1.8

Avg $/Trade

$21

PF

1.09

Drawdown

$46,225

We can now apply our Gap Zones filter. I will optimize the input parameter GapZone with the values 0-10 to test which Gap Zone(s) may produce the best results. Why start at zero? Remember, if we set GapZone to zero, that disables the Gap Zone filter. I do this so I can see the results without the filter alongside my other results.

Here is the optimization report organized in descending order based upon average profit per trade. Click the image for a larger view.

You can see that Gap Zone 5 is the best option. Only take trading with Gap Zone 5 produces an average profit of $155 per trade and the following equity curve.

A huge improvement!

What is Gap Zone 5? Looking at the Gap Zone chart above, Gap Zone 5 is when 1) The previous day was a down day and 2) Today's open was below yesterday's low.

That's an ugly trade, right? We have a down day yesterday and today's open is below yesterday's low. Yet, when you buy at the close and exit your position, you get the following results..


Overnight Edge

With Gap Zone 5

Trades

3,447
415

NP

$82,553
$46,288

NP/DD

1.8
2.4

Avg $/Trade

$21
$616

PF

1.09
1.42

Drawdown

$46,225
$19,425

Adding A Trend Filter

As we enter the bear market of 2022, the overnight edge does not hold up either. Bull markets are where this edge is the strongest. How can we avoid unproductive bear markets? Adding our standard 200-day simple moving average as a regime filter is a filter known to work well. Let's add that.

This means we'll only take trades when the price is above a 200-period simple moving average. When the price is above the 200-period simple moving average, we are in a bull market and free to trade. When the price is below the 200-period simple moving average, we are in a bear market and don't trade. The equity curve and results are below.


Overnight
Edge

With
Gap Zone 5

With
Gap Zone 5 & Trend Filter

Trades

3,447
415
263

NP

$82,553
$46,288
$34,513

NP/DD

1.8
2.4
6.9

Avg $/Trade

$21
$112
$131

PF

1.09
1.42
1.89

Drawdown

$46,225
$19,425
$5,000

We can see a considerable drawdown reduction and a solid increase in NP/DD, Profit Factor, and average profit per trade. Sure, we're making less money as we are trading less often. But overall, the improvements look good.

What Else Can We Do?

What other filters could we test?

Seasonality: You could create a simple filter that only takes trades during specific months. Thus, measuring the impact of different seasons on the overnight edge. Thinking along these lines, you could also test a day-of-the-week filter. Does Friday perform better than Thursday? Is Wednesday a day to avoid opening new trades?

Combine Zones: Looking at the optimization report once again, we can see the second choice is Zone 8. This zone happened when the previous day was an up-day, and today's price is between yesterday's open and close. You could combine Zone 8 and Zone 5. Thus, taking trades in either of these zones. This will add more trades and more profit.

Can We Turn This Into A Real Trading System?

Using Gap Zones can provide significant benefits to taking advantage of the overnight trades. Could this be turned into a real trading system? I think so!

I would move to a smaller timeframe, such as a 5, 10, or 15-minute chart. Moving to these smaller timeframes would allow me to enter trades after the close and better monitor the trades overnight. I would also explore what my stop would be. Another idea to test would be holding the trade until the next day's close vs. closing it at the open.

This should provide you with some great ideas to test on your own.

Best of luck!

]]>
https://easylanguagemastery.com/market-studies/using-gap-zones-to-improve-the-overnight-edge/feed/ 6
A Monthly Trading System That May Fool You https://easylanguagemastery.com/market-studies/a-monthly-trading-system-that-may-fool-you/?utm_source=rss&utm_medium=rss&utm_campaign=a-monthly-trading-system-that-may-fool-you https://easylanguagemastery.com/market-studies/a-monthly-trading-system-that-may-fool-you/#comments Mon, 19 Dec 2022 11:00:00 +0000 https://easylanguagemastery.com/?p=531045

Is there a monthly basis to the S&P markets? Can we locate a monthly short-term swing pattern? Let's find out.

Lately, I've seen some videos about short-term patterns. For example, buy near the close of the month and hold until the next month. Or, buy the first trading day of the month and close it three days later. This got me thinking about creating a simple market study to test short-term trading trends based on each month.

So, I created a simple EasyLanguage strategy that would buy the N day of the month and sell X days later. What does that mean?

The Monthly Bias Strategy Concept

Well, N will be the number of days in the month. One will be the first day of the month. Two will be the second day of the month, and so on. For example, if N is two, we're going to place an order to buy at the open of the next bar. If that next bar is not a trading day, TradeStation will delay the order until the next trading day.

This code is not perfect, but it will give us a rough idea if our concept is viable. Ideally I would like to have a function that will give me just the trading days so when I say N=5 it will be entering on the 5th trading day. I don't have a function to do that. If you know of an EasyLanguage function, please let me know in the comments below.

Once a trade is opened, we'll hold it for X days. After that, we'll close it at the open of the next bar. 

These two values will be inputs so I can use TradeStation's optimization feature to test a range of values quickly. The inputs will look like this.

  • OpenDay(10),
  • HoldDays(3)

Given the above example, this would indicate a new trade is signaled on the 10th day of the month and should be closed 3 bars later. 

I also added a few more enhancements to the code.

Regime Filter

I also added a regime filter as defined by a simple moving average. I included as inputs the ability to enable/disable the regime filter, invert the regime filter and modify the lookback period. Here are the inputs.

  • EnableRegime(1), // 1 enable 0 disable
  • RegimeInvert(0), // 1 invert 0 normal
  • RegimeLookback(200), // number of bars in calculation

What does inverting the regime filter mean? Well, this is a long-only study. Thus, a normal regime filter will only allow trades to happen when the market's current price is above the regime filter. In this case, the regime filter is a 200-day simple moving average. Inverting the regime filter will allow trades only to happen when the price is below the 200-day simple moving average.

Limit Trades Once Per Month

Initially, my strategy code was making several trades per month, and I added a bit of code to limit it to once per month. This is controlled by the okToTrade variable.

Testing Environment

Unless otherwise stated, all the tests in this post will have the following assumptions.

  • Testing dates: January 1, 2006, to November 2022. 
  • There will be no slippage or commissions deducted.
  • Only one contract will be traded per signal.

Testing The Monthly Bias on E-mini S&P

The first test will be on the E-mini S&P futures (@ES) without the regime filter. I will optimize the "OpenDay" input with values 1-31 and the "HoldDays" input with values 0-4. We start at zero for "HoldDays," meaning we hold for 1 bar. So, we're holding for 1-5 bars. This gives us 155 unique combinations to test.

118 of the 155 (76%) combinations make money. That's a good sign. I picked the optimal value based on perfect profit correlation, and that test was...

  • OpenDay = 23
  • HoldDays = 4

Next, let's test the behavior above and below the regime filter. I performed an optimization for each of the situations utilizing the same range of values as above. Why split the market by a regime filter? My reasoning is market behavior changes between these two regime states. I picked the best value for each optimization based on perfect profit correlation. Here are the results

Bull Market
Profitable Tests: 114/155 (74%)
OpenDay = 3
HoldDays = 3

Bear market
Profitable Tests: 101/155 (65%)
OpenDay = 22
HoldDays = 3

Below is a table with all three results. 


No Regime

Bull

Bear

%Profitable

76%

74%

65%

OpenDay

23

3

22

HoldDays

4

3

3

When price is trading above the regime filter (Bull), we can see the first few days of the month hold the best promise. In this case, we're entering on the 3rd day and holding for three days.

However, when price is below the regime filter (Bear), more toward the end of the month is where we see our bias—in this case, entering on the 22nd day and holding for three days.

Below is the performance of each of these three different trading systems with their optimized values based upon perfect profit correlation.


No Regime

Bull Only

Bear Only

Net Profit

$61,163

$57,425

$69,550

Profit Factor

1.80

1.81

3.01

Total Trades

194

159

54

%Winners

64%

66%

69%

Avg.Trade Net Profit

$315

$361

$1,288

Max Drawdown

$16,738

$13,100

$14,275

NPDD

3.7

4.4

4.9

These numbers look good. Looks like we have a promising trading system that is simple to trade. Anyone can do it!

You can imagine combing the Bull Only and Bear Only into a single killer strategy. I think we can build a good trading system from this study.

Is This Valid?

But before we do that, I would like to perform another test. My fear with our current analysis is all our data is in-sample, and this approach is not statistically valid.

Did you catch that? If you did CONGRATULATIONS!

Our results look great. It's tempting to add as stop and start trading. But that would be a mistake. Our results are probably overly optimistic, and at worst, they might be an illusion. Our results might be fooling us.

I'm skeptical of using backtested, in-sample results, used to discover monthly patterns, and expect good real-world results.

One way around this is to leave a segment of historical data as out-of-sample. For example, leave the last four years out of your in-sample backtest. Then locate your favored parameters and move the strategy to the three years of unseen data. The strategy results on the out-of-sample are what you would use to judge the quality of your strategy.

But I'm going to try something else.

I want to validate our results using a rolling window over the historical data. Thus, I will use TradeStation's Walk Forward Optimizer to test our idea further.

Testing on Walk Forward Optimizer

I first tested only taking trades in a bull market. Once again, I  optimize the "OpenDay" input with values 1-31 and the "HoldDays" input with values 0-4. Then used the optimizer to perform a cluster analysis.

The results are not optimistic. We can see many of the tests failed. 

I then performed the same test during a bear market and again, not looking so good.

I then decided to remove the regime filter and test once more. This looked better.

This had several more passing tests, but it was still far from ideal.

This is not to say we can't make a trading system from this concept. Some people may be trading something like this. Maybe that person is you. However, this makes me pause that such a simple system would work on the live market.

How would I proceed?

When I started working on this study, the results looked promising. However, the rolling window for optimizing the two input values threw a cold water on that hot idea.

This article is an excellent example of how we can fool ourselves into thinking we found an edge and this could lead us to trading live and losing money. Of course, maybe we do have a valid edge! But, when we tried a different method of analyzing the input parameters, the results don't look good. Thus, caution is warranted.

So, for moving forward, I would put this concept into incubation. Take the results of the Walk Forward Optimizer without the regime filter, which is the last WFO test we did. Select the optimal result, the five runs with 20% OOS. Here are the optimal parameters for the test:

OpenDay = 14
HoldDays = 0

These settings are the latest optimization that are valid through September 4, 2024. I would put this into incubation and see how it performs in 2023. That would be a good starting point.

]]>
https://easylanguagemastery.com/market-studies/a-monthly-trading-system-that-may-fool-you/feed/ 3
Maximizing Profits with Night or Day Trading: What You Need to Know https://easylanguagemastery.com/market-studies/maximizing-profits-with-night-or-day-trading-what-you-need-to-know/?utm_source=rss&utm_medium=rss&utm_campaign=maximizing-profits-with-night-or-day-trading-what-you-need-to-know https://easylanguagemastery.com/market-studies/maximizing-profits-with-night-or-day-trading-what-you-need-to-know/#comments Mon, 05 Dec 2022 11:00:00 +0000 https://easylanguagemastery.com/?p=531011

This blog post examines the idea of an "overnight edge" in trading S&P futures. It focuses on whether or not more points can be gained during the regular day or night session for the S & P futures market. You just might be surprised at some of the results!

This study expands upon the past article, The Overnight Edge Updated for 2022. As a quick recap, I would like to know if more points are gained during the regular day or night session for the S & P futures market.

To test this idea, I've constructed a trading system that will test the overnight edge by buying at the current close and exiting at the next day's open. Thus, our trade is exposed during the overnight session. Likewise, I've tested holding a trade only during the day by buying at the open and selling at the close.

Adding A 200-Day Regime Filter

I also added a 200-day simple moving average as a regime filter. Thus, I would only take long trades when the price is above the simple moving average and only take short trades when the price is below the simple moving average. Please review the past article for more details and results.

Trading Long In A Bear Market?

In this post, I want to expand the original test to take trades in the "wrong" regime. That is, instead of taking long trades in a bull market, as defined by our regime filter, I will take long trades during a bear market. The U.S. stock index markets have been bearish for 2022, and I wanted to know if shorting or going long is favored in either the night or day session.

Standard Regime Filter 

First, look at the table where I tested the major U.S. stock market indexes using the standard regime filter. That is, only taking long trades in a bull market and short trades only in a bear market.

The green color highlights trades that are averaging over $30 per trade. We can see the best opportunities occur at night on the long side! Shorting continues to be problematic in both the day and night sessions.

So what does this tell us?

These results demonstrate that:

  1. It's much easier to build strategies on the long side during a bull market. Makes sense.
  2. Opportunities may be most substantial in the overnight session.

Inverted Regime Filter 

Next, I want to perform this test again but invert the regime filter, so I will take long trades only in a bear market and only take short trades in a bull market. To perform this test, I used the EasyLanguage code provided in the previously mentioned article. So, review that article if you want a copy of the code. Below are the results.

Once again, the green color highlights trades averaging over $30 per trade. And once again, where is all the green seen? That's right, going long! You would think shorting in a bear market would be obvious. But it could be more apparent with this test.

So what does this tell us?

  1. It's much easier to build strategies on the long side during a bear market. A bit surprising!
  2. Opportunities may be most substantial in the day session. Notice this is the opposite of a bull market. 

Conclusions

For the U.S. stock index markets, the low-hanging fruit continues to be found on the long side. However, depending on the market regime, you will want to switch between the day or night session.

  1. During a bull market, focus on overnight trading
  2. During a bear market, focus on day trading
]]>
https://easylanguagemastery.com/market-studies/maximizing-profits-with-night-or-day-trading-what-you-need-to-know/feed/ 1
The Overnight Edge Updated for 2022 https://easylanguagemastery.com/market-studies/the-overnight-edge-updated-for-2022/?utm_source=rss&utm_medium=rss&utm_campaign=the-overnight-edge-updated-for-2022 https://easylanguagemastery.com/market-studies/the-overnight-edge-updated-for-2022/#respond Mon, 14 Feb 2022 11:00:00 +0000 https://easylanguagemastery.com/?p=27160

The overnight trading action of the S&P has a decisive edge. Did you know that a lot of the gain of the S&P happens at night? This provides a unique opportunity to build a trading system. 

The overnight edge of the S&P is something I've written about before. If you're not familiar with it, you can check out the article, "The Overnight Edge."

Let's update this market study to see how the overnight edge has held up over the past couple of years.

As a quick recap, I've constructed a trading system that will test the overnight edge by buying at the current close and exiting the trade of the next day's open. Thus, our trade is exposed during the overnight session. Likewise, I've tested holding a trade only during the day by buying at the open and selling at the close.

Before getting to the results, both tests were executed from January 2, 2006 to February 9, 2022 with no slippage or commission cost deducted. The symbol used was @ES.D.

Below are the two equity curves generated by the study. The one on the left-hand side is taking all trades during the day, and the right-hand side is taking all trades during the night session:

Day Session

Day Session

Night Session

Night Session

There is a difference between the day session and the night session. This difference is even more dramatic when adding a simple moving average regime filter and only trade trades during a bull market.

We want to go long during a bull market based on what we know about the E-mini S&P market. We also want to buy during a pullback.

Day Session With Regime

Day Session With Regime

Night Session With Regime

Night Session With Regime

Recent Performance Of The Overnight Edge

Let's take a closer look over the past couple of years. Below are the same tests performed from February 11, 2019 to February 9, 2022 with no slippage or commission cost deducted.

Day Session With Regime Recent

Day Session With Regime Recent

Night Session With Regime Recent

Night Session With Regime Recent

It really looks like the overnight edge is holding up well. When taking trades at night during a bull market, that equity curve looks like a trading system. But remember, this is a market study, not a complete trading system. These strategies have no stops and take a new trade every day.

What About Other Markets?

I took a look at the other major stock index markets, and they show similar behavior. Below are the results from taking long trades during a bull market in the overnight session. Click on the images for a larger view.

NQ Night Regime

NQ Night Regime

EMD Night Regime

EMD Night Regime

YM Night Regime

YM Night Regime

What Can I Do With This Info?

I think this information clearly points to a market edge. This would require holding a trade during the overnight session. What this study does not say is how to do that. Should you enter after the market closes? Maybe entering in the pre-market. Or, is holding all through the night the way to capture most of the points? Well, that will depend upon the market and the strategy you have.

Below are a few articles that point you in this direction to give you some ideas.


]]>
https://easylanguagemastery.com/market-studies/the-overnight-edge-updated-for-2022/feed/ 0