Strategies – Helping you Master EasyLanguage https://easylanguagemastery.com Helping you Master EasyLanguage Wed, 09 Oct 2024 14:31:34 +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 Strategies – Helping you Master EasyLanguage https://easylanguagemastery.com 32 32 A Modern Approach to Breakout Trading: The Better Breakout Strategy https://easylanguagemastery.com/strategies/a-modern-approach-to-breakout-trading-the-better-breakout-strategy/?utm_source=rss&utm_medium=rss&utm_campaign=a-modern-approach-to-breakout-trading-the-better-breakout-strategy https://easylanguagemastery.com/strategies/a-modern-approach-to-breakout-trading-the-better-breakout-strategy/#comments Mon, 21 Oct 2024 10:00:00 +0000 https://easylanguagemastery.com/?p=535126

Are you interested in an intraday breakout trading system that has been consistently performing since 2012? You're in the right place! In this article, we'll explore a modern approach to trading breakout systems, and I'll even share the code with you—for free.

Hello, I'm Jeff Swanson, and with over two decades of experience in the futures markets, I'm here to share my journey and help you become a successful algorithmic trader. This is the second article in our series on breakout trading strategies. If you missed the first article, you can read it here, The Powerful Benefits of Breakout Trading Systems.

Let's dive right in.

Understanding the Better Breakout Strategy

Today, we'll delve into a powerful breakout trading system specifically designed for the futures market. The strategy is called the Better Breakout, and it's tailored for the S&P E-Mini Futures market. The performance of this strategy has been impressive, showing strong results dating back to 1987.

The original rules for this strategy were described in Futures Truth magazine back in 2012, in an article titled "Better Breakouts in the Electronic Age" by Murray Ruggiero. While the magazine is no longer in circulation, I've written an article about it called Better Breakout Trading Model.  I wrote that article back in 2012 and that means we have 12 years of out-of-sample data!

The Shift in Breakout Strategies

Traditionally, many breakout strategies use the 8:30 AM Central Time opening as a key price level for determining when to enter long or short positions. However, with near 24-hour access to the futures market, the significance of that opening time has diminished.

Murray Ruggiero proposed a twist on the traditional breakout strategy. Instead of relying on the opening range, we're going to use yesterday's price action to set our breakout levels.

Who Was Murray Ruggiero?

Before we dive deeper, let's take a moment to acknowledge Murray Ruggiero's contributions.

Murray was a pioneering figure in algorithmic and quantitative trading, renowned for his expertise in advanced technologies like machine learning and intermarket analysis. He spent decades refining data-driven approaches and authored numerous articles and books that have been immensely helpful to traders, including myself.

Unfortunately, Murray passed away a couple of years ago, but his work continues to influence traders worldwide. He's perhaps best known for his insights into intermarket analysis and seasonality patterns. Thank you, Murray, for your invaluable contributions.

The Logic Behind the Better Breakout Strategy

Now, let's explore how Murray's strategy can help us improve a typical breakout system.

Using Yesterday's Price Action

Instead of relying on the traditional opening range, we'll use yesterday's price action to set our breakout levels. Let's consider yesterday's bar, which includes:

  • Open
  • High
  • Low
  • Close
Figure A: Yesterday's Price Action Bar

Figure A: Yesterday's Price Action Bar

We will use this information to build our breakout levels. Specifically, we'll calculate offsets based on the difference between yesterday's close and its high or low. The larger of these two values is averaged over three days to create a dynamic breakout range.

Calculating the Offsets

Here's how the process works:

Here's how the process works:

  1. Calculate the High Offset:
    High Offset=High−Close
  2. Calculate the Low Offset:
    Low Offset=Close−Low
Figure B: High and Low Offsets

Figure B: High and Low Offsets

These calculations are straightforward. We're essentially measuring the distance from the close to the high and the close to the low.

  1. Determine the Maximum Offset:
    • Take the larger of the two offsets.
    • For instance, if the close is near the high, the high offset will be small, and the low offset will be larger.
    • Store the larger value as the Max Offset.
  2. Compute the Three-Day Average:
    • Calculate the max offset for each of the last three days.
    • Compute the average of these three values.
    • Store this in a variable called Max Offset Average.

This approach gives us a more adaptive breakout level that reflects recent market conditions. It's less dependent on the arbitrary opening price and more aligned with current volatility. As market conditions change, our offset adapts accordingly.

The Logic Behind the Adaptation

By accounting for significant price movements from the previous day—both the highs and lows relative to the close—we create a breakout strategy that's responsive to the market's recent behavior. Smoothing out anomalies by averaging over three days ensures that our breakout levels aren't overly influenced by a single day's extreme movement.

Implementing the Strategy in EasyLanguage

Now, let's delve into how to implement the Better Breakout strategy using EasyLanguage in TradeStation. Don't worry if you're new to EasyLanguage; I'll break down each part of the code so it's easy to understand. Remember, mastering EasyLanguage is a crucial skill for becoming a successful algorithmic trader.

Input:
CloseTime(1500),
Lookback(40);

Variables:
LastBar(0),
StopLoss$(0),
vMomentum(0, Data2),
LowOffset(0, Data2),
HighOffset(0, Data2),
MaxOffset(0, Data2),
MaxOffsetAvg(0, Data2);

Once LastBar = CalcTime(CloseTime, -BarInterval);

LowOffset = AbsValue(Close of Data2 - Low of Data2);
HighOffset = AbsValue(Close of Data2 - High of Data2);
MaxOffset = MaxList(LowOffset, HighOffset);
MaxOffsetAvg = Round2Fraction(Average(MaxOffset, 3));
StopLoss$ = Round2Fraction(MaxOffsetAvg / 2) * BigPointValue;
vMomentum = Close of Data2 - Average(Close of Data2, Lookback);

If (vMomentum < 0) and (EntriesToday(Date) = 0) and (Time < LastBar) Then
Buy("LE") 1 Contract Next Bar at Close of Data2 + MaxOffsetAvg Stop;

If (Time >= LastBar) Then
Sell("EOD") Next Bar at Market;

SetStopLoss(StopLoss$);

Code Breakdown

Let's go through the code step by step to understand how each part contributes to the strategy.

Inputs

  • CloseTime(1500): This sets the time (in military format) when we want to close all positions. Here, it's set to 3:00 PM (1500 hours).
  • Lookback(40): This determines the number of periods (in this case, days) for calculating the momentum indicator

Variables

  • LastBar(0): Will store the time of the last bar before the close time.
  • StopLoss$(0): The calculated dollar amount for the stop loss.
  • vMomentum(0, Data2): The momentum indicator based on the daily chart (Data2).
  • LowOffset(0, Data2) and HighOffset(0, Data2): Variables to store the offsets from the close to the low and high of the previous day.
  • MaxOffset(0, Data2): The maximum of the two offsets.
  • MaxOffsetAvg(0, Data2): The three-day average of the maximum offset, rounded to the nearest valid price increment.

Calculate Last Bar Time

  • Purpose: Determines the time of the last bar before CloseTime.
  • CalcTime(CloseTime, -BarInterval): Calculates the time by subtracting the bar interval from the close time. This ensures we don't enter new trades too close to the market close.

Calculating the Offsets

  • LowOffset: The absolute value of the difference between yesterday's close and low.
  • HighOffset: The absolute value of the difference between yesterday's close and high.
  • Data Reference: Data2 refers to the daily data series we've added to our chart. This allows us to access daily high, low, and close prices while trading on a 5-minute chart (Data1).

Determining the Maximum Offset and Average

  • MaxOffset: Selects the larger of the two offsets for each day.
  • Average(MaxOffset, 3): Calculates the average of the maximum offsets over the last three days.
  • Round2Fraction(...): Rounds the average to the nearest valid price increment (tick size), ensuring our calculations align with the market's price increments.

Calculating the Dynamic Stop Loss

  • Purpose: Sets a dynamic stop loss based on recent market volatility.
  • MaxOffsetAvg / 2: We take half of the average maximum offset to determine a reasonable stop distance.
  • BigPointValue: A built-in variable representing the dollar value of a full point move in the contract (e.g., $50 for the ES futures).
  • StopLoss$: The stop loss value in dollars, adjusted to market increments.

Calculating the Momentum Filter

  • Purpose: Measures market momentum to filter trades.
  • Close of Data2: The closing price from the daily data series.
  • Average(Close of Data2, Lookback): The 40-day simple moving average of the close.
  • vMomentum: When this value is negative, it indicates that the current price is below the 40-day moving average, suggesting a potential buying opportunity in a pullback.

Entry Conditions

  • (vMomentum < 0): Ensures we're only entering trades when the momentum indicator is negative (price below the moving average).
  • (EntriesToday(Date) = 0): Limits us to one trade per day.
  • (Time < LastBar): Prevents new entries too close to the market close.
  • Buy("LE") 1 Contract Next Bar at Close of Data2 + MaxOffsetAvg Stop;:
    • Action: Places a stop order to buy one contract.
    • Price Level: At yesterday's close plus the average maximum offset.
    • Order Name: "LE" (Long Entry).

Exit Conditions

  • (Time >= LastBar): Checks if we've reached the time to close positions.
  • Sell("EOD") Next Bar at Market;:
    • Action: Sells the position at the market price on the next bar.
    • Order Name: "EOD" (End of Day)

Setting the Stop Loss

  • Purpose: Implements the stop loss calculated earlier.
  • Dynamic Stop Loss: Because StopLoss$ is based on recent volatility, it adapts to changing market conditions.

By understanding each component of the code, you can see how the Better Breakout strategy uses recent price action and market momentum to determine entry and exit points. The use of dynamic calculations makes the strategy adaptive to changing market conditions, which is crucial for long-term success in algorithmic trading.

If you're new to EasyLanguage, I highly recommend taking the time to learn it. The best way to do that is to have me teach you in my System Development Master Class.  Being able to code and test your own strategies is an invaluable skill that can significantly enhance your trading performance.

Setting Up the Chart in TradeStation

To implement this strategy in TradeStation:

