George Pruitt – Helping you Master EasyLanguage https://easylanguagemastery.com Helping you Master EasyLanguage Thu, 05 Sep 2024 16:05:55 +0000 en-US hourly 1 https://wordpress.org/?v=7.0 https://easylanguagemastery.com/wp-content/uploads/2019/02/cropped-logo_size_icon_invert.jpg George Pruitt – Helping you Master EasyLanguage https://easylanguagemastery.com 32 32 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
A Cool And Easy Way To Analyze Chart Patterns With TradeStation https://easylanguagemastery.com/market-studies/a-cool-and-easy-way-to-analyze-chart-patterns-with-tradestation/?utm_source=rss&utm_medium=rss&utm_campaign=a-cool-and-easy-way-to-analyze-chart-patterns-with-tradestation https://easylanguagemastery.com/market-studies/a-cool-and-easy-way-to-analyze-chart-patterns-with-tradestation/#respond Mon, 17 Jun 2024 10:00:15 +0000 http://easylanguagemastery.com/?p=20789

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

The inefficient way:


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

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


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

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

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

The following code does this:

value1 = patternTests - 1;

if(value1 > 0) then
begin

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

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

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

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

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

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

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

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

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



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

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

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

Pattern

Binary Pattern

P&L

Pattern String

0

0000

$12,187

– – – – 

1

0001

$14,150

– – – + 

2

0010

$7,687

– – +–

3

0011

$5,425

– – + + 

4

0100

$2,412

– + – –

5

0101

$6,887

- + - +

6

0110

$7,500

– + + –

7

0111

$9,762

– + + +

8

1000

$13,850

+ – – – 

9

1001

$10,225

+ – – +

10

1010

-$12.0

+ – + –

11

1011

$7,700

+ – + +

12

1 1 0 0

$11,025

+ + – –

13

1101

$4,975

+ + – +

14

1110

-$1,312

+ + + –

15

1111

-$1,000

+ + + + 

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

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

Pattern

Binary Pattern

P&L

Pattern String

0

0000

-$12,187.5

– – – – 

1

0001

-$14,150

– – – + 

2

0010

$7,687

– – +–

3

0011

-$5,425

– – + + 

4

0100

-$2,412

– + – –

5

0101

$6,887

- + - +

6

0110

-$7,500

– + + –

7

0111

-$9,762

– + + +

8

1000

-$13,850

+ – – – 

9

1001

-$10,225

+ – – +

10

1010

$12

+ – + –

11

1011

-$7,700

+ – + +

12

1 1 0 0

-$11,025

+ + – –

13

1101

-$4,975

+ + – +

14

1110

$1,312

+ + + –

15

1111

$1,000

+ + + + 

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

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

Here is the program in its entirety:

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

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

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

patternString = "";
patternTest = "";

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

value1 = patternTests - 1;

if(value1 > 0) then
begin

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

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

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

patternString = "";

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

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

end;
end;

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

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

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

end;

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

-- George Pruitt from GeorgePruitt.com.

Update by Jeff Swanson 

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

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

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

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

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

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

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

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

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

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

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

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

CFTC-required risk disclosure for hypothetical results:

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

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

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

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

Draw down as a percentage of account value.

Detto!

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

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

ES: N = 6 AND M = 6

US: N =10 AND M = 1

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

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

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

Create a synthetic calendar from the current day of month

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

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

Output of Python Snippet - use in EZLang.

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

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

Counting the days until the EOM

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

array: monthDays[12](0);

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

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

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

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

loopDOW = curDayOfWeek+1;
tdToEOM=0;

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

EasyLanguage Function : TradingDaysLeftInMonth

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

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

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

TDLM = tradingDaysLeftInMonth;
TDIM = tradingDayOfMonth;

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

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

EasyLanguage function driver in form of Strategy

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

Get your Pick ready to mine!

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

Genetically MODIFIED – Data Mining at its best!

Here are the parameters:

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

Bond System:

Bond market results.

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

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


>> By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/market-studies/how-to-test-and-optimize-turn-of-the-month-seasonality/feed/ 0
A Timely Function in Easylanguage https://easylanguagemastery.com/building-strategies/a-timely-function-in-easylanguage/?utm_source=rss&utm_medium=rss&utm_campaign=a-timely-function-in-easylanguage https://easylanguagemastery.com/building-strategies/a-timely-function-in-easylanguage/#comments Mon, 29 Jan 2024 11:00:00 +0000 https://easylanguagemastery.com/?p=533439

Learn how to constrain trading between a Start and End Time – not so “easy-peasy”

Why waste time on this?

Is Time > StartTime and Time <= EndTime then…  Right?

This is definitely valid when EndTime > StartTime.  But what happens when EndTime < StartTime.  Meaning that you start trading yesterday, prior to midnight, and end trading after midnight (today.)  Many readers of my blog know I have addressed this issue before and created some simple equations to help facilitate trading around midnight.  The lines of code I have presented work most of the time.  Remember when the ES used to close at 4:15 and re-open at 4:30 eastern?   As of late June 2021, this gap in time has been removed.  The ES now trades between 4:15 and 4:30 continuously.   I discovered a little bug in my code for this small gap when I was optimizing a “get out time.”   I wanted to create a user function that uses the latest session start and end times and build a small database of valid times for the 24-hour markets.  Close to 24 hours – most markets will close for an hour.  With this small database you can test your time to see if it is a valid time.  The construction of this database will require a little TIME math and require the use of arrays and loops.  It is a good tutorial.  However, it is not perfect.  If you optimize time and you want to get out at 4:20 in 2020 on the ES, then you still run into the problem of this time not being valid.  This requires a small workaround.  Going forward with automated trading, this function might be useful.  Most markets trade around the midnight hour – I think meats might be the exception.