Chart Settings:

  • Session Times: 8:30 AM to 3:00 PM Central Time.
  • Time Frame: 5-minute chart.
  • Slippage and Commissions: $30 deducted per round trip.
  • Data Stream:
    • Data1: 5-minute chart (trading timeframe).
    • Data2: Daily chart (for calculations).

Trading Rules:

  • Long Only: The strategy is designed for long entries.
  • One Trade Per Day: Ensures risk management and prevents overtrading.
  • Close All Trades at End of Day: All positions are closed at the specified close time.

Performance Analysis

The equity curve shows a steady upward trend since 2012, indicating consistent performance. While there has been some choppiness in recent times, the strategy has maintained its profitability

Better Breakout 2024

Better Breakout 2024

Key Performance Metrics:

  • Total Net Profit: Approximately $35,000.
  • Average Trade Profit: $181 (including slippage and commissions).
  • Total Trades: 191.

Annual Returns Breakdown:

  • Profitable in most years since 2012.
  • Notable exceptions in 2013 and potentially 2024.

Trying the Strategy on Different Markets

One of the great aspects of algorithmic trading is the ability to test strategies on different markets. Let's see how the Better Breakout strategy performs on the NASDAQ futures (NQ).

A New Market and New Chart Setting

In an effort to explore the robustness and adaptability of the Better Breakout strategy, I decided to apply it to the NASDAQ futures (NQ) market. The NASDAQ futures often exhibit higher volatility and different trading dynamics compared to the S&P E-Mini Futures (ES), which can potentially enhance the strategy's performance.

Next I adjusting Data2 to use a 1,440-minute chart (equivalent to a daily chart), we can test the strategy on the NASDAQ futures.

The 1,440-minute chart provides more accurate pricing information because the closing price represents the actual last traded price, rather than the settlement price used in daily bars. Settlement prices can introduce inaccuracies due to adjustments made at the end of the trading day, which can affect real-time trading strategies. By using the last traded price, we eliminate issues with changing settlement prices, leading to more precise entry and exit signals.

Using a 1,440-minute chart leads to more accurate backtesting results. It removes discrepancies between daily Open, High, Low, and Close (OHLC) prices and minute bar OHLC prices that can significantly impact backtested strategy performance. 

Better Breakout on NQ with 1440 minute data2  2012 to 2024-10-09

Better Breakout on NQ with 1440 minute data2 

Improved Performance Metrics:

  • Total Net Profit: Approximately $60,000.
  • Average Trade Profit: $308.
  • Total Trades: 193.

The equity curve for NQ shows an even more impressive upward trend, with a new equity high as recent as August 2024

Experimenting with the Momentum Filter

In the original Better Breakout strategy code, we included a momentum filter to improve the quality of our trade signals. This filter is designed to ensure that we only enter trades when certain momentum conditions are met, potentially increasing the efficiency and profitability of the strategy.

I also experimented with removing the momentum filter to see its impact.

Without Momentum Filter:

  • Total Net Profit: Approximately $67,800.
  • Average Trade Profit: $108.
  • Total Trades: 627.
  • Profit Factor: 1.63.
  • Equity Curve: More volatile with a larger number of trades and lower efficiency.

With Momentum Filter:

  • Total Net Profit: Approximately $60,000.
  • Average Trade Profit: $308.
  • Total Trades: 193.
  • Profit Factor: 1.88.
  • Equity Curve: Smooth upward trend with fewer trades and higher efficiency.

By only allowing trades when the price is below the 40-day moving average, the filter reduces the number of trades. It helps us focus on higher-probability setups where the market may be poised for a rebound after a pullback.

This illustrates the importance of testing different ideas. Removing the momentum filter increased the number of trades and total profit but reduced efficiency. Depending on your trading goals, you might prefer one setup over the other.

Avoiding Rookie Mistakes

When experimenting with algorithmic trading, keep these common pitfalls in mind:

  1. Not Trying Different Markets:
    • Don't limit yourself to a single market. Testing on similar markets can yield better results, as we saw when switching from ES to NQ.
  2. Not Trying Different Time Frames:
    • Experiment with different time frames, both for your trading chart and data inputs. Small changes can lead to significant differences in performance.

Conclusion

In this article, we've explored the Better Breakout strategy, a robust and adaptive approach to intraday breakout trading that has stood the test of time since its inception in 2012.

The Better Breakout strategy continues to demonstrate its effectiveness in today's markets, proving to be a reliable and adaptable approach for algorithmic traders. Its strength lies in its simplicity and the use of dynamic calculations that adjust to changing market conditions. Whether you're a novice trader or an experienced professional, this strategy offers a solid foundation upon which you can build and customize your own trading system.

By understanding the underlying logic and experimenting with different time frames, and filters—you can tailor the strategy to fit your trading style and objectives. I think the Better Breakout only works well for the stock index markets, but it's worth testing other markets. 

Final Thoughts

Algorithmic trading is a journey of continuous learning and adaptation. The Better Breakout strategy serves as an excellent starting point, encouraging you to delve deeper into the mechanics of trading systems and the nuances of market behavior. As you apply and modify this strategy, you'll gain valuable insights and develop the skills necessary to become a successful algorithmic trader.

Remember, the key to success lies in diligent testing, thoughtful analysis, and a willingness to experiment. Don't hesitate to explore different markets, adjust parameters, and incorporate new ideas. The more you engage with the strategy, the more proficient you'll become in crafting systems that align with your goals.


]]>
https://easylanguagemastery.com/strategies/a-modern-approach-to-breakout-trading-the-better-breakout-strategy/feed/ 2
Prune Your Trend Following Algorithm https://easylanguagemastery.com/strategies/prune-your-trend-following-algorithm/?utm_source=rss&utm_medium=rss&utm_campaign=prune-your-trend-following-algorithm https://easylanguagemastery.com/strategies/prune-your-trend-following-algorithm/#respond Mon, 09 Sep 2024 10:00:00 +0000 https://easylanguagemastery.com/?p=534898

Multiple trading decisions based on “logic” may not add to the bottom line

In this post, I will present a trend following system that uses four exit techniques. These techniques are based on experience and also logic. The problem with using multiple exit techniques is that it is difficult to see the synergy that is generated from all the moving parts. Pruning your algorithm may help cut down on invisible redundancy and opportunities to over curve fit. The trading strategy I will be presenting will use a very popular entry technique overlaid with trade risk compression.

Entry logic

Long:

Criteria #1: Penetration of the closing price above an 85 day (closing prices) and 1.5X standard deviation-based Bollinger Band.

Criteria #2: The mid-band or moving average must be increasing for the past three consecutive days.

Criteria #3: The trade risk (1.5X standard deviation) must be less than 3 X average true range for the past twenty days and also must be less than $4,500.

Risk is initially defined by the standard deviation of the market but is then compared to $4,500. If the trade risk is less than $4,500, then a trade is entered. I am allowing the market movement to define risk, but I am putting a ceiling on it if necessary.

Short:

Criteria #1: Penetration of the closing price below an 85 day (closing prices) and 1.5X standard deviation-based Bollinger Band.

Criteria #2: The mid-band or moving average must be decreasing for the past three consecutive days.

Criteria #3: Same as criteria #3 on the long side

Exit Logic

Exit #1: Like any Bollinger Band strategy, the mid band or moving average is the initial exit point. This exit must be included in this particular strategy, because it allows exits at profitable levels and works synergistically with the entry technique.

Exit #2: Fixed $ stop loss ($3,000)

Exit #3: The mid-band must be decreasing for three consecutive days and today’s close must be below the entry price.

Exit #4: Todays true range must be greater than 3X average true range for the past twenty days, and today’s close is below yesterday’s, and yesterday’s close must be below the prior days.

Here is the logic of exits #2 through exit #4. With longer term trend following system, risk can increase quickly during a trade and capping the maximum loss to $3,000 can help in extreme situations. If the mid-band starts to move down for three consecutive days and the trade is underwater, then the trade probably should be aborted. If you have a very wide bar and the market has closed twice against the trade, there is a good chance the trade should be aborted.

Short exits use the same logic but in reverse. The close must close below the midband, or a $3,000 maximum loss, or three bars where each moving average is greater than the one before, or a wide bar and two consecutive up closes.

Here is the logic in PowerLanguage/EasyLanguage that includes the which exit seletor.

[LegacyColorValue = true];
Inputs:maxEntryRisk$(4500),maxNATRLossMult(3),maxTradeLoss$(3000),
indicLen(85),numStdDevs(1.5),highVolMult(3),whichExit(7);

Vars: upperBand(0), lowerBand(0),slopeUp(False),slopeDn(False),
largeAtr(0),sma(0),
initialRisk(0),tradeRisk(0),
longLoss(0),shortLoss(0),permString("");

upperBand = bollingerBand(close,indicLen,numStdDevs);
lowerBand = bollingerBand(close,indicLen,-numStdDevs);
largeATR = highVolMult*(AvgTrueRange(20));

sma = average(close,indicLen);

slopeUp = sma>sma[1] and sma[1]>sma[2] and sma[2]>sma[3];
slopeDn = sma<sma[1] and sma[1]<sma[2] and sma[2]<sma[3];

initialRisk = AvgTrueRange(20);
largeATR = highVolMult * initialRisk;
tradeRisk = (upperBand - sma);
// 3 objects in our permutations
// exit 1, exit 2, exit 3
// perm # exit #
// 1 1
// 2 1,2
// 3 1,3
// 4 2
// 5 2,3
// 6 3
// 7 1,2,3

if whichExit = 1 then permString = "1";
if whichExit = 2 then permString = "1,2";
if whichExit = 3 then permString = "1,3";
if whichExit = 4 then permString = "2";
if whichExit = 5 then permString = "2,3";
if whichExit = 6 then permString = "3";
if whichExit = 7 then permString = "1,2,3";


{Long Entry:}
If (MarketPosition = 0) and
Close crosses above upperBand and slopeUp and
(tradeRisk < initialRisk*maxNATRLossMult and tradeRisk<maxEntryRisk$/bigPointValue) then
begin
Buy ("LE") Next Bar at Market;
End;

{Short Entry:}
If (MarketPosition = 0) and slopeDn and
Close crosses below lowerBand and
(tradeRisk < initialRisk*maxNATRLossMult and tradeRisk<maxEntryRisk$/bigPointValue) then
begin
Sell Short ("SE") Next Bar at Market;
End;
{Long Exits:}

if marketPosition = 1 Then
Begin
longLoss = initialRisk * maxNATRLossMult;
longLoss = minList(longLoss,maxTradeLoss$/bigPointValue);

If Close < sma then
Sell ("LX Stop") Next Bar at Market;;

if inStr(permString,"1") > 0 then
sell("LX MaxL") next bar at entryPrice - longLoss stop;

if inStr(permString,"2") > 0 then
If sma < sma[1] and sma[1] < sma[2] and sma[2] < sma[3] and close < entryPrice then
Sell ("LX MA") Next Bar at Market;
if inStr(permString,"3") > 0 then
If TrueRange > largeATR and close < close[1] and close[1] < close[2] then
Sell ("LX ATR") Next Bar at Market;
end;

{Short Exit:}

If (MarketPosition = -1) Then
Begin

shortLoss = initialRisk * maxNATRLossMult;
shortLoss = minList(shortLoss,maxTradeLoss$/bigPointValue);
if Close > sma then
Buy to Cover ("SX Stop") Next Bar at Market;

if inStr(permString,"1") > 0 then
buyToCover("SX MaxL") next bar at entryPrice + shortLoss stop;

if inStr(permString,"2") > 0 then
If sma > sma[1] and sma[1] > sma[2] and sma[2] > sma[3] and close > entryPrice then
Buy to Cover ("SX MA") Next Bar at Market;
if inStr(permString,"3") > 0 then
If TrueRange > largeAtr and close > close[1] and close[1] > close[2] then
Buy to Cover ("SX ATR") Next Bar at Market;
end;

Trend following with exit selector

Please note that I modified the code from my original by forcing the close to cross above or below the Bollinger Bands. There is a slight chance that one of the exits could get you out of a trade outside of the bands, and this could potentially cause and automatic re-entry in the same direction at the same price. Forcing a crossing, makes sure the market is currently within the bands’ boundaries.

This code has an input that will allow the user to select which combination of exits to use.

Since we have three exits, and we want to evaluate all the combinations of each exit separately, taken two of the exits and finally all the exits, we will need to rely on a combinatorial table. In long form, here are the combinations:

3 objects in our combinations of exit 1, exit 2, exit 3

* one – 1
* two – 1,2
* three – 1,3
* four – 2
* five – 2,3
* six – 3
* seven – 1,2,3

There are a total of seven different combinations. Given the small set, we can effectively hard-code this using string manipulation to create a combinatorial table. For larger sets, you may find my post on the Pattern Smasher beneficial. A robust programming language like Easy/PowerLanguage offers extensive libraries for string manipulation. The inStr string function, for instance, identifies the starting position of a substring within a larger string. When keyed to the whichExit input, I can dynamically recreate the various combinations using string values.

1. if whichExit = 1 then permString = “1”
2. if whichExit = 2 then permString= “1,2”
3. if whichExit = 3 then permString = “1,2,3”
4. etc…
As I optimize from one to seven, permString will dynamically change its value, representing different rows in the table. For my exit logic, I simply check if the enumerated string value corresponding to each exit is present within the string.

if inStr(permString,"1") > 0 then
sell("LX MaxL") next bar at entryPrice - longLoss stop;
if inStr(permString,"2") > 0 then
If sma < sma[1] and sma[1] < sma[2] and sma[2] < sma[3] and close < entryPrice then
Sell ("LX MA") Next Bar at Market;
if inStr(permString,"3") > 0 then
If TrueRange > largeATR and close < close[1] and close[1] < close[2] then
Sell ("LX ATR") Next Bar at Market;

Using inStr to see if the current whichExit input applies

When permString = “1,2,3” then all exits are used. If permString = “1,2”, then only the first two exits are utilized. Now all we need to do is optimize whichExit from 1 to 7. Let’s see what happens:

Combination of all three exits

The best combination of exits was “3”. Remember 3 is the permString that = “1,3” – this combination includes the money management loss exit, and the wide bar against position exit. It only slightly improved overall profitability instead of using all the exits – combo #7. In reality, just using the max loss stop wouldn’t be a bad way to go either. Occam uses his razor to shave away unnecessary complexities again!

If you like this code, you should check out the Summer Special at my digital store. I showcase over ten more trend-following algorithms with different entry and exit logic constructs. These other algorithms are derived from the best Trend Following “Masters” of the twentieth century. IMHO!

Here is a video you can watch that goes over the core of this trading strategy.

>> By George Pruitt from blog Georgepruitt.com

]]>
https://easylanguagemastery.com/strategies/prune-your-trend-following-algorithm/feed/ 0
Crafting a Winning NG Futures Strategy with CCI and Build Alpha https://easylanguagemastery.com/strategies/building-a-cci-strategy-with-build-alpha/?utm_source=rss&utm_medium=rss&utm_campaign=building-a-cci-strategy-with-build-alpha https://easylanguagemastery.com/strategies/building-a-cci-strategy-with-build-alpha/#respond Mon, 25 Sep 2023 10:00:00 +0000 https://easylanguagemastery.com/?p=532838

About 16 years ago, I stumbled upon the world of trading, and it was a rollercoaster of emotions and experiences. Fast forward to today, and I've discovered yet another intriguing facet of trading: the Commodity Channel Index (CCI). Inspired by a thought-provoking YouTube channel from StatOasis, I felt the urge to explore the CCI's potential in the realm of natural gas futures. And, as always, I wanted to share this journey with you, my fellow traders.

Now, I'm sure many of you have dabbled with the CCI in your trading adventures. But have you ever considered building an entire strategy around it? That's precisely what we're about to do. With the help of Build Alpha, a tool I've come to trust over the years, we'll construct, refine, and put to the test a CCI-centric strategy tailored for the NG futures market.

For those of you who've been with me since the early days of my trading journey, you know the drill. We're going to dissect the CCI, understand its nuances, and then dive deep into the mechanics of strategy development. Whether you're a seasoned trader or just starting your algorithmic trading journey, I promise this exploration will be packed with insights and actionable takeaways.

So, let's roll up our sleeves and get started. Together, we'll navigate the intricacies of the CCI and the dynamic world of natural gas futures. Ready to embark on another trading adventure with me?

Understanding the Commodity Channel Index (CCI)

Years ago, when I first dipped my toes into the vast ocean of trading, I was overwhelmed by the sheer number of technical indicators available. Some were straightforward, while others seemed wrapped in layers of complexity. Among them, the Commodity Channel Index, or CCI as it's commonly known, caught my attention. And today, I want to pull back the curtain on this fascinating indicator.

A Brief History of the CCI

The CCI was introduced by Donald Lambert back in the late 1970s. Originally designed for the commodities market, its primary goal was to identify cyclical turns in commodities. But, as with many things in trading, its application soon expanded beyond its initial intent. Today, traders use the CCI across various asset classes, from stocks to forex and, of course, futures.

The Mechanics Behind the CCI

At its core, the CCI measures the current price level relative to an average price level over a specific period. Think of it as a tool that gauges how far the price has deviated from its average. A high CCI indicates prices are above their average, which can signify an overbought condition. Conversely, a low CCI suggests prices are below their average, hinting at an oversold condition.

Now, I know what some of you might be thinking: "Jeff, this sounds a lot like other oscillators!" And you're not wrong. But the CCI has its unique quirks and nuances. For instance, it uses the typical price (the average of high, low, and close) for its calculations rather than just the closing price. This gives it a slightly different flavor compared to some other indicators.

Interpreting the CCI

The CCI oscillates around a zero line. Traditionally, a reading above +100 indicates an overbought condition, suggesting a potential price reversal to the downside. On the flip side, a reading below -100 signals an oversold condition, hinting at a possible upward price move.

But here's a nugget of wisdom from my years of trading: while these traditional levels can be useful, they aren't set in stone. Different markets and different timeframes can exhibit varying behaviors. Sometimes, I've found it beneficial to adjust these thresholds to better suit the specific market conditions I'm trading in.

The Basic CCI Strategy

In the StatOasis video, the core of the strategy is to go short when the 8-period CCI rises above 130. A profit target of 2 times ATR and a stop loss of 4 times ATR are used to exit the trade.

If we code this up in EasyLanguage, we get the following results when applied to the daily chart of the natural gas futures market (@NG).

CCI Basic Strategy EQ Curve

CCI Basic Strategy EQ Curve

CCI Basic Strategy Report

CCI Basic Strategy Report

Note, these results do not take into account slippage or commissions.

The results are a great starting point. We have a rising equity curve and it's a profitable system. I think this demonstrates the CCI might be a good signal for going short the @NG market. Now, we want to improve our basic strategy.

We want to look for filters we can add to this strategy to improve it. We could use our EasyLanguage skills to test different filters, such as moving averages, volume, or price patterns, but that would take a long time. How can we do it faster?

We can use a tool like Build Alpha.

Building the CCI Strategy with Build Alpha

At its core, Build Alpha is a robust, automated strategy development platform. But to label it just as such would be an understatement. It's more like a Swiss Army knife for traders, offering a suite of features that cater to both novices and seasoned professionals.

Build Alpha is designed to assist traders in creating, testing, and optimizing trading strategies. But what sets it apart is its ability to do so without any programming knowledge required. That's right – you can craft intricate, data-driven strategies without writing a single line of code. Read more about Build Alpha here, Creating Strategies Using Build Alpha.

We have our basic CCI strategy, but we want to test different filters on our strategy. Writing the code to test additional filters will take a lot of time. However, with Build Alpha, we can "program" basic CCI strategy into software and have it search over 4,000 additional filters in a few minutes.

In Build Alpha, I "code" our basic CCI strategy with a few mouse clicks. I added the CCI trigger.