Time Based Math

How many 5-minute bars are between 18:00 (prior day) and 17:00 (today)?  We can do this in our heads 23 hours X (60 minutes / 5 minutes) or 23 X 12 = 276 bars.  But we need to tell the computer how to do this and we also should allow users to use times that include minutes such as 18:55 to 14:25. Here’s the math – btw you may have a simpler approach.

Using startTime of 18:55 and endTime of 14:25.

1. Calculate the difference in hours and minutes from startTime to midnight and then in terms of minutes only.

a. timeDiffInHrsMins = 2360 – 1855 = 505 or 5 hours and 5 minutes.  We use a little short cut hear.  23 hours and 60 minutes is the same as 2400 or midnight. 

b. timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100).  This looks much more complicated than it really is because we are using two helper functions – intPortion and mod:

I) intPortion – returns the whole number from a fraction.  If we divide 505/100 we get 5.05 and if we truncate the decimal we get 5 hours.

II) mod – returns the modulus or remainder from a division operation.  I use this function a lot.  Mod(505/100) gives 5 minutes.

III) Five hours * 60 minutes + Five minutes = 305 minutes.

2. Calculate the difference in hours and minutes from midnight to endTime and then in terms of minutes only.

a. timeDiffInHrsMins = endTime – 0 = 1425 or 14 hours and 25 minutes.  We don’t need to use our little, short cut here since we are simply subtracting zero.  I left the zero in the calculation to denote midnight.

b. timeDiffInMinutes = timeDiffInMinutes + intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100).  This is the same calculation as before, but we are adding the result to the number of minutes derived from the startTime to midnight.  

I) intPortion – returns the whole number from a fraction.  If we divide 1425/100, we get 14.05 and if we truncate the decimal, we get 14.

II) mod – returns the modulus or remainder from a division operation.  I use this function a lot.  Mod(1425/100) gives 25.

III) 14* 60 + 25 = 865 minutes.

iv) Now add 305 minutes to 865.  This gives us a total of 1165 minutes between the start and end times.

3. Now divide the timeDiffInMinutes by the barInterval.  This gives 1165 minutes/5 minutes or 233 five-minute bars.

Build Database of all potential time stamps between start and end time

We now have all the ingredients to build are simple array-based database.  Don’t let the word array scare you away.  Follow the logic and you will see how easy it is to use them.   First, we will create the database of all the time stamps between the regular session start and end times of the data on the chart.  We will use the same time-based math (and a little more) to create this benchmark database.  Check out the following code.

// You could use static arrays
// reserve enough room for 24 hours of minute bars
// 24 * 60 = 1440
// arrays: theoTimes[1440](0),validTimes[1440](0);
// syntax - arrayName[size](0) - the zero sets all elements to zero
// this seems like over kill because we don't know what
// bar interval or time span the user will be using

// these arrays are dynamic
// we dimension or reserve space for just what we need
arrays: theoTimes[](0),validTimes[](0);

// Create a database of all times stamps that potentiall could
// occur

numBarsInCompleteSession = timeDiffInMinutes/barInterval;

// Now set the dimension of the array by using the following
// function and the number of bars we calculated for the entire
// regular session
Array_setmaxindex(theoTimes,numBarsInCompleteSession);
// Load the array from start time to end time
// We know the start time and we know the number of X-min bars
// loop from 1 to numBarsInCompleteSession and
// use timeSum as the each and every time stamp
// To get to the end of our journey we must use Time Based Math again.
timeSum = startTime;
for arrayIndex = 1 to numBarsInCompleteSession
Begin
timeSum = timeSum + barInterval;
if mod(timeSum,100) = 60 Then
timeSum = timeSum - 60 + 100; // 1860 - becomes 1900
if timeSum = 2400 Then
timeSum = 0; // 2400 becomes 0000
theoTimes[arrayIndex] = timeSum;

print(d," theo time",arrayIndex," ",theoTimes[arrayIndex]);
end;

Create a dynamic array with all possible time stamps

This is a simple looping mechanism that continually adds the barInterval to timeSum until numBarsInCompleteSession are exhausted.  Reade about the difference between static and dynamic arrays in the code, please.  Here’s how it works with a session start time of 1800:

theoTimes[01] = 1800 + 5 = 1805
theoTimes[02] = 1805 + 5 = 1810
theoTimes[04] = 1810 + 5 = 1815
theoTimes[05] = 1815 + 5 = 1820
theoTimes[06] = 1820 + 5 = 1830
...
//whoops - need more time based math 1860 is not valid
theoTimes[12] = 1855 + 5 = 1860

Insert bar stamps into our theoTimes array

More time-based math

Our loop hit a snag when we came up with 1860 as a valid time.  We all know that 1860 is really 1900.  We need to intervene when this occurs.  All we need to do is use our modulus function again to extract the minutes from our time.

If mod(timeSum,100) = 60 then timeSum = timeSum – 60 + 100.  Her we remove the sixty minutes from the time and add an hour to it.

1860 – 60 + 100 = 1900 // a valid time stamp

That should fix everything right?  What about this:

theoTimes[69] = 2340 + 5 = 2345
theoTimes[70] = 2345 + 5 = 2350
theoTimes[71] = 2350 + 5 = 2355
theoTimes[72] = 2355 + 5 = 2400 // whoops

2400 is okay in Military Time but not in TradeStation

This is a simple fix with.  All we need to do is check to see if timeSum = 2400 and if so, just simply reset to zero.

Build a database on our custom time frame.