CCI Basic Strategy Configure CCI

CCI Basic Strategy Configure CCI

Next, I want to tell Build Alpha to search for an additional entry condition to act as a filter. Build Alpha has access to over 4,000 different indicators that will serve as a filter.

CCI Basic Strategy Configure Signals

CCI Basic Strategy Configure Signals

I then added my Stop Loss and Profit Target. I then also tell Build Alpha to test different ATR profit target values and ATR stop values. For example, it will explore 2xATR, 3xATR, and 4xATR for the profit target. 

CCI Basic Strategy Configure Stops & Targets

CCI Basic Strategy Configure Stops & Targets

Next, I also want to test another type of exit, and that's a maximum hold time limit. I will have Build Alpha hold for a maximum of 1, 2, or 3 days. I'm also going to set the out-of-sample to 50% of this historical data.

CCI Basic Strategy Configure OOS

CCI Basic Strategy Configure OOS

Finally, we tell Build Alpha what dates we will use for our in-sample, out-of-sample, and Validation. Did you catch that? When building strategies, you must use in-sample and out-of-sample. However, when I use a tool like Build Alpha, I like to include a third segment called Validation. This is simply a segment of history that Build Alpha does not have access to. 

I will use data from 2000-01-01 to 2020-12-31 as data for Build Alpha to use. The in-sample will be 50% of this and the out-of-sample will be the remainder.

I'm going to do something a little different. I will have Build Alpha build our strategy on the most recent price data and use the out-of-sample as the most distant price data. This is different than a lot of other people do. Traditionally, the out-of-sample data segment is the most recent. I like to have Build Alpha build on the most recent price history.

CCI Basic Strategy Configure Hisorical Data Segments

CCI Basic Strategy Configure To Use out-of-sample at Beginning of historical data


We're about ready for Build Alpha to work its magic. Below is what we have Build Alpha testing for:

  • Additional Filter
  • Profit Target ATR multiple
  • Stop Loss ATR multiple
  • Max hold 1, 2 or 3 bars

Now, we press a button and let Build Alpha work its magic.

Build Alpha Results

CCI Basic Strategy Simulation Results

CCI Basic Strategy Simulation Results

Enter your text here...The highlight light blue color is the out-of-sample. Notice that the out-of-sample occurs on the first 60 trades or so. But it looks good!

CCI Basic Strategy Simulation EQ

CCI Basic Strategy Simulation EQ

Introducing The NG CCI Alchemy Trading Systems

So, what filter did Build Alpha discover as a great filter? It's straightforward. It a moving average filter. Here is the EasyLanguage code:

  average(close,200)[0] < average(close,200)[3]

We're using a 200-bar simple moving average, and today's value must be lower than three days ago. This is the filter applied to our basic CCI strategy. 

Build Alpha also determined our stop and profit target multiples as:

  • Profit Target Multiple: 2 times daily 20-period ATR
  • Stop Loss Multiple: 3 times daily 20-period ATR

The last value optimized was the maximum hold time, which is three. Thus, we close our trades after holding for three days.

I then named this strategy the NG CCI Alchemy Strategy. Why that name? Nothing particular. I just wanted to give it a unique name so it's easier to reference. 

Build Alpha discovered this simple moving average filter and all our parameters within a few minutes of searching. Our out-of-sample equity curve looks good. Now it's time to validate our strategy to help ensure it's not curve fit to the historical data.


Build Alpha Validation

One of the excellent ways Build Alpha helps you avoid curve fitting is by comparing your strategy to randomly generated strategies. During the development phase, Build Alpha will develop thousands of random strategies based on your chosen signals. The performance of these random strategies will be collected, and they act as a baseline helping you discern whether your final generated strategies will perform better than random.

If your final strategy is based upon random chance (curve-fit), it will likely look indistinguishable from the other random strategies. However, if your strategy performs better than the thousands of random strategies, your strategy may possess some edge more significant than could be found by random chance. This is a test from Jaffray Woodriff's chapter 5 in Hedge Fund Market Wizards.

Below are two of my favorite robustness tests within Build Alpha to help quickly locate strategies that might be overfitted to the historical data. They are, Variance Testing and Noise Testing.

Let's apply these two tests to our new CCI Strategy. We'll be using a $100,000 account size and define a ruin level of $40,000. This means if few ever lose more than $40,000 from our starting capital, we'll say the strategy failed (ruin).

Here are the tests in detail.

Variance Testing: This unique test simulates how well a trading strategy should do over the following N trades. It creates hypothetical equity curves into the future based on the distribution of the backtest results. This type of stress testing can help determine if a strategy has an unrealistic backtest or is part of a stable distribution poised to perform near desired expectations moving forward.

CCI Basic Strategy Simulation Variance Test

CCI Basic Strategy Simulation Variance Test

Here we can see the Variance Testing is producing hypothetical equity curves into the future. Notice they are all in positive territory. This is good! We can also see in the numbers below that the graph of our Risk of Ruin is below 1%. This is a great sign that our strategy is robust and may work on the live market.

Noise Test: This test introduces noise to the price data. Noise is accomplished by slightly changing some of the open, high, low, and close values. Build Alpha then re-trades the selected strategy on 1,000 newly generated price series with varying amounts of noise. The idea is to see if the noise in the data crashes our strategy or does it continue to do OK.

CCI Basic Strategy Simulation Noise Test

CCI Basic Strategy Simulation Noise Test

Our strategy is represented as the Blue Line. When we add noise to the price data we can see our equity curve shifts above the blue line and below the blue line. Notice all the equity curves remain profitable. This is another good sign that our strategy is robust. 

My Final Validation

Remember when I told you I like to break my historical data into three segments?

  1. In-sample
  2. Out-of-sample
  3. Validation

Well, now it's time for the final test. I want to take the strategy created in Build Alpha and apply to my Validation data segment. This is price data that was not used during the development of the strategy in Build Alpha. It's completely unseen data.

To test my strategy on the Validation segment, I'm going to have Build Alpha generate the EasyLanguage code. I will then import that code into TradeStation and see how the strategy performs on this unseen data.

Let's generate the code. We do that with a push of a button!

CCI Basic Strategy Simulation Generate EL Code

CCI Basic Strategy Simulation Generate EL Code

Below is the equity curve of the strategy on the validation segment. Remember, this is unseen data. 

The equity curve looks great! This is showing about $20,000 in profit with 31 trades. That's about $655 per trade. The drawdown is $4,870 giving us a NP/DD ratio of 4.1, which is excellent.

Summary and Conclusion: Harnessing the Power of CCI and Build Alpha for NG Futures Trading

In our exploration today, we've journeyed through the intricacies of the Commodity Channel Index (CCI) and delved into some of capabilities of Build Alpha. From understanding the mathematical underpinnings of the CCI to appreciating the robust features of Build Alpha, we've covered significant ground.

We also developed what appears to be a fully working algorithmic strategy for the NG market. Do you want a copy of the code? Jump to the bottom of this article to see how to get a copy.

The CCI, with its roots in the commodities market, offers traders a unique lens to view market momentum and potential price reversals. Its adaptability across various asset classes, including the NG futures market, makes it a versatile tool in a trader's arsenal. But as with any indicator, its true potential shines when integrated into a comprehensive trading strategy.

Enter Build Alpha, a game-changer in the realm of algorithmic trading. Its ability to craft, test, and optimize strategies without the need for programming is nothing short of revolutionary. For traders like us, who are constantly seeking an edge in the markets, Build Alpha provides the tools and framexwork to turn our trading ideas into actionable strategies.

As we wrap up, I want to leave you with a few thoughts. The world of trading is ever-evolving, with new tools and techniques emerging regularly. But the core principles remain the same: knowledge, discipline, and continuous learning. The CCI and Build Alpha are just two pieces of the puzzle. It's up to us, the traders, to fit these pieces together, creating a trading mosaic that aligns with our goals and risk tolerance.

Thank you for joining me on this exploration. I hope you've found it enlightening and that it sparks further curiosity and experimentation in your trading journey. Remember, at EasyLanguage Mastery, our mission is to empower you with the knowledge and tools to excel in the world of algorithmic trading. Let's continue this journey together, one trade at a time.

Get A Copy of Build Alpha

You can get a copy of Build Alpha over at the Build Alpha website. Let them know you read about Build Alpha here at EasyLanguage Mastery.

Let Me Show You How To Use Build Alpha

I have an exciting announcement for those eager to elevate their trading game with Build Alpha. Introducing the Alpha Compass course – a meticulously crafted program designed to navigate you through the complexities of Build Alpha. Whether you're a novice finding your way or an experienced trader aiming to refine your strategies, the Alpha Compass well help.

Enrollment is open this week! However, do note that doors close on Thursday, September 28th.

Click Here To Learn More

Here are some Build Alpha links

]]>
https://easylanguagemastery.com/strategies/building-a-cci-strategy-with-build-alpha/feed/ 0
Enhancing the 2-Period RSI2 on Indexes Using the VIX Futures Market – an RSI trading strategy https://easylanguagemastery.com/strategies/enhancing-the-2-period-rsi2-on-indexes-using-the-vix-futures-market-an-rsi-trading-strategy/?utm_source=rss&utm_medium=rss&utm_campaign=enhancing-the-2-period-rsi2-on-indexes-using-the-vix-futures-market-an-rsi-trading-strategy https://easylanguagemastery.com/strategies/enhancing-the-2-period-rsi2-on-indexes-using-the-vix-futures-market-an-rsi-trading-strategy/#respond Mon, 11 Sep 2023 10:00:00 +0000 https://easylanguagemastery.com/?p=532869

Table of Contents

Introduction

In the book “Short Term Trading Strategies That Work” by Larry Connors and Cesar Alvarez, a widely used entry strategy for Index markets is discussed, which takes advantage of the index mean reversion edge through the 2-period RSI. This RSI trading strategy involves going long only when the 2-period RSI falls below an oversold limit. In this article, we will explore whether the RSI works in different timeframes and index markets, and we will use the Volatility Index (VIX) as a filter to enhance the strategy.