Basically, do the same thing, but use the user’s choice of start and end times.

//calculate the number of barInterval bars in the
//user defined session
numBarsInSession = timeDiffInMinutes/barInterval;

Array_setmaxindex(validTimes,numBarsInSession);

startTimeStamp = calcTime(startTime,barInterval);

timeSum = startTime;
for arrayIndex = 1 to numBarsInSession
Begin
timeSum = timeSum + barInterval;
if mod(timeSum,100) = 60 Then
timeSum = timeSum - 60 + 100;
if timeSum = 2400 Then
timeSum = 0;
validTimes[arrayIndex] = timeSum;
//print(d," valid times ",arrayIndex," ",validTimes[arrayIndex]," ",numBarsInSession);
end;

Create another database using the time frame chose by the user

Don’t allow weird times!

Good programmers don’t allow extraneous values to bomb their functions.  TRY and CATCH the erroneous input before proceeding.  If we have a database of all possible time stamps, shouldn’t we use it to validate the user entry?  Of course, we should.

//Are the users startTime and endTime valid
//bar time stamps? Loop through all the times
//and validate the times.

for arrayIndex = 1 to numBarsInCompleteSession
begin
if startTimeStamp = theoTimes[arrayIndex] then
validStartTime = True;
if endTime = theoTimes[arrayIndex] Then
validEndTime = True;
end;

Validate user's input

Once we determine if both time inputs are valid, then we can determine if the any bar’s time stamp during a back-test is a valid time.

if validStartTime = false or validEndTime = false Then
error = True;
//Okay to check for bar time stamps against our
//database - only go through the loop until we
//validate the time - break out when time is found
//in database. CanTradeThisTime is the name of the function.
//It returns either True or False

if error = False Then
Begin
for arrayIndex = 1 to numBarsInSession
Begin
if t = validTimes[arrayIndex] Then
begin
CanTradeThisTime = True;
break;
end;
end;
end;

This portion of the code is executed on every bar of the back-test

Once and only Once!

The code that creates the theoretical and user defined time stamp database is only done on the very first bar of the chart.  Also, the validation of the user’s input in only done once as well.  This is accomplished by encasing this code inside a Once – begin – end.

Now this code will test any time stamp against the current regular session.  If you run a test prior to June 2021, you will get a theoretical database that includes a 4:20, 4:25, and 4:30 on the ES futures.  However, in actuality these bar stamps did not exist in the data.  This might cause a problem when working with a start or end time prior to June 2021, that falls in this range.

Function Name:  CanTradeThisTime

Complete code:

// Function to determine if time is in acceptable
// set of times
inputs:startTime(numericSimple),endTime(numericSimple);

vars: sessStartTime(0),sessEndTime(0),
startTimeStamp(0),timeSum(0),timeDiffInHrsMins(0),timeDiffInMinutes(0),
validStartTime(False), validEndTime(False);

vars: error(False),arrayIndex(0),
numBarsInSession(0),numBarsInCompleteSession(0);

arrays: theoTimes[](0),validTimes[](0);
vars: arrCnt(0),seed(0);

canTradeThisTime = false;

once
Begin

sessStartTime = sessionStartTime(0,1);
sessEndTime = sessionEndTime(0,1);

if sessStartTime > sessEndTime Then
Begin
timeDiffInHrsMins = 2360 - sessStartTime;
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);

timeDiffInHrsMins = sessEndTime - 0;
timeDiffInMinutes += intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
end;

if sessStartTime <= sessEndTime Then
Begin
timeDiffInHrsMins = (intPortion(sessEndTime/100) - 1)*100 + mod(sessEndTime,100) + 60 - sessEndTime;
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
end;

numBarsInCompleteSession = timeDiffInMinutes/barInterval;

Array_setmaxindex(theoTimes,numBarsInCompleteSession);

timeSum = startTime;
for arrayIndex = 1 to numBarsInCompleteSession
Begin
timeSum = timeSum + barInterval;
if mod(timeSum,100) = 60 Then
timeSum = timeSum - 60 + 100;
if timeSum = 2400 Then
timeSum = 0;
theoTimes[arrayIndex] = timeSum;

print(d," theo time",arrayIndex," ",theoTimes[arrayIndex]);
end;

if startTime > endTime Then
Begin
timeDiffInHrsMins = 2360 - startTime;
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
timeDiffInHrsMins = endTime - 0;
timeDiffInMinutes += intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
end;

if startTime <= endTime Then
Begin
timeDiffInHrsMins = (intPortion(endTime/100) - 1)*100 + mod(endTime,100) + 60 - startTime;
timeDiffInMinutes = intPortion(timeDiffInHrsMins/100) * 60 + mod(timeDiffInHrsMins,100);
end;

numBarsInSession = timeDiffInMinutes/barInterval;

Array_setmaxindex(validTimes,numBarsInSession);

startTimeStamp = calcTime(startTime,barInterval);

timeSum = startTime;
for arrayIndex = 1 to numBarsInSession
Begin
timeSum = timeSum + barInterval;
if mod(timeSum,100) = 60 Then
timeSum = timeSum - 60 + 100;
if timeSum = 2400 Then
timeSum = 0;
validTimes[arrayIndex] = timeSum;
print(d," valid times ",arrayIndex," ",validTimes[arrayIndex]," ",numBarsInSession);
end;
for arrayIndex = 1 to numBarsInCompleteSession
begin
if startTimeStamp = theoTimes[arrayIndex] then
validStartTime = True;
if endTime = theoTimes[arrayIndex] Then
validEndTime = True;
end;
end;

if validStartTime = False or validEndTime = false Then
error = True;

if error = False Then
Begin
for arrayIndex = 1 to numBarsInSession
Begin
if t = validTimes[arrayIndex] Then
begin
CanTradeThisTime = True;
break;
end;
end;
end;

Complete CanTradeThisTime function code

Sandbox Strategy function driver

inputs: startTime(1800),endTime(1500);

if canTradeThisTime(startTime,endTime) Then
if d = 1231206 or d = 1231207 then
print(d," ",t," can trade this time");

I hope you find this useful.  Remember to purchase by Easing into EasyLanguage books at amazon.com.  The DayTrade edition is still on sale.  Email me with any question or suggestions or bugs or anything else.

>>By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/building-strategies/a-timely-function-in-easylanguage/feed/ 4
Extend Data Mining To Actual Trading System https://easylanguagemastery.com/building-strategies/extend-data-mining-to-actual-trading-system/?utm_source=rss&utm_medium=rss&utm_campaign=extend-data-mining-to-actual-trading-system https://easylanguagemastery.com/building-strategies/extend-data-mining-to-actual-trading-system/#respond Mon, 14 Aug 2023 10:00:00 +0000 https://easylanguagemastery.com/?p=532714

Data Mining May or May Not Link Causality

A study between ice cream sales and crime rate demonstrated a high level of correlation.  However, it would be illogical to assume that buying more ice cream leads to more crime.  There are just too many other factors and variables involved to draw a conclusion.  So, data mining with EasyLanguage may or may not lead to anything beneficial.  One thing is you cannot hang your hat completely on this type of research.  A reader of my books asked if there was evidence that pointed to the best time to enter and exit a day trade.  Is it better to enter in the morning or in the afternoon or are there multiple trading windows throughout the day?  I thought I would try to answer the question using TradeStation’s optimization capabilities.

Get Your Copy Now!

Create a Search Space of Different Window Opening Times and Open Duration

My approach is just one of a few that can be used to help answer this question.  To cut down on time and the size of this blog we will only look at day trading the @ES.D from the long side.  The search space boundaries can be defined by when we open the trading window and how long we leave it open.  These two variables will be defined by inputs so we can access the optimization engine.  Here is how I did it with EasyLanguage code.

inputs: openWindowTime(930),openWindowOffset(5),windowDuration(60);
inputs: canBuy(True),canShort(True);
if t >= calcTime(openWindowTime,openWindowOffset) and t < calcTime(openWindowTime,openWindowOffset+windowDuration) Then
Begin
if entriesToday(d) = 0 and canBuy Then
buy next bar at market;
if entriesToday(d) = 0 and canShort Then
sellshort next bar at market ;
end;

if t = calcTime(openWindowTime,openWindowOffset+windowDuration) Then
Begin
if marketPosition = 1 then sell next bar at open;
if marketPosition =-1 then buyToCover next bar at open;
end;
setExitOnClose;

Optimize when to open and how long to leave open

The openWindowTime input is the basis from where we open the trading window.  We are working with the @ES.D with an open time of 9:30 AM eastern.  The openWindowOffset will be incremented in minutes equivalent to the data resolution of the chart, five minutes.  We will start by opening the window at 9:35 and leave it open for 60 minutes.  The next iteration in the optimization loop will open the window at 9:40 and keep it open for 60 minutes as well.  Here are the boundaries that I used to define our search space.

  • window opening times offset: 5 to 240 by 5 minutes
  • window opening duration: 60 to 240 by 5 minutes
Optimization Ranges for Window Open and Open Duration

A total of 1739 iterations will span our search space.   The results state that waiting for twenty minutes before buying and then exiting 190 minutes later, worked best.  But also entering 90 minutes after the open and exiting 4 hours later produced good results as well (no trade execution fee were utilized.)  Initially I was going to limit entry to once per day, but then I thought it might be worthwhile to enter a fresh position, if the first one is stopped out, or pyramid if it hasn’t.  I also thought, each entry should have its own protective stop amount.  Would entering later require a small stop – isn’t most of the volatility, on average, expressed during the early part of the day.

Results of different opening and duration times.

Build a Strategy that Takes on a Secondary Trade as a New Position or One that is Pyramided.

This is not a simple strategy.  It sounds simple and it requires just a few lines of code.  But there is a trick in assigning each entry with its own exit.  As you can see there is a potential for trade overlap.  You can get long 20 minutes after the open and then add on 70 minutes  (90 from the open) later.  If the first position hasn’t been stopped out, then you will pyramid at the second trade entry.  You have to tell TradeStation to allow this to happen.

Allow TradeStation to Pyramid up to 2 positions with different signals.

System Rules

  1. Enter long 20 minutes after open
  2. Enter long 90 minutes after open
  3. Exit 1st entry 190 minutes later or at a fixed $ stop loss
  4. Exit 2nd entry 240 minutes later or at a fixed $ stop loss
  5. Make sure you are out at the end of the day

Sounds pretty simple, but if you want to use different stop values for each entry, then the water gets very muddy.

AvgEntryPrice versus EntryPrice

Assume you enter long and then you add on another long position.  If you examine EntryPrice you will discover that it reflects the initial entry price only.   The built-in variable AvgEntryPrice will be updated with the average price between the two entries.  If you want to key off of the second entry price, then you will need to do a little math.

avgEntryPrice = (entry price 1 + entry price 2) / 2

or ap = (ep1 + ep2) /2

Using this formula and simple algebra we can arrive at ep2 using this formula:  ep2 = 2*ap – ep1.  Since we already know ep1 and ap, ep2 is easy to get to.  We will need this information and also the functionality of from entry.  You tie entries and exits together with the keywords from entry.  Here are the entry and exit trade directives.