To establish a reference point, let’s consider a random pick from the ES market:

Market: @ES
Timeframe: 120 mins.
Entry RSI2 crosses below 20. (Long only).
Stop loss: $1500.
Profit target: $1500.
Slippage: $12.5 per contract.
Commission: $2.5 per trade.

Based on the above parameters, the results are as follows:

Net Profit:$87.977
Avg Trade:$69.7
Trades:1.262
Profit Factor:1,10
Max DD:$37.282

We could say there is an edge, but it can be further improved to increase its effectiveness by reducing the number of trades. In order to achieve this, I want to use the VIX as a filter.

Why VIX?

Let’s explore its definition:

 “The Cboe Volatility Index (VIX) is a real-time index that represents the market’s expectations for the relative strength of near-term price changes of the S&P 500 Index (SPX). Because it is derived from the prices of SPX index options with near-term expiration dates, it generates a 30-day forward projection of volatility. Volatility, or how fast prices change, is often seen as a way to gauge market sentiment, and in particular the degree of fear among market participants.

The index is more commonly known by its ticker symbol and is often referred to simply as “the VIX.” It was created by the Cboe Options Exchange (Cboe) and is maintained by Cboe Global Markets. It is an important index in the world of trading and investment because it provides a quantifiable measure of market risk and investors’ sentiments.”

Source: https://www.investopedia.com/terms/v/vix.asp

As we can see from the definition, incorporating the VIX in our strategy allows us to leverage market sentiment as a filtering mechanism. To achieve this, we will consider the following cases:

  • Case 1: High of the VIX is higher than X bars ago.
  • Case 2: High of the VIX is lower than X bars ago.
  • Case 3: VIX RSI of X number bars ago is greater than 50.
  • Case 4: VIX RSI of X number bars ago is lower than 50.
  • Case 5: VIX RSI of X number bars ago is greater than 80.
  • Case 6: VIX RSI of X number bars ago is lower than 20.

Considerations

Charting Software: TradeStation 10.0.

Code development language: Easylanguage 10.0.

Code Considerations:

  • Entries type: 
    • Long only.
  • Entries Direction: 
    • Mean Reversion.
  • Exits:
    • Stop Loss
    • Profit Target: Stop Loss 
  • Trigger:
    • Long when Close crosses below Oversold.
    • VIX Filter on data 2

First approach

OK, now that the code is ready, let’s add Data2 to our reference strategy:

And look for the following cases and parameters:

Results

 RSI2RSI2 + VIX filters
Net Profit:$87.977$77.862
Avg Trade:$69.7$140.29
Trades:1.262555
Profit Factor:1,101.21
Max DD:$37.282$17.862

The more effective filter case is number 4: where the RSI of the VIX with 7 bars back is above 50, even if the net profit is reduced, the strategy is more effective in reducing more than half of the trades, duplicating the average per trade and reducing the drawdown by $20.000. 

After seeing the improvement of the strategy, some questions arise:

  • Will it work in another timeframe?
  • Will it work on other Index futures markets?
  • What will happen if the VIX has a different timeframe from the primary Market?

This research will take me a considerable big amount of time to do it manually, so what better tool than Tradesq to help me out.

Applying Tradesq

Tradesq has been chosen as a Futures trading system research tool.

On Tradesq, I will enter the code, and on Data1, select the four main Index futures markets: 

@ES: E-MINI S&P 500.

@NQ: E-MINI NASDAQ 100.

@RTY: E-MINI RUSSELL 2000.

@YM: E-MINI DOW 30.

11 timeframes, from 15 minutes to daily.

For Data 2, the market will be @VX, and timeframes from 15 minutes to daily.

Results

After a few hours, we obtained results based on the following criteria:

Nasdaq 60min

Data1: Nasdaq (@NQ) 60min

Data2: VIX (@VX) 180min

ES 120min

Data1: S&P (@ES) 120min

Data2: VIX (@VX) Daily

YM 60min

Data1: DOW (@YM) 60min

Data2: VIX (@VX) 60min

YM 120min

Data1: RTY (@YM) 120min

Data2: VIX (@VX) 1440min

Note: All results include trading costs, Slippage, and Commission.

Conclusion

Incorporating the VIX as a filter has significantly improved the RSI trading strategy’s performance across different timeframes and Index futures markets. The results show promising potential and further research and testing can be conducted to refine and optimize the strategy.

>> By Juan Fernando Gómez from blog blog.tradesq.net

]]>
https://easylanguagemastery.com/strategies/enhancing-the-2-period-rsi2-on-indexes-using-the-vix-futures-market-an-rsi-trading-strategy/feed/ 0
The ES 500 (Futures) Seasonal Day Trade https://easylanguagemastery.com/strategies/the-es-500-futures-seasonal-day-trade/?utm_source=rss&utm_medium=rss&utm_campaign=the-es-500-futures-seasonal-day-trade https://easylanguagemastery.com/strategies/the-es-500-futures-seasonal-day-trade/#comments Mon, 13 Feb 2023 11:00:00 +0000 https://easylanguagemastery.com/?p=531347

Complete Strategy based on Sheldon Knight and William Brower Research

In my Easing Into EasyLanguage:  Hi-Res Edition, I discuss the famous statistician and trader Sheldon Knight and his  K-DATA Time Line.  This time line enumerated each day of the year using the following nomenclature:

First Monday in December = 1stMonDec

Second Friday in April = 2ndFriApr

Third Wednesday in March = 3rdWedMar

This enumeration or encoding was used to determine if a certain week of the month and the day of week held any seasonality tendencies.  If you trade index futures you are probably familiar with Triple Witching Days.

Four times a year, contracts for stock options, stock index options, and stock index futures all expire on the same day, resulting in much higher volumes and price volatility. While the stock market may seem foreign and complicated to many people, it is definitely not “witchy”, however, it does have what is known as “triple witching days.”

Triple witching, typically, occurs on the third Friday of the last month in the quarter. That means the third Friday in March, June, September, and December. In 2022, triple witching Friday are March 18, June 17, September 16, and December 16

Other days of certain months also carry significance.  Some days, such as the first Friday of every month (employment situation), carry even more significance.   In 1996, Bill Brower wrote an excellent article in Technical Analysis of Stocks and Commodities.  The title of the article was The S&P 500 Seasonal Day Trade.  In this article, Bill devised 8 very simple day trade patterns and then filtered them with the Day of Week in Month.  Here are the eight patterns as he laid them out in the article.

  1. Pattern 1:  If tomorrow’s open minus 30 points is greater than today’s close, then buy at market.
  2. Pattern 2:  If tomorrow’s open plus 30 points is less than today’s close, then buy at market.
  3. Pattern 3:  If tomorrow’s open minus 30 points is greater than today’s close, then sell short at market.
  4. Pattern 4:  If tomorrow’s open plus 30 points is less than today’s close, then sell short at market.
  5. Pattern 5:  If tomorrow’s open plus 10 points is less than today’s low, then buy at market.
  6. Pattern 6:  If tomorrow’s open minus 20 points is greater than today’s high, then sell short at today’s close stop.
  7. Pattern 7:  If tomorrow’s open minus 40 points is greater than today’s close, then buy at today’s low limit.
  8. Pattern 8:  If tomorrow’s open plus 70 points is less than today’s close, then sell short at today’s high limit.

This article was written nearly 27 years ago when 30 points meant something in the S&P futures contract.   The S&P was trading around the 600.00 level.  Today the  e-mini S&P 500 (big S&P replacement) is trading near 4000.00 and has been higher.  So 30, 40 or 70 points doesn’t make sense.  To bring the patterns up to date, I decided to use a percentage of ATR in place of a single point.  If today’s range equals 112.00 handles or in terms of points 11200 and we use 5%, then the basis would equate to 11200 = 560 points or 5.6 handles.  In the day of the article the range was around 6 handles or 600 points.  So. I think using 1% or 5% of ATR could replace Bill’s point values.  Bill’s syntax was a little different than the way I would have described the patterns.  I would have used this language to describe Pattern1

– If tomorrow’s open is greater than today’s close plus 30 points, then buy at market – its easy to see we are looking for a gap open greater than 30 points here.  Remember there is more than one way to program an idea.  Let’s stick with Bills syntax.

  • 10 points = 1 X (Mult)  X ATR
  • 20 points = 2 X (Mult)  X ATR
  • 30 points = 3 X (Mult)  X ATR
  • 40 points = 4 X (Mult)  X ATR
  • 50 points = 5 X (Mult)  X ATR
  • 70 points =7 X (Mult)  X ATR

We can play around with the Mult to see if we can simulate similar levels back in 1996.

// atrMult will be a small percentage like 0.01 or 0.05
atrVal = avgTrueRange(atrLen) * atrMult;

//original patterns
//use IFF function to either returne a 1 or a 0
//1 pattern is true or 0 it is false

patt1 = iff(open of tomorrow - 3 * atrVal > c,1,0);
patt2 = iff(open of tomorrow + 3 * atrVal < c,1,0);
patt3 = iff(open of tomorrow - 3 * atrVal > c,1,0);
patt4 = iff(open of tomorrow + 3 * atrVal < c,1,0);
patt5 = iff(open of tomorrow + 1 * atrVal < l,1,0);
patt6 = iff(open of tomorrow - 2 * atrVal > h,1,0);
patt7 = iff(open of tomorrow - 4 * atrVal > c,1,0);
patt8 = iff(open of tomorrow + 7 * atrVal < c,1,0);

William Brower’s DoWInMonth Enumeration

The Day of Week In A Month is represented by a two digit number.  The first digit is the week rank and the second number is day of the week.  I thought this to be very clever, so I decided to program it.    I approached it from a couple of different angles and I actually coded an encoding method that included the week rank, day of week, and month (1stWedJan) in my Hi-Res Edition.   Bill’s version didn’t need to be as sophisticated and since I decided to use TradeStation’s optimization capabilities I didn’t need to create a data structure to store any data.  Take a look at the code and see if it makes a little bit of sense.