if time = calcTime(openTime,entryTime1Offset) then
buy("1st buy") next bar at open;

if time = calcTime(openTime,entryTime2Offset) then
buy("2nd buy") next bar at open;

if time = calcTime(openTime,entryTime1Offset + exitTime1Offset) then
sell("1st exit") from entry("1st buy") next bar at open;

if time = calcTime(openTime,entryTime2Offset + exitTime2Offset) then
sell("2nd exit") from entry("2nd buy") next bar at open;

if mp = 1 Then
Begin
value1 = avgEntryPrice;
if currentShares = 2 then value1 = avgEntryPrice*2 - entryPrice;
sell("1st loss") from entry("1st buy") next bar at entryPrice - stopLoss1/bigPointValue stop;
sell("2nd loss") from entry("2nd buy") next bar at value1 - stopLoss2/bigPointValue stop;
end;

if mp = 1 and t = openTime + barInterval then sell("oops") next bar at open;

Entry and Exit Directives Code

The trade entry directives are rather simple, but you must use the calcTime function to arrive at the correct entry and exit times.  Here we are using the benchmark, openTime and the offsets of entryTime1Offset and entryTime2Offset.  This function adds (or subtracts if the offset is negative) the offset to the benchmark.  This takes care of when the trading windows open, but you must add the entry1TimeOffset to exit1TimeOffset to calculate the duration the trading window is to remain open.  This goes for the second entry window as well.

Now let’s look at the exit directives.  Notice how I exit the 1st buy entry with the code from entry (“1st buy”).  This ties the entry and exit directives together.  This is pretty much straightforward as well.  The tricky part arrives when we try to apply different money management stops to each entry.  Exiting from the 1st buy requires us to simply subtract the $ in terms of points from entryPrice.  We must use our new equation to derive the 2nd entry price when two contracts are concurrent.   But what if we get stopped out of the first position prior to entering the second position?  Should we continue using the formula.  No.  We need to fall back to entryPrice or avgEntryPrice:  when only one contract or unit is in play, these two variables are equal.  We initially assign the variable value1 to the avgEntryPrice and only use our formula when currentShares = 2.  This code will work a majority of the time.  But take a look at this trade:

Didn’t have an intervening bar to update the 2nd entry price. The first entry price was used as the basis to calculate the stop loss!

This is an anomaly, but anomalies can add up.  What happened is we added the second position and the market moved down very quickly – too quickly for the correct entry price to be updated.  The stop out (2nd loss) was elected by using the 1st entry price, not the second.  You can fix this with the following two solutions:

  1. Increase data resolution and hope for an intervening bar
  2. Force the second loss to occur on the subsequent trading bar after entry.  This means you will not be stopped out on the bar of entry but will have to wait five minutes or whatever bar interval you are working with.
Fixed – just told TS to place the order at the close of the bar where we were filled!

OK – Now How Do We Make this a Viable Trading System

If you refer back to the optimization results you will notice that the average trade (before execution costs) was around $31.  Keep in mind we were trading every day.  This is just the beginning of your research – did we find a technical advantage?  No.  We just found out that you can enter and exit at different times of the trading day, and you can expect a positive outcome.  Are there better times to enter and exit?  YES.  You can’t trade this approach without adding some technical analysis – a reason to enter based on observable patterns.  This process is called FILTERING.   Maybe you should only enter after range compression.  Or after the market closed up on the prior day, or if the market was an NR4 (narrow range 4.)  I have added all these filters so you can iterate across them all using the optimization engine.  Take a look:

filter1 = True;
filter2 = True;

if filtNum1 = 1 then
filter1 = close of data2 > close[1] of data2;
if filtNum1 = 2 Then
filter1 = close of data2 < close[1] of data2;
if filtNum1 = 3 Then
filter1 = close of data2 > open of data2;
if filtNum1 = 4 Then
filter1 = close of data2 < open of data2;
if filtNum1 = 5 Then
filter1 = close of data2 > (h data2 + l data2 + c data2)/3;
if filtNum1 = 6 Then
filter1 = close of data2 < (h data2 + l data2 + c data2)/3;
if filtNum1 = 7 Then
filter1 = openD(0) > close data2;
if filtNum1 = 8 Then
filter1 = openD(0) < close data2;

if filtNum2 = 1 Then
filter2 = trueRange data2 < avgTrueRange(10) data2;
if filtNum2 = 2 Then
filter2 = trueRange data2 > avgTrueRange(10) data2;
if filtNum2 = 3 Then
filter2 = range data2 = lowest(range data2,4);
if filtNum2 = 4 Then
filter2 = range data2 = highest(range data2,4);

Filter1 and Filter2 - filter1 looks for a pattern and filter2 seeks range compression/expansion.

Let’s Search – And Away We Go

I will optimize across the different patterns and range analysis and different $ stops for each entry (1st and 2nd.)

Optimize across patterns and volatility and protective stops for 1st and 2nd entries.

Best Total Profit

Trade when today’s open is greater than yesterday’s close and don’t worry about the volatility.  Use $550 for the first entry and $600 for the second.

Best W:L Ratio and Respectable Avg. Trade

This curve was created  by waiting for yesterday’s close to be below the prior day’s and yesterday being an NR4 (narrow range 4).  And using a $500 protective stop for both the 1st and 2nd entries.

Did We Find the Holy Grail?  Gosh No!

This post served two purposes.  One, how to set up a framework for data mining and two, create code that can handle things that aren’t apparently obvious – entryPrice versus avgEntryPrice!

if filter1 and filter2 Then
begin
if time = calcTime(openTime,entryTime1Offset) then
buy("1st buy") next bar at open;

if time = calcTime(openTime,entryTime2Offset) then
buy("2nd buy") next bar at open;
end;

Incorporating Filter1 and Filter2 in the Entry Logic

>>By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/building-strategies/extend-data-mining-to-actual-trading-system/feed/ 0
EasyLanguage to Determine Week of Month https://easylanguagemastery.com/indicators/easylanguage-to-determine-week-of-month/?utm_source=rss&utm_medium=rss&utm_campaign=easylanguage-to-determine-week-of-month https://easylanguagemastery.com/indicators/easylanguage-to-determine-week-of-month/#respond Mon, 22 May 2023 10:00:00 +0000 https://easylanguagemastery.com/?p=532499

Week Of Month
I could be wrong, but I couldn’t find this functionality in EasyLanguage. I was testing a strategy that didn’t want to trade a specific week of the month. If it’s not built-in, then it must be created. I coded this functionality in Sheldon Knight’s Seasonality indicator but wanted to create a simplified universal version. I may have run into one little snag. Before discussing the snag, here is a Series function that returns my theoretical week of the month.

vars: weekCnt(0),cnt(0);
vars: newMonth(False),functionSeed(False);

if month(d) <> month(d[1]) Then
Begin
weekCnt = 1;
end;

if dayOfWeek(d)<dayOfWeek(d[1]) and month(d) = month(d[1]) Then
begin
weekCnt = weekCnt + 1;
end;
if weekCnt = 1 and dayofMonth(d) = 2 and dayOfWeek(D) = Sunday Then
print("Saturday was first day of month"," ",d);

WeekOfMonth = weekCnt;

Series Function to Return Week Rank


This function is of type Series because it has to remember the prior output of the function call – weekCnt.  This function is simple as it will not provide the week count accurately (at the very beginning of a test) until a new month is encountered in your data.  It needs a ramp up (at least 30 days of daily or intraday data) to get to that new month.  I could have used a while loop the first time the function was called and worked my way back in time to the beginning of the month and along the way calculate the week of the month.  I decided against that, because if you are using tick data then that would be a bunch of loops and TradeStation can get caught in an infinite loop very easily.

This code is rather straightforward.  If the today’s month is not equal to yesterday’s month, then weekCnt is set to one.  Makes sense, right.  The first day of the month should be the first week of the month.  I then compare the day of week of today against the day of week of yesterday.  If today’s day of week is less than the prior day’s day of week, then it must be a Sunday (futures markets open Sunday night to start the week) or Monday (Sunday = 0 and Monday = 1 and Friday = 5.)  If this occurs and today’s month is the same as yesterday’s month, weekCnt is incremented.  Why did I check for the month?  What if the first trading day was a Sunday or Monday?  Without the month comparison I would immediately increment weekCnt and that would be wrong.  That is all there is to it?  Or is it?  Notice I put some debug code in the function code.

Is There a Snag?

April 2023 started the month on Saturday which is the last day of the week, but it falls in the first week of the month.  The sun rises on Sunday and it falls in the second week of the month.  If you think about my code, this is the first trading day of the month for futures:

month(April 2nd) = April or 4

month(March 31st) = March or 3

They do not equal so weekCnt is set to 1.  The first trading day of the month is Sunday or DOW=0 and the prior trading day is Friday or DOW=5.  WeekCnt is NOT incremented because month(D) doesn’t equal month(D[1]).  Should WeekCnt be incremented?  On a calendar basis it should, but on a trading calendar maybe not.  If you are searching for the first occurrence of a certain day of week, then my code will work for you.  On April 2nd, 2023, it is the second week of the month, but it is the first Sunday of April.

Thoughts???  Here are a couple of screenshots of interest.

Indicator in Histogram form representing the Week of Month

Some months are spread across SIX weeks.

This function is an example of where we let the data tell us what to do.  I am sure there is calendar functions, in other languages, that can extract information from just the date.  However, I like to extract from what is actually going to be traded.

Email me if you have any questions, concerns, criticism, or a better mouse trap.

>> By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/indicators/easylanguage-to-determine-week-of-month/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
Can Futures Traders Trust Continuous Contracts? [Part – 2] https://easylanguagemastery.com/development-tools/can-futures-traders-trust-continuous-contracts-part-2/?utm_source=rss&utm_medium=rss&utm_campaign=can-futures-traders-trust-continuous-contracts-part-2 https://easylanguagemastery.com/development-tools/can-futures-traders-trust-continuous-contracts-part-2/#respond Mon, 24 Oct 2022 10:00:00 +0000 https://easylanguagemastery.com/?p=530606

Recap from Part -1

I had to wrap up Part -1 rather quickly and probably didn’t get my ideas across, completely.  Here is what we did in Part – 1.

  1. used my function to locate the First Notice Date in crude
  2. used the same function to print out exact EasyLanguage syntax
  3. chose to roll eight days before FND and had the function print out pure EasyLanguage
  4. the output created array assignments and loaded the calculated roll points in YYYMMDD format into the array
  5.  visually inspected non-adjusted continuous contracts that were spliced eight days before FND
  6. appended dates in the array to match roll points, as illustrated by the dip in open interest

Step 6 from above is very important, because you want to make sure you are out of a position on the correct rollover date.  If you are not, then you will absorb the discount between the contracts into your profit/loss when you exit the trade.

Step 2 – Create the code that executes the rollover trades

Here is the code that handles the rollover trades.

...

...

...

...

rollArr[118]=20220314;

rollArr[119]=20220411;

rollArr[120]=20220512;

rollArr[121]=20220613;

rollArr[122]=20220712;