newMonth = False;
newMonth = dayOfMonth(d of tomorrow) < dayOfMonth(d of today);
atrVal = avgTrueRange(atrLen) * atrMult;
if newMonth then
begin
startTrading = True;
monCnt = 0;
tueCnt = 0;
wedCnt = 0;
thuCnt = 0;
friCnt = 0;
weekCnt = 1;

end;

if not(newMonth) and dayOfWeek(d of tomorrow) < dayOfWeek(d of today) then
weekCnt +=1;

dayOfWeekInMonth = weekCnt * 10 + dayOfWeek(d of tomorrow);

Simple formula to week rank and DOW

NewMonth is set to false on every bar.  If tomorrow’s day of month is less than today’s day of month, then we know we have a new month and newMonth is set to true.  If we have a new month, then several things take place: reinitialize the code that counts the number Mondays, Tuesdays, Wednesdays, Thursdays and Fridays to 0 (not used for this application but can be used later,) and set the week count weekCnt to 1.  If its not a new month and the day of week of tomorrow is less than the day of the week today (Monday = 1 and Friday = 5, if tomorrow is less than today (1 < 5)) then we must have a new week on tomorrow’s bar.  To encode the day of week in month as a two digit number is quite easy – just multiply the week rank (or count) by 10 and add the day of week (1-Monday, 2-Tuesday,…)  So the third Wednesday would be equal to 3X10+3 or 33.

Use Optimization to Step Through 8 Patterns and 25 Day of Week in Month Enumerations

Stepping through the 8 patterns is a no brainer.  However, stepping through the 25 possible DowInAMonth codes or enumerations is another story.  Many times you can use an equation based on the iterative process of going from 1 to 25.  I played around with this using the modulus function, but decided to use the Switch-Case construct instead.  This is a perfect example of replacing math with computer code.  Check this out.

switch(dowInMonthInc)
begin
case 1 to 5:
value2 = mod(dowInMonthInc,6);
value3 = 10;
case 6 to 10:
value2 = mod(dowInMonthInc-5,6);
value3 = 20;
case 11 to 15:
value2 = mod(dowInMonthInc-10,6);
value3 = 30;
case 16 to 20:
value2 = mod(dowInMonthInc-15,6);
value3 = 40;
case 21 to 25:
value2 = mod(dowInMonthInc-20,6);
value3 = 50;
end;

Switch-Case to Step across 25 Enumerations

Here we are switching on the input (dowInMonthInc).  Remember this value will go from 1 to 25 in increments of 1. What is really neat about EasyLanguage’s implementation of the Switch-Case is that it can handle ranges.  If the dowInMonthInc turns out to be 4 it will fall within the first case block (case 1 to 5).  Here we know that if this value is less than 6, then we are in the first week so I set the first number in the two digit dayOfWeekInMonth representation to 1.  This is accomplished by setting value3 to 10.  Now you need to extract the day of the week from the 1 to 25 loop.  If the dowInMonthInc is less than 6, then all you need to do is use the modulus function and the value 6.

  • mod(1,6)  = 1
  • mod(2,6) = 2
  • mod(3,6) = 3

This works great when the increment value is less than 6.  Remember:

  • 1 –> 11 (first Monday)
  • 2 –> 12 (first Tuesday)
  • 3 –> 13 (first Wednesday)
  • 6 –> 21 (second Monday)
  • 7 –> 22 (second Tuesday).

So, you have to get a little creative with your code.  Assume the iterative value is 8.  We need to get 8 to equal 23 (second Wednesday).  This value falls into the second case, so Value3 = 20 the second week of the month.  That is easy enough.  Now we need to extract the day of week – remember this is just one solution, I guarantee there are are many.

mod(dowInMonthInc – 5, 6) – does it work?

value2 = mod(8-5,6) = 3 -> value3 = value1  +  value2 -> value3 = 23.  It worked.   Do you see the pattern below.

  • case   6 to 10 – mod(dowInMonthInc –  5, 6)
  • case 11 to 15 – mod(dowInMonthInc – 10, 6)
  • case 16 to 20- mod(dowInMonthInc – 15, 6)
  • case 21 to25 – mod(dowInMonthInc – 20, 6)

Save Optimization Report as Text and Open with Excel

Here are the settings that I used to create the following report.  If you do the math that is a total of 200 iterations.

Seasonal Day Trader Settings

I opened the Optimization Report and saved as text.  Excel had no problem opening it.

Optimization results output to Excel and cleaned up.

I created the third column by translating the second column into our week of month and day of week vernacular. These results were applied to 20 years of ES.D (day session data.) The best result was Pattern #3 applied to the third Friday of the month (35.) Remember the 15th DowInMonthInc equals the third (3) Friday (5). The top patterns predominately occurred on a Thursday or Friday.

Here is the complete code for you to play with.

inputs: atrLen(10),atrMult(.05),patternNum(1),dowInMonthInc(1);

vars: patt1(0),patt2(0),patt3(0),patt4(0),
patt5(0),patt6(0),patt7(0),patt8(0);

vars: atrVal(0),dayOfWeekInMonth(0),startTrading(false),newMonth(False);;

vars: monCnt(0),tueCnt(0),wedCnt(0),thuCnt(0),friCnt(0),weekCnt(0);

newMonth = False;
newMonth = dayOfMonth(d of tomorrow) < dayOfMonth(d of today);
atrVal = avgTrueRange(atrLen) * atrMult;
if newMonth then
begin
startTrading = True;
monCnt = 0;
tueCnt = 0;
wedCnt = 0;
thuCnt = 0;
friCnt = 0;
weekCnt = 1;
end;

if not(newMonth) and dayOfWeek(d of tomorrow) < dayOfWeek(d of today) then
weekCnt +=1;
dayOfWeekInMonth = weekCnt * 10 + dayOfWeek(d of tomorrow);

//print(date," ", dayOfMonth(d)," " ,dayOfWeek(d)," ",weekCnt," ",monCnt," ",dayOfWeekInMonth);

//original patterns

patt1 = iff(open of tomorrow - 3 * atrVal > c,1,0);
patt2 = iff(open of tomorrow + 3 * atrVal < c,1,0);
patt3 = iff(open of tomorrow - 3 * atrVal > c,1,0);
patt4 = iff(open of tomorrow + 3 * atrVal < c,1,0);
patt5 = iff(open of tomorrow + 1 * atrVal < l,1,0);
patt6 = iff(open of tomorrow - 2 * atrVal > h,1,0);
patt7 = iff(open of tomorrow - 4 * atrVal > c,1,0);
patt8 = iff(open of tomorrow + 7 * atrVal < c,1,0);

switch(dowInMonthInc)
begin
case 1 to 5:
value2 = mod(dowInMonthInc,6);
value3 = 10;
case 6 to 10:
value2 = mod(dowInMonthInc-5,6);
value3 = 20;
case 11 to 15:
value2 = mod(dowInMonthInc-10,6);
value3 = 30;
case 16 to 20:
value2 = mod(dowInMonthInc-15,6);
value3 = 40;
case 21 to 25:
value2 = mod(dowInMonthInc-20,6);
value3 = 50;
end;
value1 = value3 + value2 ;

//print(d," ",dowInMonthInc," ",dayOfWeekInMonth," ",value1," ",value2," ",value3," ",mod(dowInMonthInc,value2));

if value1 = dayOfWeekInMonth then
begin
if patternNum = 1 and patt1 = 1 then buy("Patt1") next bar at open;
if patternNum = 2 and patt2 = 1 then buy("Patt2") next bar at open;
if patternNum = 3 and patt3 = 1 then sellShort("Patt3") next bar at open;
if patternNum = 4 and patt4 = 1 then sellShort("Patt4") next bar at open;
if patternNum = 5 and patt5 = 1 then buy("Patt5") next bar at low limit;
if patternNum = 6 and patt6 = 1 then sellShort("Patt6") next bar at close stop;
if patternNum = 7 and patt7 = 1 then buy("Patt7") next bar at low limit;
if patternNum = 8 and patt8 = 1 then sellShort("Patt8") next bar at high stop;
end;
setExitOnClose;

The Full Monty of the ES-Seasonal-Day Trade

I think this could provide a means to much more in-depth analysis.  I think the Patterns could be changed up.  I would like to thank William (Bill) Brower for his excellent article, The S&P Seasonal Day Trade in Stocks and Commodities, August 1996 Issue, V.14:7 (333-337).  The article is copyright by Technical Analysis Inc.  For those not familiar with Stocks and Commodities check them out at https://store.traders.com/

Please email me with any questions or anything I just got plain wrong.  George

>>By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/strategies/the-es-500-futures-seasonal-day-trade/feed/ 4
Why You Should Become A Algorithmic Trader https://easylanguagemastery.com/strategies/why-you-should-become-a-algorithmic-trader/?utm_source=rss&utm_medium=rss&utm_campaign=why-you-should-become-a-algorithmic-trader https://easylanguagemastery.com/strategies/why-you-should-become-a-algorithmic-trader/#respond Mon, 21 Nov 2022 11:00:00 +0000 https://easylanguagemastery.com/?p=530874

Did you know that algorithmic trading can help transform you into a winning trader? A winning trader means many things. First, it means brining consistency to your trading. Taking each trade when a setup occurs. Managing the trade without emotion. Following your trading plan 100%. It also means, finding and exploiting market edges that generate income.

Well, with algorithmic trading, you can become a winning trader. There are several reasons why you should consider becoming an algorithmic trader. This blog post will explore some of these reasons and look at how you can get started as an algorithmic trader. First, what is an algorithmic trader?

What is an algorithmic trader? 

An algorithmic trader is a person who uses a computer to trade stocks, options, futures, or other financial instruments. This trading computer is programmed with a set of instructions on when to place trades in the market. But it can do even more. It will manage those open position exactly to your specification. In short, an algorithmic trader will program a computer with his custom trading plan and the computer will execute that plan.

Algorithmic trading has become increasingly popular recently. TradeStation and other platforms have made it easier for traders to develop and deploy their algorithms from their home computers. It's allowing for the retail trader, to take advantage of all the benefits of algorithmic trading.