rollArr[123]=20220812;

// If in a position and date + 1900000 (convert TS date format to YYYYMMDD),

// then exit long or short on the current bar's close and then re-enter

// on the next bar's openif d+19000000 = rollArr[arrCnt] then begin

 condition1 = true; arrCnt = arrCnt + 1;if marketPosition = 1 then begin

 sell("LongRollExit") this bar on close;buy("LongRollEntry") next bar at open;end;

if marketPosition = -1 then begin

 buyToCover("ShrtRollExit") this bar on close;sellShort("ShrtRollEntry") next bar at open;

end;

end;

Code to rollover open position

This code gets us out of an open position during the transition from the old contract to the new contract.  Remember our function created and loaded the rollArr for us with the appropriate dates.  This simulation is the best we can do – in reality we would exit/enter at the same time in the two different contracts.  Waiting until the open of the next bar introduces slippage.  However, in the long run this slippage cost may wash out.

Step 3 – Create a trading system with entries and exits

The system will be a simple Donchian where you enter on the close when the bar’s high/low penetrates the highest/lowest low of the past 40 bars.  If you are long, then you will exit on the close of the bar whose low is less than the lowest low of the past 20 bars.  If short, get out on the close of the bar that is greater than the highest high of the past twenty bars.  The first test will show the result of using an adjusted continuous contract rolling 8 days prior to FND

CAN FUTURES TRADERS TRUST CONTINUOUS CONTRACTS
Nice Trade. Around August 2014

This test will use the exact same data to generate the signals, but execution will take place on a non-adjusted continuous contract with rollovers.  Here data2 is the adjusted continuous contract and data1 is the non-adjusted.

CAN FUTURES TRADERS TRUST CONTINUOUS CONTRACTS
Same Trade but with rollovers

Still a very nice trade, but in reality you would have to endure six rollover trades and the associated execution costs.

Conclusion

Here is the mechanism of the rollover trade.

CAN FUTURES TRADERS TRUST CONTINUOUS CONTRACTS
Roll out of old contract and roll into new contract

And now the performance results using $30 for round turn execution costs.

No-Rollovers

No Rollovers?

Now with rollovers

Many more trades with the rollovers!

The results are very close, if you take into consideration the additional execution costs.  Since TradeStation is not built around the concept of rollovers, many of the trade metrics are not accurate.  Metrics such as average trade, percent wins, average win/loss and max Trade Drawdown will not reflect the pure algorithm based entries and exits.  These metrics take into consideration the entries and exits promulgated by the rollovers.  The first trade graphic where the short was held for several months should be considered 1 entry and 1 exit.  The rollovers should be executed in real time, but the performance metrics should ignore these intermediary trades.

I will test these rollovers with different algorithms, and see if we still get similar results, and will post them later.  As you can see, testing on non-adjusted data with rollovers is no simple task.  Email me if you would like to see some of the code I used in this post.

>> By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/development-tools/can-futures-traders-trust-continuous-contracts-part-2/feed/ 0
Can Futures Traders Trust Continuous Contracts? [Part-1] https://easylanguagemastery.com/uncategorized/can-futures-traders-trust-continuous-contracts-part-1/?utm_source=rss&utm_medium=rss&utm_campaign=can-futures-traders-trust-continuous-contracts-part-1 https://easylanguagemastery.com/uncategorized/can-futures-traders-trust-continuous-contracts-part-1/#respond Mon, 03 Oct 2022 15:03:56 +0000 https://easylanguagemastery.com/?p=530680

Well You Have To, Don’t You?

When I worked at Futures Truth, we tested everything with our Excalibur software.  This software used individual contract data and loaded the entire history (well, the part we maintained) of each contract into memory and executed rollovers at a certain time of the month.  Excalibur had its limitations as certain futures contracts had very short histories and rollover dates had to be predetermined – in other words, they were undynamic.  Over the years, we fixed the short history problem by creating a dynamic continuous contract going back in time for the number of days required for a calculation.  We also fixed the database with more appropriate rollover frequency and dates.  So in the end, the software simulated what I had expected from trading real futures contracts.  This software was originally written in Fortran and for the Macintosh.  It also had limitations on portfolio analysis as it worked its way across the portfolio, one complete market at a time.   Even with all these limitations, I truly thought that the returns more closely mirrored what a trader might see in real time.  Today, there aren’t many, if any, simulation platforms that test on individual contracts.  The main reasons for this are the complexity of the software, and the database management.  However, if you are willing to do the work, you can get close to testing on individual contract data with EasyLanguage.

Step 1 – Get the rollover dates

This is critical as the dates will be used to roll out of one contract and into another.  In this post, I will test a simple strategy on the crude futures.  I picked crude because it rolls every month.   Some data vendors use a specific date to roll contracts, such as Pinnacle data.  In real time trading, I did this as well.  We had a calendar for each month, and we would mark the rollover dates for all markets traded at the beginning of each month.  Crude was rolled on the 11th or 12th of the prior month to expiration.  So, if we were trading the September 2022 contract, we would roll on August 11th.  A single order (rollover spread) was placed to sell (if long) the September contract and buy the October contract at the market simultaneously.  Sometimes we would leg into the rollover by executing two separate orders – in hopes of getting better execution.  I have never been able to find a historic database of when TradeStation performs its rollovers.  When you use the default @CL symbol, you allow TradeStation to use a formula to determine the best time to perform a rollover.  This was probably based on volume and open interest.  TradeStation does allow you to pick several different rollover triggers when using their continuous data.

You can choose type of trigger – (3) Dynamic or (4) Time based.

I am getting ahead of myself, because we can simply use the default @CL data to derive the rollover dates (almost.)  Crude oil is one of those weird markets where LTD (last trade days) occurs before FND (first notice day.)  Most markets will give you a notice before they back up a huge truck and dump a 1000 barrels of oil at your front door.   With crude you have to be Johnny on the spot!  Rollover is just a headache when trading futures, but it can be very expensive headache if you don’t get out in time.  Some markets are cash settled so rollover isn’t that important, but others result in delivery of the commodity.  Most clearing firms will help you unwind an expired contract for a small fee (well relatively small.)  In the good old days your full service broker would give you heads up.  They would call you and say, “George you have to get out of that Sept. crude pronto!”  Some firms would automatically liquidate the offending contract on your behalf – which sounds nice but it could cost you.  Over my 30 year history of trading futures I was caught a few times in the delivery process.   You can determine these FND and LTD from the CME website.  Here is the expiration description for crude futures.

Trading terminates 3 business day before the 25th calendar day of the month prior to the contract month. If the 25th calendar day is not a business day, trading terminates 4 business days before the 25th calendar day of the month prior to the contract month.

You can look this up on your favorite broker’s website or the handy calendars they send out at Christmas.  Based on this description, the Sept. 2022 Crude contract would expire on August 20th and here’s why

  • August 25 is Tuesday
  • August 24 is Monday- DAY1
  • August 21 is Friday – DAY2
  • August 20 is Thursday – DAY3

This is the beauty of a well oiled machine or exchange.  The FND will occur exactly as described.  All you need to do is get all the calendars for the past ten years and find the 25th of the month and count back three business days.  Or if the 25 falls on a weekend count back four business days.  Boy that would be chore, would it not?  Luckily, we can have the data and an  EasyLanguage script do this for us.  Take a look at this code and see if it makes any sense to you.

Case "@CL":If dayOfMonth(date) = 25 and firstMonthPrint = false then begin print(date[3]+19000000:8:0);firstMonthPrint = true;end;If(dayOfMonth(date[1]) < 25 and dayOfMonth(date) > 25 ) and firstMonthPrint = false then begin print(date[4]+19000000:8:0);firstMonthPrint = true;end;

Code to printout all the FND of crude oil.

I have created a tool to print out the FND or LTD of any commodity futures by examining the date.  In this example, I am using a Switch-Case to determine what logic is applied to the chart symbol.  If the chart symbol is @CL, I look to see if the 25th of the month exists and if it does, I print the date 3 days prior out.  If today’s day of month is greater than 25 and the prior day’s day of month is less than 25, I know the 25th occurred on a weekend and I must print out the date four bars prior.  These dates are FN dates and cannot be used as is to simulate a rollover. You had best be out before the FND to prevent the delivery process.   Pinnacle Date rolls the crude on the 11th day of the prior month for its crude continuous contracts.  I aimed for this day of the month with my logic.  If the FND normally fell on the 22nd of the month, then I should back up either 9 or 10 business days to get near the 11th of the month.   Also I wanted to use the output directly in an EasyLanguage strategy so I modified my output to be exact EasyLanguage.

Case "@CL":If dayOfMonth(date) = 25 and firstMonthPrint = false then begin value1 = value1 + 1;print("rollArr[",value1:1:0,"]=",date[9]+19000000:8:0,";");firstMonthPrint = true;end;If(dayOfMonth(date[1]) < 25 and dayOfMonth(date) > 25 ) and firstMonthPrint = false then begin value1 = value1 + 1;print("rollArr[",value1:1:0,"]=",date[10]+19000000:8:0,";");//print(date[4]+19000000:8:0);firstMonthPrint = true;end; // example of output rollArr[103]=20210312;rollArr[104]=20210412;rollArr[105]=20210512;rollArr[106]=20210614;rollArr[107]=20210712;rollArr[108]=20210812;rollArr[109]=20210913;rollArr[110]=20211012;rollArr[111]=20211111;rollArr[112]=20211210;rollArr[113]=20220111;rollArr[114]=20220211;rollArr[115]=20220314;rollArr[116]=20220411;rollArr[117]=20220512;rollArr[118]=20220610;rollArr[119]=20220712;rollArr[120]=20220812;

Code to print our 9 or 10 bars prior to FND in actual EasyLanguage

Now. that I had the theoretical rollover dates for my analysis I had to make sure the data that I was going to use matched up exactly.  As you saw before, you can pick the rollover date for your chart data.   And you can also determine the discount to add or subtract to all prior data points based on the difference between the closing prices at the rollover point.  I played around with the number of days prior to FND and selected non adjusted for the smoothing of prior data.

Actual data I simulated rollovers with.

How did I determine 8 days Prior to First Notice Date?  I plotted different data using a different number of days prior and determined 8 provided a sweet spot between the old and new contract data’s open interest.  Can you see the rollover points in the following chart?  Ignore the trades – these were a beta test.

The Open Interest Valley is the rollover date.

The dates where the open interest creates a valley aligned very closely with the dates I printed out using my FND date finder function.  To be safe, I compared the dates and fixed my array data to match the chart exactly.  Here are two rollover trades – now these are correct.

Using an adjusted continuous contract you would not see these trades.

This post turned out to be a little longer than I thought, so I will post the results of using an adjusted continuous contract with no rollovers, and the results using non-adjusted concatenated contracts with rollovers.  The strategy will be a simple 40/20 bar Donchian entry/exit.  You maybe surprised by the results – stay tuned.

>>By George Pruitt from blog georgepruitt.com

]]>
https://easylanguagemastery.com/uncategorized/can-futures-traders-trust-continuous-contracts-part-1/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