Let's look at those benefits now.

Remove emotion from your trading.

Humans are not logical creatures. They make poor financial choices when money is on the line. I'm sure you're aware of this pheonoma. How many costly mistakes do you make trading on a weekly or monthly basis? I know I've made my fair share.

It's been shown that people are more likely to sell stocks after a market crash and buy after a rally. Often this is the complete opposite of what you should do. Using emotion often leads to impulsive decisions that can be costly.

When you trade using algorithms, a computer follows your trading rules based on logic and data rather than emotions.  Algorithmic traders have the computer to decide when to buy and sell. When the computer makes all the decisions, algorithmic traders can remove much of the emotion from their trading decisions, leading to more successful trades.

When you take emotion out of trading, you can make better financial decisions. You're not worried about the next trade. You're not worried about making money. You're not worried about losing money. You're following a plan that you've backtested and you have confidence in.

Do more! Faster! 

Algorithmic trading can allow you to scale your trading operations. If you manually trade stocks, options, or other financial instruments, there is only so much you can do in a day. However, if you use algorithms to place trades, you can increase the number of trades you make in a day without increasing the amount of time you spend doing so. You can trade 10, 20 or more markets at the same time. Try doing that without the help of a computer.

I may have 10 active trades open at one time and will feel comfortable stepping away to use the bathroom or have lunch. I'm not saying I walk away from my trading computer for hours. But when I step away for a bit, I have confidence that everything is being managed fine.

Algorithmic traders also have the edge over traditional traders because they can make trades faster and more efficiently. When you manually place a trade, it can take time to enter all the necessary information into the system. However, the trade can be executed automatically and with greater speed when you use an algorithm.

Discover what works and what does not work

For algorithmic traders, backtesting is an essential tool that can help to determine the profitability of a trading system. Backtesting is the process of simulating how a system would have performed in the past, using historical price data. This allows traders to see how the system would have fared under different market conditions. By backtesting a system, traders can identify its strengths and weaknesses, and make refinements as needed.

Additionally, you can backtest indicators, price patterns and other market observations to see if they hold any market edge. Discovered a new indicator on a blog post? You can quickly backtest that indicator on your favorite market and see if it's worth keeping. Ultimately, backtesting can be a valuable tool in helping traders to become more profitable.

How do I become an algorithmic trader? 

I enjoy the process of building my trading systems. It's not for everyone. You have to like working with computers, testing ideas, and performing experiments on the market. In short, you must put a lot of time into the endeavor.

Algorithmic traders are a special breed of traders. They require a unique set of skills and knowledge in order to be successful. Here are some of the skills you'll need to become an algorithmic trader:

  • Comfortable with computer coding. Algorithmic traders need to be able to understand and develop trading system using a computer language. You should know how to program a computer, be comfortable with computers and have a willingness to learn.
  • An understanding of basic statistics would help.
  • The ability to think creatively. Algorithmic traders need to be able to see the market from different angles and come up with new ideas for how to trade. Must have a willingness to try new idea.

If you're interested in becoming an algorithmic trader, the first thing you should do is start learning about programming. I recommend downloading the TradeStation platform and learning to code using their coding language, EasyLanguage. TradeStation is one of the most popular platforms for algorithmic trading for retail traders like you and me. TradeStation comes with EasyLanguage, which allows traders to create algorithmic trading systems. Here is an article on why EasyLanguage is excellent for beginner algo traders.

TradeStation also provides backtesting capabilities so that traders can test their strategies before putting them into live trading. Many online resources can help you learn more about TradeStation and EasyLanguage. That's actually why my website, EasyLanguage Mastery, exists. To help you learn EasyLanguage so you can become a successful algorithmic trader.

Conclusion

Algorithmic trading is a process whereby traders use computers to place trades faster and more efficiently than if they were to do so manually. Backtesting is an essential tool for algorithmic traders, which allows them to simulate how a system would have performed in the past using historical price data. By backtesting a system, traders can identify its strengths and weaknesses and make refinements as needed. Ultimately, backtesting can be a valuable tool in helping traders to become more profitable.

If you are interested in becoming an algorithmic trader, your first task is to learn how to code. TradeStation is one of the most popular platforms for algorithmic trading and provides backtesting capabilities so that traders can test their strategies before putting them into live trading. EasyLanguage is the coding language used by TradeStation and is excellent for beginner algo traders. You can learn more about TradeStation and EasyLanguage through online resources like my website, EasyLanguage Mastery.

FAQ

What is an algorithmic trader?
An algorithmic trader is a trader who uses computer algorithms to place trades automatically.

What is backtesting?
Backtesting is the process of simulating how a system would have performed in the past, using historical price data. This allows traders to see how the system would have fared under different market conditions.

How do I become an algorithmic trader?
If you are interested in becoming an algorithmic trader, your first task is to learn how to code. TradeStation is one of the most popular platforms for algorithmic trading and comes with the EasyLanguage programming language.

What skills do I need to be an algorithmic trader?
You will need to be good with computers and have an aptitude for working with code. In addition, you must be comfortable with performing experiments and testing ideas on the market. Your first step is to learn a computer language. I recommend, EasyLanguage.

]]>
https://easylanguagemastery.com/strategies/why-you-should-become-a-algorithmic-trader/feed/ 0
The Journey https://easylanguagemastery.com/strategies/the-journey/?utm_source=rss&utm_medium=rss&utm_campaign=the-journey https://easylanguagemastery.com/strategies/the-journey/#respond Mon, 29 Aug 2022 10:00:00 +0000 http://systemtradersuccess.com/?p=14161

“The journey, Not the destination matters...” ― T.S. Eliot

You might be wondering what the Nobel Prize winning poet, T.S. Eliot has to do with trading. No, he did not leave a secret trading manual in his attic for his grandchildren to stumble upon. And I’m guessing he did not even trade – he was too busy creating immortal prose.

Yet, his quote, “The journey, Not the destination matters...” has profound implications for us as traders. Let me explain…

What if I told you of a Soybean Oil strategy that earned nearly $40,000 in single contract profits in five years? That is $8,000 profit per contract each year. Would you want to trade it?

Right now, margin on Soybean Oil is $660, so you might determine you could trade 1 contract of this strategy with $2,500. So, in five years, your $2,500 would turn into $42,500, which is a compounded annual growth rate of over 76%. Per year!

At first blush, who would not want that?  

The problem is that it's where most traders stop their analysis. They see the start point, and they see the end point five years later, with bags of cash awaiting them. They jump for joy at their performance, and rush to trade the strategy live.

Of course, our friend T.S. Eliot would disagree. He would argue that the journey during those five years, not just the end point, is what really matters.

So what does that journey look like? Here it is:

The end profit is there, sure enough. But look at what we had to endure to get there! A maximum drawdown of $9,000, numerous quick and steep equity collapses, extended flat periods – UGH!

The final profit says this is a nice strategy, but the path to get there is brutal. In other words, the journey is really important. Unfortunately, too many traders ignore that.

Psychologically, this strategy would be practically impossible to trade. Pretend you are trading this strategy, and just imagine yourself at the following point on the equity curve:

What would you be thinking? Most people probably would have quit even before this point, but how much confidence would you have right now? Realistically, you’d have zero confidence that this strategy would ever turn around. Yet, from that point on, that is exactly what the strategy did – its performance took off from that point.

Hopefully, this simple example makes it clear that the path of an equity curve is critical. You can’t enjoy the riches at the end if you cannot stomach the road to get there.

So, how can you take this into account with your own trading? Here are a few simple tips:

  1. When reviewing a Performance Report, make sure you look at more than just the Net Profit. Make sure you look at the max drawdown and any drawdown curves – could you handle the drawdowns? My rule of thumb is that I can mentally handle about half the maximum drawdown that I think I can handle. So, if I think I can handle a $10,000 drawdown, and the system has an $8,000 maximum drawdown, chances are I won’t be able to endure it. In that case, I probably should not trade such a strategy.
  2. You can employ my free Monte Carlo simulator for Excel (see below) to determine the drawdown, profit/drawdown and other statistics for any strategy. This is a simple, but powerful way to see if the risk adjusted return is appropriate for you. I throw away many great profit strategies because the drawdowns are just too severe, and the risk adjusted return is just too low.
  3. Take the equity curve, print it on a piece of paper, then get another piece of paper and cover it up. Slowly reveal the developing equity curve, moving left to right, and imagine yourself at each point along the curve. Try to experience what you would feel at each point. This is hard to do, especially when you know the positive end result, but if you do it correctly, it can be very enlightening.

To wrap up, always remember that the end result of a trading strategy is usually not the most important part. The path matters – a lot.

]]>
https://easylanguagemastery.com/strategies/the-journey/feed/ 0
A Tribute To Murray And His Inter-Market Research https://easylanguagemastery.com/strategies/a-tribute-to-murray-and-his-inter-market-research/?utm_source=rss&utm_medium=rss&utm_campaign=a-tribute-to-murray-and-his-inter-market-research https://easylanguagemastery.com/strategies/a-tribute-to-murray-and-his-inter-market-research/#respond Mon, 01 Aug 2022 10:00:00 +0000 https://easylanguagemastery.com/?p=529892

Murray Ruggiero’s Inter-Market Research

Well it’s been a year, this month, that Murray passed away.  I was fortunate to work with him on many of his projects and learned quite a bit about inter-market convergence and divergence.  Honestly, I wasn’t that into it, but you couldn’t argue with his results.  A strategy that he developed in the 1990s that compared the Bond market with silver really did stand the test of time.  He monitored this relationship over the years and watched in wane.  Murray replaced silver with $UTY.

The PHLX Utility Sector Index (UTY) is a market capitalization-weighted index composed of geographically diverse public utility stocks.

He wrote an article for EasyLanguage Mastery by Jeff Swanson where he discussed this relationship and the development of inter-market strategies and through statistical analysis proved that these relationships added real value.

I am currently writing Advanced Topics, the final book in my Easing Into EasyLanguage trilogy, and have been working with Murray’s research.  I am fortunate to have a complete collection of his Futures Magazine articles from the mid 1990s to the mid 2000s.  There is a quite a bit of inter-market stuff in his articles.  I wanted, as a tribute and to proffer up some neat code, to show the performance and code of his Bond and $UTY inter-market algorithm.

Here is a version that he published a few years ago updated through June 30, 2022 – no commission/slippage.

Murray’s Bond and $UTY inter-market Strategy

Not a bad equity curve.  To be fair to Murray he did notice the connection between $UTY and the bonds was changing over the past couple of year.  And this simple stop and reverse system doesn’t  have a protective stop.   But it wouldn’t look much different with one, because the system looks at momentum of the primary  data and momentum of the secondary data and if they are in synch (either positively or negatively correlated – selected by the algo) an order is fired off.  If you simply just add a protective stop, and the momentum of the data are in synch, the strategy will just re-enter on the next bar.  However, the equity curve just made a new high  recently.  It has got on the wrong side of the Fed raising rates.  One could argue that this invisible hand has toppled the apple cart and this inter-market relationship has been rendered meaningless.

Murray had evolved his inter-market analysis to include state transitions.  He not only looked at the current momentum, but also at where the momentum had been.  He assigned the transitions of the momentum for the primary and secondary markets a value from one to four and he felt this state transition helped overcome some of the coupling/decoupling of the inter-market relationship.

However,  I wanted to test Murray’s simple strategy with a fixed $ stop and force the primary market to move from positive to negative or negative to positive territory while the secondary market is in the correct relationship.  Here is an updated equity curve.

George’s Adaptation and using a $4500 stop loss

This equity curve was developed  by using a $4500 stop loss.  Because I changed the order triggers, I reoptimized the length of the momentum calculations for the primary and secondary markets.  This curve is only better in the category of maximum draw down.  Shouldn’t we give Murray a chance and reoptimize his momentum length calculations too!  You bet.

Murray Length Optimizations

These metrics were sorted by Max Intraday Draw down.  The numbers did improve, but look at the Max Losing Trade value.  Murray’s later technology,  his State Systems, were a great improvement over this basic system.  Here is my optimization using a slightly different entry technique and a $4500 protective stop.

Standing on the Shoulders of a Giant

This system, using Murray’s overall research, achieved a better Max Draw Down and a much better Max Losing Trade.   Here is my code using the template that Murray provided in his articles in Futures Magazine and EasyLanguage Mastery.

// Code by Murray Ruggiero
// adapted by George Pruitt

Inputs: InterSet(2),LSB(0),Type(1),LenTr(4),LenInt(4),Relate(0);
Vars: MarkInd(0),InterInd(0);

If Type=0 Then
Begin
InterInd=Close of Data(InterSet)-CLose[LenInt] of Data(InterSet);
MarkInd=CLose-CLose[LenTr];
end;

If Type=1 Then
Begin
InterInd=Close of Data(InterSet)-Average(CLose of Data(InterSet),LenInt);
MarkInd=CLose-Average(CLose,LenTr);
end;

if Relate=1 then
begin
If InterInd > 0 and MarkInd CROSSES BELOW 0 and LSB>=0 then
Buy("GO--Long") Next Bar at open;
If InterInd < 0 and MarkInd CROSSES ABOVE 0 and LSB<=0 then
Sell Short("GO--Shrt") Next Bar at open;

end;
if Relate=0 then begin
If InterInd<0 and MarkInd CROSSES BELOW 0 and LSB>=0 then
Buy Next Bar at open;
If InterInd>0 and MarkInd CROSSES ABOVE 0 and LSB<=0 then
Sell Short Next Bar at open;
end;

Here the user can actually include more than two data streams on the chart.  The InterSet input allows the user to choose or optimize the secondary market data stream.  Momentum is defined by two types:

  • Type 0:  Intermarket or secondary momentum simply calculated by close of data(2) – close[LenInt] of date(2) and primary momentum calculated by close – close[LenTr]
  • Type 1:   Intermarket or secondary momentum  calculated by close of data(2) – average( close of data2, LenInt)  and primary momentum calculated by close – average(close, LenTr)

The user can also input what type of Relationship: 1 for positive correlation and 0 for negative correlation.  This template can be used to dig deeper into other market relationships.

George’s Modification

I simply forced the primary market to CROSS below/above 0 to initiate a new trade as long the secondary market was pointing in the right direction.

If InterInd > 0 and MarkInd CROSSES BELOW 0 and LSB>=0 then Buy("GO--Long") Next Bar at open;If InterInd < 0 and MarkInd CROSSES ABOVE 0 and LSB<=0 then Sell Short("GO--Shrt") Next Bar at open;

Using the keyword CROSSES

This was a one STATE transition and also allowed a protective stop to be used without the strategy automatically re-entering the trade in the same direction.

Thank You Murray – we sure do miss you!

Murray loved to share his research and would want us to carry on with it.  I will write one or two blogs a year in tribute to Murray and his invaluable research.

>> By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/strategies/a-tribute-to-murray-and-his-inter-market-research/feed/ 0
Using RSI And VIX To Profit In A Bear Market https://easylanguagemastery.com/strategies/inverting-the-rsi-and-vix-strategy/?utm_source=rss&utm_medium=rss&utm_campaign=inverting-the-rsi-and-vix-strategy https://easylanguagemastery.com/strategies/inverting-the-rsi-and-vix-strategy/#comments Mon, 06 Jun 2022 10:00:30 +0000 http://systemtradersuccess.com/?p=6299

In this article, I will reverse the trading rules on a long-only trading system and see if we can build a profitable shorting trading system. Let's do this and see if any edge awaits us.

As pointed out in a previous article, "Profit By Combing RSI and VIX", combining RSI and VIX can be a profitable strategy for trading the S&P. If you're not familiar with this simple yet powerful strategy, please take a look at the previous article first. 

Shortly after the original article was posted, a reader asked what this strategy would look like if we reversed the rules and took short positions.

It's an exciting idea and something I've not tested in many years. Here's why... 

First of all, I'm not a big fan of long/short symmetry with trading systems, and the difference between market psychology between bull and bear market participants can be huge. Thus, simply reversing long-only rules to trade the short side is often ineffective. This may not always be true, but it has been my general observation.

Furthermore, based on past testing, I recall that many Connor's RSI strategies don't do so well trading the short side. However, it's still a great idea to test.

The Original Rules (Long Only)

As a reminder here are the original rules for taking long trades:

  • Price must be above its 200-day moving average
  • RSI(2) on price must be below 30
  • Buy when RSI(2) of the VIX is above 90
  • Exit when RSI(2) of the price rises above 65

Environmental Settings

Note I will be trading the E-mini S&P. 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 30, 2022.
  • There are no deductions for commissions and slippage.
  • There are no stops.

Below is the equity curve of the original trading rules as provided above.

Original rules. Long only during bull market.

The results are promising but not great mainly due to the significant drawdown. Of course, this strategy has no stops, so adding a hard stop can mitigate that. The important thing to note is that the equity curve rises from left to right and continues to make new equity highs into 2022.

Now, let's take the trading rules and invert them. We'll attempt to take short trades during a bear market. 

Inverted Rules (Short Only)

Here are the new rules, inverted for taking short trades:

  • Price must be below its 200-day moving average
  • RSI(2) on price must be above 70
  • Sell short when RSI(2) of the VIX is below 10
  • Exit when RSI(2) of the price falls below 35

Baseline Results

Below is the equity curve for trading the E-mini S&P based upon the rules as defined above.

Going short during bear market.

We have a different story here. First, the equity curve peeks around trade 155, about 2008. Thus since 2008, the equity curve has fallen. That 14 years of no profit!

It does look like this shorting strategy held an edge until 2008, but since then, not so much. We all know shorting strategies on the stock index markets can be challenging to create.

One example of a successful shorting system for the US index market can be found in another article here.

Getting back with our shorting strategy, let's test something a little different. Going long during a bear market!

Going Long In A Bear Market

What would happen if we simply go long during a bear market? The original rules called for trades only when the daily price is above the 200-day moving average. Let's turn that around and go long only when price is below the 200-day moving average. Below is the equity curve.

Going long during bear market.

This looks better than I thought it would. Even going long during a bear market produces a positive return. However, lots of drawdown!

This gets me thinking. Bear markets are a lot different than bull markets. Connor's originally developed his trading rules for bull markets so let's change the parameters.

Going Long In A Bear Market (Modified Parameters)

I optimized the VIX Threshold and the Price Threshold. I wanted to see how many combinations are profitable. It turned out all are profitable which is a good sign. Below is a graph of the 108 combinations I tested. All positive!

Connors RSI on VIX Long During Bear Study

Connor's RSI on VIX Long During Bear Study

I then picked a pair of parameters that did not appear to be outliers. Those values were:

VIX Threshold 50 instead of 90. This means the amount of fear does not have to be as extreme to trigger a trade. This will produce more trading opportunities.

Price Threshold 20 instead of 30. This requires price to experience a deeper pullback.

Both of these change makes sense. We want a deeper pullback and price so we require the RSI threshold to be lower. We also want to generate enough trades so we lose the restriction on the VIX Threshold. Below are the results:

Connors RSI on VIX Long During Bear Optimized

Connor's RSI on VIX Long During Bear Optimized

In Closing

It’s clear that simply reversing the rules do not produce viable results. However, going long during a bear market creates better results than one might first imagine. Here is a couple of ideas for you to test:

1. Try adding a stop to this strategy. Remember, as the strategy currently stands it does not have a hard stop. So, attempt to reduce drawdown with a stop. This will most likely come at the expense of sacrificing some returns. That's OK.

2. Combine this strategy with the original rules, "Profit By Combing RSI and VIX. " You then have two independent trading systems. One trading during a bull market and one trading during a bear market. This would be an exciting combination!

Let me know how your testing goes. Leave a comment below!

]]>
https://easylanguagemastery.com/strategies/inverting-the-rsi-and-vix-strategy/feed/ 1
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