Category Archives: EasyLanguage Function

Turn of the Month Trading Strategy [Stock Indices Only]

The System

This system has been around for several years.  Its based on the belief that fund managers start pouring money into the market near the end of the month and this creates momentum that lasts for just a few days.  The original system states to enter the market on the close of the last bar of the day if the its above a certain moving average value.  In the Jaekle and Tomasini book, the authors describe such a trading system.  Its quite simple, enter on the close of the month if its greater than X-Day moving average and exit either 4 days later or if during the trade the closing price drops below the X-Day moving average.

EasyLanguage or Multi-Charts Version

Determining the end of the month should be quite easy -right?  Well if you want to use EasyLanguage on TradeStation and I think on Multi-Charts you can’t sneak a peek at the next bar’s open to determine if the current bar is the last bar of the month.  You can try, but you will receive an error message that you can’t mix this bar on close with next bar.  In other words you can’t take action on today’s close if tomorrow’s bar is the first day of the month.  This is designed, I think, to prevent from future leak or cheating.  In TradeStation the shift from backtesting to trading is designed to be a no brainer, but this does provide some obstacles when you only want to do a backtest.

LDOM function – last day of month for past 15 years or so

So I had to create a LastDayOfMonth function.  At first I thought if the day of the month is the 31st then it is definitely the last bar of the month.  And this is the case no matter what.  And if its the 30th then its the last day of the month too if the month is April, June, Sept, and November.  But what happens if the last day of the month falls on a weekend.  Then if its the 28th and its a Friday and the month is blah, blah, blah.  What about February?  To save time here is the code:

Inputs: movAvgPeriods(50);
vars: endOfMonth(false),theDayOfWeek(0),theMonth(0),theDayOfMonth(0),isLeapYear(False);

endOfMonth = false;
theDayOfWeek = dayOfWeek(date);
theMonth = month(date);
theDayOfMonth = dayOfMonth(date);
isLeapYear = mod(year(d),4) = 0;

// 29th of the month and a Friday
if theDayOfMonth = 29 and theDayOfWeek = 5 then
endOfMonth = True;
// 30th of the month and a Friday
if theDayOfMonth = 30 and theDayOfWeek = 5 then
endOfMonth = True;
// 31st of the month
if theDayOfMonth = 31 then
endOfMonth = True;
// 30th of the month and April, June, Sept, or Nov
if theDayOfMonth = 30 and (theMonth=4 or theMonth=6 or theMonth=9 or theMonth=11) then
endOfMonth = True;
// 28th of the month and February and not leap year
if theDayOfMonth = 28 and theMonth = 2 and not(isLeapYear) then
endOfMonth = True;
// 29th of the month and February and a leap year or 28th, 27th and a Friday
if theMonth = 2 and isLeapYear then
Begin
If theDayOfMonth = 29 or ((theDayOfMonth = 28 or theDayOfMonth = 27) and theDayOfWeek = 5) then
endOfMonth = True;
end;
// 28th of the month and Friday and April, June, Sept, or Nov
if theDayOfMonth = 28 and (theMonth = 4 or theMonth = 6 or
theMonth = 9 or theMonth =11) and theDayOfWeek = 5 then
endOfMonth = True;
// 27th, 28th of Feb and Friday
if theMonth = 2 and theDayOfWeek = 5 and theDayOfMonth = 27 then
endOfMonth = True;
// 26th of Feb and Friday and not LeapYear
if theMonth = 2 and theDayOfWeek = 5 and theDayOfMonth = 26 and not(isLeapYear) then
endOfMonth = True;
// Memorial day adjustment
If theMonth = 5 and theDayOfWeek = 5 and theDayOfMonth = 28 then
endOfMonth = True;
//Easter 2013 adjustment
If theMonth = 3 and year(d) = 113 and theDayOfMonth = 28 then
endOfMonth = True;
//Easter 2018 adjustment
If theMonth = 3 and year(d) = 118 and theDayOfMonth = 29 then
endOfMonth = True;

if endOfMonth and c > average(c,movAvgPeriods) then
Buy("BuyDay") this bar on close;

If C <average(c,movAvgPeriods) then
Sell("MovAvgExit") this bar on close;
If BarsSinceEntry=4 then
Sell("4days") this bar on close;
Last Day Of Month Function and Strategy

All the code is generic except for the hard code for days that are a consequence of Good Friday.

All this code because I couldn’t sneak a peek at the date of tomorrow.  Here are the results of trading the ES futures sans execution costs for the past 15 years.

Last Day Of Month Buy If C > 50 Day Mavg

What if it did the easy way and executed the open of the first bar of the month.

If c > average(c,50) and month(d) <> month(d of tomorrow) then 
buy next bar at open;

If barsSinceEntry >=3 then
sell next bar at open;

If marketPosition = 1 and c < average(c,50) then
sell next bar at open;
Buy First Day Of Month
First Day of Month If C > 50 Day Mavg

The results aren’t as good but it sure was easier to program.

TradingSimula-18 Version

Since you can use daily bars we can test this with my TradingSimula-18 Python platform.  And we will execute on the close of the month.  Here is the snippet of code that you have to concern yourself with.  Here I am using Sublime Text and utilizing their text collapsing tool to hide non-user code:

Small Snippet of TS-18 Code

This was easy to program in TS-18 because I do allow Future Leak – in other words I will let you sneak a peek at tomorrow’s values and make a decision today.  Now many people might say this is a huge boo-boo, but with great power comes great responsibility.  If you go in with eyes wide open, then you will only use the data to make things easier or even doable, but without cheating.  Because you are only going to cheat yourself.  Its in your best interest do follow the rules.  Here is the line that let’s you leak into the future.

If isNewMonth(myDate[curBar+1])

The curBar is today and curBar+1 is tomorrow.  So I am saying if tomorrow is the first day of the month then buy today’s close.  Here you are leaking into the future but not taking advantage of it.  We all know if today is the last day of the month, but try explaining that to a computer.  You saw the EasyLanguage code.  So things are made easier with future leak, but not taking advantage of .

Here is a quick video of running the TS-18 Module of 4 different markets.

 

Ratio Adjusted versus Point Adjusted Contracts in TradeStation Part 2

Thomas Stridsman quote from  his “Trading Systems That Work Book”

The benefits of the RAD contract also become evident when you want to put together a multimarket portfolio…For now we only state that the percentage based calculations do not take into consideration how many contracts you’re trading and, therefore, give each market an equal weighting in the portfolio.

The Stridsman Function I presented in the last post can be used to help normalize a portfolio of different markets.  Here is a two market portfolio (SP – 250price and JY -125Kprice contract sizes) on a PAD contract.

1-Contract SP and JY on PAD data

Here is the performance of the same portfolio on a RAD contract.

Equal rating of SP and JY on RAD data

 

The curve shapes are similar but look at the total profit and the nearly $125K draw down.  I was trying to replicate Thomas’ research so this data is from Jan. 1990 to Dec. 1999.  A time period where the price of the SP increased 3 FOLD!  Initially you would start trading 1 JY to 2 SP but by the time it was over you would be trading nearly 3 JY to 1 SP.  Had you traded at this allocation the PAD numbers would be nearly $240K in profit.  Now this change occurred through time so the percentage approach is applied continuously.  Also the RAD data allows for a somewhat “unrealistic” reinvestment or compounding mechanism.  Its unrealistic because you can’t trade a partial futures contract.  But it does give you a glimpse of the potential.  The PAD test does not show reinvestment of profit.  I have code for that if you want to research that a little bit more.  Remember everything is in terms of Dec. 31 1999 dollars.  That is another beauty of the RAD contract.

Another Stridsman Quote

Now, wait a minute, you say, those results are purely hypothetical.  How can I place all the trades in the same market at presumably the same point in time?  Well, you can’t, so that is a good and valid question; but let me ask you, can you place any of these trades for real, no matter, how you do it?  No, of course not.  They all represent foregone opportunities.  Isn’t it better then to at least place them hypothetically in today’s marketplace to get a feel for what might happen today, rather in a ten-year-old market situation to get a feel for how the situation was back then?  I think wall can agree that it is better to know what might happen today, rather than what happened ten years ago.

That is a very good point.  However, convenience and time is import and when developing an algorithm.  And most platforms, including my TS-18, are geared toward PAD data.  However TS-18 can look at the entire portfolio balance and all the market data for each market up to that point in time and can adjust/normalize based on portfolio and data metrics.  However, I will add a percentage module a little later, but I would definitely use the StridsmanFunc that I presented in the last post to validate/verify your algorithm in today’s market place if using TradeStation.

Email me if you want the ELD of the function.

Ratio Adjusted versus Pointed Adjusted Contracts in TradeStation – Part 1

If you play around with TradeStation’s custom futures capabilities you will discover you can create different adjusted continuous contracts.  Take a look at this picture:

Panama vs Ratio Adjusted

Both charts look the same and the trades enter and exit at the same locations in relation to the respective price charts.   However, take a look at the Price Scale on the right and the following pictures.

As you can see from the P/L from each trade list there is a big difference.  The top list is using RAD and the second is the generally accepted Panama Adjusted Data (PAD.)  Ratio adjusted data takes the percentage difference between the expiring contract and the new contract and propagates the value throughout the entire back history.  This is different than the PAD we have all used, where the actual point difference is propagated.  These two forms of adjustment have their own pros and cons but many industry leaders prefer the RAD.  I will go over a little bit of the theory in my next post, but in the mean time I will direct you to Thomas Stridsman’s excellent work on the subject in his book, “Trading Systems That Work – Building and Evaluating Effective Trading Systems”.

Here is another look at draw down metrics between the two formats.

RAD V PAD DrawDown

Who would want to trade a system on 1 contract of crude and have a $174K draw down?  Well you can’t look at it like that.  Back in 2008 crude was trading at $100 X 1000 = $100,000 a contract.  Today May 11th 2020 it is around $25,000.  So a drawdown of $44K back then would be more like $176K in today’s terms.  In my next post I will go over the theory of  RAD, but for right now you just need to basically ignore TradeStation’s built in performance metrics and use this function that I developed in most part by looking at Thomas’ book.

//Name this function StridsmanFunc1

Vars: FName(""), offset(1),TotTr(0), Prof(0), CumProf(1), ETop(1), TopBar(0), Toplnt(0),BotBar(0), Botlnt(0), EBot(1), EDraw(1), TradeStr2( "" );
Arrays: tradesPerArr[1000](0),drawDownArr[1000](0);
Vars: myEntryPrice(0),myEntryDate(0),myMarketPosition(0),myExitDate(0),myExitPrice(0);
If CurrentBar = 1 Then
Begin
FName = "C:\Temp\" + LeftStr(GetSymbolName, 3) + ".csv";
FileDelete(FName);
TradeStr2 = "E Date" + "," + "Position" + "," + "E Price" + "," + "X Date" +"," + "X Price" + "," + "Profit" + "," + "Cum. prof." + "," + "E-Top" + "," +"E-Bottom" + "," + "Flat time" + "," + "Run up" + "," + "Drawdown" +NewLine;
FileAppend(FName, TradeStr2);
End;
TotTr = TotalTrades;
If TotTr > TotTr[1] or (lastBarOnChart and marketPosition <> 0) Then
Begin

if TotTr > TotTr[1] then
begin
if (EntryPrice(1) <> 0) then Prof = 1 + PositionProfit(1)/(EntryPrice(1) * BigPointValue);
End
else
begin
Value99 = iff(marketPosition = 1,c - entryPrice, entryPrice - c);
Prof = 1 + (Value99*bigPointValue) /(Entryprice *BigPointValue);
// print(d," StridsmanFunc1 ",Value99," ",Prof," ",(Value99*bigPointValue) /(Entryprice *BigPointValue):5:4);
TotTr = totTr + 1;
end;
tradesPerArr[TotTr] = Prof - 1;
CumProf = CumProf * Prof;
ETop = MaxList(ETop, CumProf);
If ETop > ETop[1] Then
Begin
TopBar = CurrentBar;
EBot = ETop;
End;

EBot = MinList(EBot, CumProf);

If EBot<EBot[1] Then BotBar = CurrentBar;

Toplnt = CurrentBar - TopBar;

Botlnt = CurrentBar - BotBar;

if ETop <> 0 then EDraw = CumProf / ETop;

drawDownArr[TotTr] = (EDraw - 1);

myEntryDate = EntryDate(1);
myMarketPosition = MarketPosition(1);
myEntryPrice = EntryPrice(1);
myExitDate = ExitDate(1);
myExitPrice = ExitPrice(1);
If lastBarOnChart and marketPosition <> 0 then
Begin
myEntryDate = EntryDate(0);
myMarketPosition = MarketPosition(0);
myEntryPrice = EntryPrice(0);
myExitDate = d;
myExitPrice =c;
end;
TradeStr2 = NumToStr(myEntryDate, 0) + "," +NumToStr(myMarketPosition, 0) + "," + NumToStr(myEntryPrice, 2) + ","
+ NumToStr(myExitDate, 0) + "," + NumToStr(myExitPrice, 2) + ","+ NumToStr((Prof - 1) * 100, 2) + "," + NumToStr((CumProf - 1) *100, 2) + ","
+ NumToStr((ETop - 1) * 100, 2) + "," + NumToStr((EBot - 1) * 100, 2) + "," + NumToStr(Toplnt, 0) + "," + NumToStr(Botlnt, 0) + "," + NumToStr((EDraw - 1) * 100, 2) +
NewLine;

FileAppend(FName, TradeStr2);
End;
vars: tradeStr3(""),
ii(0),avgTrade(0),avgTrade$(0),cumProf$(0),trdSum(0),
stdDevTrade(0),stdDevTrade$(0),
profFactor(0),winTrades(0),lossTrades(0),perWins(0),perLosers(0),
largestWin(0),largestWin$(0),largestLoss(0),largestLoss$(0),avgProf(0),avgProf$(0),
winSum(0),lossSum(0),avgWin(0),avgWin$(0),avgLoss(0),avgLoss$(0),maxDD(0),maxDD$(0),cumProfit(0),cumProfit$(0);

If lastBarOnChart then
begin
stdDevTrade = standardDevArray(tradesPerArr,TotTr,1);
stdDevTrade$ = stdDevTrade*c*bigPointValue;
For ii = 1 to TotTr
Begin
trdSum = trdSum + tradesPerArr[ii];
// print(d," ",ii," ",tradesPerArr[ii]);
If tradesPerArr[ii] > 0 then
begin
winTrades = winTrades + 1;
winSum = winSum + tradesPerArr[ii];
end;
If tradesPerArr[ii] <=0 then
begin
lossTrades = lossTrades + 1;
lossSum = lossSum + tradesPerArr[ii];
end;
If tradesPerArr[ii] > largestWin then
begin
largestWin = tradesPerArr[ii];
// print("LargestWin Found ",largestWin);
end;
If tradesPerArr[ii] < largestLoss then largestLoss = tradesPerArr[ii];
If drawDownArr[ii] < maxDD then maxDD = drawDownArr[ii];
end;
// print("TradeSum: ",trdSum);
if TotTr <> 0 then avgTrade = trdSum/TotTr;
avgTrade$ = avgTrade*c*bigPointValue;
largestWin = largestWin;
largestLoss = largestLoss;
largestWin$ = largestWin*c*bigPointValue;
largestLoss$ = largestLoss*c*bigPointValue;
if TotTr <> 0 then perWins = winTrades/TotTr;
if TotTr <> 0 then perLosers = lossTrades/TotTr;
If winTrades <> 0 then avgWin = winSum / winTrades;
avgWin$ = avgWin*c*bigPointValue;
if lossTrades <> 0 then avgLoss= lossSum / lossTrades;
avgLoss$ = avgLoss*c*bigPointValue;
maxDD$ = maxDD *c*bigPointValue;
if lossTrades <>0 and avgLoss$ <> 0 then profFactor = (winTrades*avgWin$)/(lossTrades*avgLoss$);
CumProf = cumProf - 1;
CumProf$ = cumProf*c*bigPointValue;

TradeStr3 = "Total Trades,,"+NumToStr(TotTr,0)+",Num. Winners,"+NumToStr(winTrades,0)+","+NumToStr(perWins,3)+", Num. Losses,"+NumToStr(lossTrades,0)+","+NumToStr(perLosers,3)+NewLine+
"Profit Factor,,"+NumToStr(profFactor,3)+",Largest Win ,"+NumToStr(largestWin,3)+","+NumToStr(largestWin$,0)+",Largest Loss,"+NumToStr(largestLoss,3)+","+NumToStr(largestLoss$,0)+NewLine+
"Avg Profit,"+NumToStr(avgTrade,3)+","+NumToSTr(avgTrade$,0)+",Avg Win,"+NumToStr(avgWin,3)+","+NumToStr(avgWin$,0)+",Avg Loss,"+NumToStr(avgLoss,3)+","+NumToStr(avgLoss$,0)+NewLine+
"Std. Dev,"+NumToStr(stdDevTrade,3)+","+NumToStr(stdDevTrade$,0)+",Cum Profit,"+NumToStr(cumProf,3)+","+NumToStr(cumProf$,3)+",Draw Down,"+numToStr(maxDD,3)+","+numToStr(maxDD$,0)+NewLine;
FileAppend(FName, TradeStr3);
{ Print("Total Trades ",totalTrades," Num. Winners ",winTrades," ",perWins," Num. Losses ",lossTrades," ",perLosers);
Print("Profit Factor ",profFactor," Largest Win ",largestWin:5:2," ",largestWin$," Largest Loss ",largestLoss:5:2," ",largestLoss$);
Print("Avg Profit ",avgTrade," ",avgTrade$," Avg Win ",avgWin," ",avgWin$," Avg Loss ",avgLoss," ",avgLoss$);
Print("St Dev ",stdDevTrade," ",stdDevTrade$," Cum Profit ",cumProf," ",cumProf$," Drawdown ",maxDD," ",maxDD$);}


end;



StridsmanFunc1 = 1;
Conversion of Performance Metrics to Percentages Instead of $Dollars

This function will out put a file that looks like this.  Go ahead and play with the code – all you have to do is call the function from within an existing strategy that you are working with.  In part two I will go over the code and explain what its doing and how arrays and strings were used to archive the trade history and print out this nifty table.

Stridsman Function Output.

In this output if you treat the return from each trade as a function of the entry price and accumulate the returns you can convert the value to today’s current market price of the underlying.  In this case a 15 -year test going through the end of last year, ended up making almost $70K.

RAD TradeStation Metrics:

Profit $350K – Draw Down $140K

PAD TradeStation Metrics:

Profit $89K – Draw Down $45K

Stridsman Func on RAD:

Profit $70K – Draw Down $48K

At this point you can definitely determine that the typical RAD/TS metrics are not all that usuable.  The PAD/TS results look very similar to RAD/StridsmanFunc results.  Stay tuned for my next post and I will hopefully explain why RAD/StridsmanFunc is probably the most accurate performance metrics of the three.

A Quant’s ToolBox: Beautiful Soup, Python, Excel and EasyLanguage

Many Times It Takes Multiple Tools to Get the Job Done

Just like a mechanic, a Quant needs tools to accomplish many programming tasks.  In this post, I use a toolbox to construct an EasyLanguage function that will test a date and determine if it is considered a Holiday in the eyes of the NYSE.

Why a Holiday Function?

TradeStation will pump holiday data into a chart and then later go back and take it out of the database.  Many times the data will only be removed from the daily database, but still persist in the intraday database.  Many mechanical day traders don’t want to trade on a shortened holiday session or use the data for indicator/signal calculations.  Here is an example of a gold chart reflecting President’s Day data in the intra-day data and not in the daily.

Holiday Data Throws A Monkey Wrench Into the Works

This affects many stock index day traders.  Especially if automation is turned on.  At the end of this post I provide a link to my youTube channel for a complete tutorial on the use of these tools to accomplish this task.  It goes along with this post.

First Get The Data

I searched the web for a list of historical holiday dates and came across this:

Historic List of Holidays and Their Dates

You might be able to find this in a easier to use format, but this was perfect for this post.

Extract Data with Beautiful Soup

Here is where Python and the plethora of its libraries come in handy.  I used pip to install the requests and the bs4 libraries.  If this sounds like Latin to you drop me an email and I will shoot you some instructions on how to install these libraries.  If you have Python, then you have the download/install tool known as pip.

Here is the Python code.  Don’t worry it is quite short.

# Created:     24/02/2020
# Copyright: (c) George 2020
# Licence: <your licence>
#-------------------------------------------------------------------------------

import requests
from bs4 import BeautifulSoup

url = 'http://www.market-holidays.com/'
page = requests.get(url)
soup = BeautifulSoup(page.text,'html.parser')
print(soup.title.text)
all_tables = soup.findAll('table')
#print (all_tables)
print (len(all_tables))
#print (all_tables[0])
print("***")
a = list()
b = list()
c = list()
#print(all_tables[0].find_all('tr')[0].text)
for numTables in range(len(all_tables)-1):
for rows in all_tables[numTables].find_all('tr'):
a.append(rows.find_all('td')[0].text)
b.append(rows.find_all('td')[1].text)

for j in range(len(a)-1):
print(a[j],"-",b[j])
Using Beautiful Soup to Extract Table Data

As you can see this is very simple code.  First I set the variable url to the website where the holidays are located.  I Googled on how to do this – another cool thing about Python – tons of users.  I pulled the data from the website and stuffed it into the page object.  The page object has several attributes (properties) and one of them  is a text representation of the entire page.  I pass this text to the BeautifulSoup library and inform it to parse it with the html.parser.  In other words, prepare to extract certain values based on html tags.  All_tables contains all of the tables that were parsed from the text file using Soup.  Don’t worry how this works, as its not important, just use it as a tool.  In my younger days as a programmer I would have delved into how this works, but it wouldn’t be worth the time because I just need the data to carry out my objective; this is one of the reasons classically trained programmers never pick up the object concept.  Now that I have all the tables in a list I can loop through each row in each table.  It looked liker there were 9 rows and 2 columns in the different sections of the website, but I didn’t know for sure so I just let the library figure this out for me.  So I played around with the code and found out that the first two columns of the table contained the name of the holiday and the date of the holiday.  So, I simply stuffed the text values of these columns in two lists:  a and b.  Finally I print out the contents of the two lists, separated by a hyphen, into the Interpreter window.  At this point I could simply carry on with Python and create the EasyLanguage statements and fill in the data I need.  But I wanted to play around with Excel in case readers didn’t want to go the Python route.  I could have used a powerful editor such as NotePad++ to extract the data from the website in place of Python.  GREP could have done this.  GREP is an editor tool to find and replace expressions in a text file.

Use Excel to Create Actual EasyLanguage – Really!

I created a new spreadsheet.  I used Excel, but you could use any spreadsheet software.   I first created a prototype of the code I would need to encapsulate the data into array structures.  Here is what I want the code to look like:

Arrays: holidayName[300](""),holidayDate[300](0);

holidayName[1]="New Year's Day "; holidayDate[1]=19900101;
Code Prototype

This is just the first few lines of the function prototype.  But you can notice a repetitive pattern.  The array names stay the same – the only values that change are the array elements and the array indices.  Computers love repetitiveness.  I can use this information a build a spreadsheet – take a look.

Type EasyLanguage Into the Columns and Fill Down!

I haven’t copied the data that I got out of Python just yet.  That will be step 2.  Column A has the first array name holidayName (notice I put the left square [ bracket in the column as well).  Column B will contain the array index and this is a formula.  Column C contains ]=”.  Column D will contain the actual holiday name and Column E contains theThese columns will build the holidayName array.  Columns G throuh K will build the holidayDates array.    Notice column  H  equals column B.  So whatever we do to column B (Index) will be reflected in Column H (Index).  So we have basically put all the parts of the EasyLanguage into  Columns A thru K. 

Excel provides tools for manipulating strings and text.  I will use the Concat function to build my EasyLanguageBut before I can use Concat all the stuff I want to string together must be in a string or text format.  The only column in the first five that is not a string is Column B.  So the first thing I have to do is convert it to text.  First copy the column and paste special as values.  Then go to your Data Tab and select Text To Columns. 

Text To Columns

It will ask if fixed width or delimited – I don’t think it matters which you pick.  On step 3 select text.

Text To Columns – A Powerful Tool

The Text To Columns button will solve 90% of your formatting issues in Excel.    Once you do this you will notice the numbers will be left justified – this signifies a text format.  Now lets select another sheet in the workbook and past the holiday data.

Copy Holiday Data Into Another Spreadsheet

New Year's Day - January 1, 2021
Martin Luther King, Jr. Day - January 18, 2021
Washington's Birthday (Presidents' Day) - February 15, 2021
Good Friday - April 2, 2021
Memorial Day - May 31, 2021
Independence Day - July 5, 2021
Labor Day - September 6, 2021
Thanksgiving - November 25, 2021
Christmas - December 24, 2021
New Year's Day - January 1, 2020
Martin Luther King, Jr. Day - January 20, 2020
Washington's Birthday (Presidents' Day) - February 17, 2020
Good Friday - April 10, 2020
Memorial Day - May 25, 2020
Holiday Output

 

Data Is In Column A

Text To Columns to the rescue.  Here I will separate the data with the “-” as delimiter and tell Excel to import the second column in Date format as MDY.  

Text To Columns with “-” as the delimiter and MDY as Column B Format

Now once the data is split accordingly into two columns with the correct format – we need to convert the date column into a string.

Convert Date to a String

Now the last couple of steps are really easy.  Once you have converted the date to a string, copy Column A and past into Column D from the first spreadsheet.  Since this is text, you can simply copy and then paste.  Now go back to Sheet 2 and copy Column C and paste special [values] in Column J on Sheet 1.  All we need to do now is concatenate the strings in Columns A thru E for the EasyLanguage for the holidayName array.  Columns G thru K will be concatenated for the holidayDate array.  Take a look.

Concatenate all the strings to create the EasyLanguage

Now create a function in the EasyLanguage editor and name it IsHoliday and have it return a boolean value.  Then all you need to do is copy/paste Columns F and L and the data from the website will now be available for you use.   Here is a portion of the function code.  Notice I declare the holidayNameStr as a stringRef?  I did this so I could change the variable in the function and pass it back to the calling routine.

Inputs : testDate(numericSeries),holidayNameStr(stringRef);

Arrays: holidayName[300](""),holidayDate[300](0);

holidayNameStr = "";

holidayName[1]="New Year's Day "; holidayDate[1]=19900101;
holidayName[2]="Martin Luther King, Jr. Day "; holidayDate[2]=19900115;
holidayName[3]="Washington's Birthday (Presidents' Day) "; holidayDate[3]=19900219;
holidayName[4]="Good Friday "; holidayDate[4]=19900413;
holidayName[5]="Memorial Day "; holidayDate[5]=19900528;
holidayName[6]="Independence Day "; holidayDate[6]=19900704;
holidayName[7]="Labor Day "; holidayDate[7]=19900903;
holidayName[8]="Thanksgiving "; holidayDate[8]=19901122;
holidayName[9]="New Year's Day "; holidayDate[9]=19910101;
holidayName[10]="Martin Luther King, Jr. Day "; holidayDate[10]=19910121;
holidayName[11]="Washington's Birthday (Presidents' Day) "; holidayDate[11]=19910218;

// There are 287 holiays in the database.
// Here is the looping mechanism to compare the data that is passed
// to the database

vars: j(0);
IsHoliday = False;
For j=1 to 287
Begin
If testDate = holidayDate[j] - 19000000 then
Begin
holidayNameStr = holidayName[j] + " " + numToStr(holidayDate[j],0);
IsHoliday = True;
end;
end;
A Snippet Of The Function - Including Header and Looping Mechanism

This was a pretty long tutorial and might be difficult to follow along.  If you want to watch my video, then go to this link.

I created this post to demonstrate the need to have several tools at your disposal if you really want to become a Quant programmer.  How you use those tools is up to you.  Also you will be able to take bits and pieces out of this post and use in other ways to get the data you really need.  I could have skipped the entire Excel portion of the post and just did everything in Python.  But I know a lot of Quants that just love spreadsheets.  You have to continually hone your craft in this business.   And you can’t let one software application limit your creativity.  If you have a problem always be on the lookout for alternative platforms and/or languages to help you solve it.

 

 

A Christmas Project for TradeStation Day-Traders

Here is a neat little day trader system that takes advantage of what some technicians call a “CLEAR OUT” trade.  Basically traders push the market through yesterday’s high and then when everybody jumps on board they pull the rug out from beneath you.  This strategy tries to take advantage of this.  As is its OK, but it could be made into a complete system with some filtering.  Its a neat base to start your day-trading schemes from.

But first have you ever encountered this one when you only want to go long once during the day.

I have logic that examines marketPosition, and if it changes from a non 1 value to 1 then I increment buysToday.  Since there isn’t an intervening bar to establish a change in marketPosition, then buysToday does not get incremented and another buy order is issued.  I don’t want this.  Remember to plot on the @ES.D.

Here’s how I fixed it and also the source of the CLEAR-OUT day-trade in its entirety.  I have a $500 stop and a $350 take profit, but it simply trades way too often.  Have fun with this one – let me now if you come up with something.

inputs: clearOutAmtPer(0.1),prot$Stop(325),prof$Obj(500),lastTradeTime(1530);

vars: coBuy(false),coSell(false),buysToday(0),sellsToday(0),mp(0),totNumTrades(0);

If d <> d[1] then
Begin
coBuy = false;
coSell = false;
buysToday = 0;
sellsToday = 0;
totNumTrades = totalTrades;
end;


mp = marketPosition;
If mp[1] <> mp and mp = 1 then buysToday = buysToday + 1;
If mp[1] <> mp and mp = -1 then sellsToday = sellsToday + 1;

If h > highD(1) + clearOutAmtPer * (highD(1) - lowD(1)) then coSell = true;
If l < lowD(1) - clearOutAmtPer * (highD(1) - lowD(1)) then coBuy = true;

If totNumTrades <> totalTrades and mp = 0 and mp[1] = 0 and positionProfit(1) < 0 and entryPrice(1) > exitPrice(1) then buysToday = buysToday + 1;
If totNumTrades <> totalTrades and mp = 0 and mp[1] = 0 and positionProfit(1) < 0 and entryPrice(1) < exitPrice(1) then sellsToday =sellsToday + 1;

totNumTrades = totalTrades;

If buysToday = 0 and t < lastTradeTime and coBuy = true then buy ("COBuy") next bar at lowD(1) + minMove/priceScale stop;
If sellsToday = 0 and t < lastTradeTime and coSell = true then sellShort ("COSell") next bar at highD(1) - minMove/priceScale stop;

setStopLoss(prot$stop);
Setprofittarget(prof$Obj);
setExitOnClose;
Look at lines 22 and 23 - the entry/exit same bar fix

Testing Keith Fitschen’s Bar Scoring with Pattern Smasher

Keith’s Book

Thanks to MJ for planting the seed for this post.  If you were one of the lucky ones to get Keith’s “Building Reliable Trading SystemsTradable Strategies that Perform as They Backtest and Meet Your Risk-Reward Goals”  book by John Wiley 2013 at the list price of $75 count yourself lucky.  The book sells for a multiple of that on Amazon.com.  Is there anything earth shattering in the book you might ask?  I wouldn’t necessarily say that, but there are some very well thought out and researched topics that most traders would find of interest.

Bar Scoring

In his book Keith discusses the concept of bar-scoring.  In Keith’s words, “Bar-scoring is an objective way to classify an instrument’s movement potential every bar.  The two parts of the bar-scoring are the criterion and the resultant profit X days hence.”  Keith provides several bar scoring techniques, but I highlight just one.

Keith broke these patterns down into the relationship of the close to the open, and close in the upper half of the range; close greater than the open and close in the lower half of the range.  He extended the total number of types to 8 by adding the relationship of the close of the bar to yesterdays bar.

The PatternSmasher code can run through a binary representation

for each pattern and test holding the position for an optimizable number of days.  It can also check for long and short positions.  The original Pattern Smasher code used a for-loop to create patterns that were then compared to the real life facsimile.  In this code it was easier to just manually define the patterns and assign them the binary string.

if c[0]> c[1] and c[0] > o[0] and c[0] > (h[0] + l[0])/2  then patternString = "----";
if c[0]> c[1] and c[0] > o[0] and c[0] < (h[0] + l[0])/2 then patternString = "---+";
if c[0]> c[1] and c[0] < o[0] and c[0] > (h[0] + l[0])/2 then patternString = "--+-";
if c[0]> c[1] and c[0] < o[0] and c[0] < (h[0] + l[0])/2 then patternString = "--++";
if c[0]< c[1] and c[0] > o[0] and c[0] > (h[0] + l[0])/2 then patternString = "-+--";
if c[0]< c[1] and c[0] > o[0] and c[0] < (h[0] + l[0])/2 then patternString = "-+-+";
if c[0]< c[1] and c[0] < o[0] and c[0] > (h[0] + l[0])/2 then patternString = "-++-";
if c[0]< c[1] and c[0] < o[0] and c[0] < (h[0] + l[0])/2 then patternString = "-+++";
Manual Pattern Designations

Please check my code for any errors.  Here I go through the 8 different relationships and assign them to a Patter String.  “-+++”  represents pattern number (7 ) or type (7 + 1 = 8 – my strings start out at 0).  You can then optimize the test pattern and if the test pattern matches the actual pattern, then the Pattern Smasher takes the trade  on the opening of the next bar and holds it for the number of days you specify.  You an also designate long and short positions in the code.  Here I optimized the 8 patterns going long and short and holding from 1-4 days.

Here is the equity curve!  Remember these are Hypothetical Results with $0 commission/slippage and historic performance is not necessarily indicative of future results.  Educational purposes only!  This is tested on ES.D

Play around with the code and let me know if you find any errors or any improvements.

input: patternTests(8),orbAmount(0.20),LorS(1),holdDays(0),atrAvgLen(10),enterNextBarAtOpen(true);

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

{written by George Pruitt -- copyright 2019 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;


//example patternTests = 0 -- > 0000
//example patternTests = 1 -- > 0001
//example patternTests = 2 -- > 0010
//example patternTests = 3 -- > 0011
//example patternTests = 4 -- > 0100
//example patternTests = 5 -- > 0101
//example patternTests = 6 -- > 0110
//example patternTests = 7 -- > 0111

if(value1 >= 0) then
begin

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

if(value2 >= 7) 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;

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

patternString = "";

if c[0]> c[1] and c[0] > o[0] and c[0] > (h[0] + l[0])/2 then patternString = "----";
if c[0]> c[1] and c[0] > o[0] and c[0] < (h[0] + l[0])/2 then patternString = "---+";
if c[0]> c[1] and c[0] < o[0] and c[0] > (h[0] + l[0])/2 then patternString = "--+-";
if c[0]> c[1] and c[0] < o[0] and c[0] < (h[0] + l[0])/2 then patternString = "--++";
if c[0]< c[1] and c[0] > o[0] and c[0] > (h[0] + l[0])/2 then patternString = "-+--";
if c[0]< c[1] and c[0] > o[0] and c[0] < (h[0] + l[0])/2 then patternString = "-+-+";
if c[0]< c[1] and c[0] < o[0] and c[0] > (h[0] + l[0])/2 then patternString = "-++-";
if c[0]< c[1] and c[0] < o[0] and c[0] < (h[0] + l[0])/2 then patternString = "-+++";


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 (enterNextBarAtOpen) then
begin
if(LorS = 2) then SellShort("PatternSell") next bar on open;
if(LorS = 1) then buy("PatternBuy") next bar at open;
end
else
begin
if(LorS = 2) then SellShort("PatternSellBO") next bar at open of tomorrow - avgTrueRange(atrAvgLen) * orbAmount stop;
if(LorS = 1) then buy("PatternBuyBO") next bar at open of tomorrow + avgTrueRange(atrAvgLen) * orbAmount stop;
end;


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;
Bar Scoring Testing Template

Passing a Two Dimensional Array to a Function- EasyLanguage

In this post, I want to share some code that I was surprised wasn’t really all that accessible.  I was in need of passing a 2-D array to a function and couldn’t remember the exact syntax.  The semantics of the problem is pretty straightforward.

  • Build Array
  • Pass Array as Reference
  • Unpack Array
  • Do Calculation

A 2D Array Is Just Like a Table

Any readers please correct me if I am wrong here, but you can’t use dynamic arrays on any dimension greater than 1.  A dynamic array is one where you don’t initially know the size of the array so you leave it blank and TradeStation allocates memory dynamically.  Also, there are a plethora of built-in functions that only work with dynamic arrays.  Once we step up in dimension then that all goes out the window.  I know what you are thinking, just use multiple dynamic arrays.  Sometimes you want to keep the accounting down to a minimum and a matrix or table fits this bill.  So if you do use multi-dimension arrays just remember you will need to know the total number of rows and columns in your table.  Table?  What do you mean table?  I thought we were talking about arrays.  Well, we are and a two-dimensional array can look like a table with rows as your first index and columns as your second.  Just like an Excel spreadsheet.  First, let’s create a very small and simple table in EasyLangauge:

array: testArray[2,2](0);

Once
begin
testArray[0,0] = 100;
testArray[0,1] = 5;

testArray[1,0] = 200;
testArray[1,1] = 10;

testArray[2,0] = 300;
testArray[2,1] = 7.5;

Value2 = getArrayHH(testArray,2,2);
Print (value2);

end;
Create a Very Small Table in Our Sandbox

 

My EasyLanguage Sandbox

You will notice I used the keyword Once.  I use this whenever I want to play around with some code in my EasyLanguage Sandbox.  Huh?  In programmer-ese a Sandbox is a quick and dirty environment that runs very quickly and requires nearly zero overhead.  So here I apply the code to print out just one line of output when applied to any chart.   Notice how I declare the 2-D array – use the keyword Array: and the name of the array or table and allocate the total number of rows as the first argument and the total number of columns as the second argument.  Also notice the arguments are separated by a comma and enclosed in square brackets.  The following value enclosed in parentheses is the default value of every element in the array.    Remember arrays are zero-based in EasyLanguage.  So if you dimension an array with the number 2 you access the rows with 0 and 1 and 2.  Same goes for columns as well.  Did you catch that.  If you dimension an array with the number 2 shouldn’t there be just 2 rows?  Well in EasyLanguage when you dimension an array you get a free element at row 0 and column 0.  In EasyLanguage you can just ignore row 0 and column 0 if you like.  Here is the code if you ignore row 0 and column 0.

Should I Use Row 0 and Column Zero – It’s A Preference

array: testArray[2,2](0);

Once
begin
testArray[1,1] = 100;
testArray[1,2] = 5;

testArray[2,1] = 200;
testArray[2,2] = 10;

Value2 = getArrayHH(testArray,2,2);
Print (value2);

end;
Ignore the Elements at Row 0 and Column 0

Out Of Bounds

Even though you get one free row you still cannot go beyond the boundaries of the array size.  If I were to say something like:

testArray[3,1] = 300;

I would get an error message.  If you want to work with a zero element then all of your code must coincide with that.  If not, then your code shouldn’t try to access row 0 or column 0.    Okay here is the function that I programmed for this little test:

inputs: tempArray[x,y](numericArray),numOfRows(numericSimple),whichColumn(numericSimple);

vars: j(0),tempHi(0),cnt(0);

For j= 1 to numOfRows
Begin
print(j," ",tempArray[j,whichColumn]);
If tempArray[j,whichColumn] > tempHi then tempHi = tempArray[j,whichColumn];
end;

GetArrayHH = tempHi;
Function That Utilizes a 2D Array

Notice in the inputs how I declare the tempArray with the values x and y.  You could have used a and b if you like or any other letters.  This informs the compiler to expect a 2D array.  It doesn’t know the size and that’s not important as long as you control the boundaries from the calling routine.  The second parameter is the number of rows in the table and the third parameter is the column I am interested in.  In this example, I am interested in column 2.

The Caller Function is the QuarterBack – Make Sure You Don’t Throw it Out of Bounds

Again this function assumes the caller will prevent stepping out of bounds.  I loop the number of rows in the table and examine the second column and keep track of the highest value.  I then return the highest column value.

This was a simple post, but remembering the syntax can be tough and know that EasyLangauge is zero-based when it comes to arrays is nice to know.   You can also use this format for your own Sandbox.

 

 

Using a Dictionary to Create a Trading System

Dictionary Recap

Last month’s post on using the elcollections dictionary was a little thin so I wanted to elaborate on it and also develop a trading system around the best patterns that are stored in the dictionary.  The concept of the dictionary exists in most programming languages and almost all the time uses the (key)–>value model.  Just like a regular dictionary a word or a key has a unique definition or value.  In the last post, we stored the cumulative 3-day rate of return in keys that looked like “+ + – –” or “+ – – +“.  We will build off this and create a trading system that finds the best pattern historically based on average return.  Since its rather difficult to store serial data in a Dictionary I chose to use Wilder’s smoothing average function.

Ideally, I Would Have Liked to Use a Nested Dictionary

Initially, I played around with the idea of the pattern key pointing to another dictionary that contained not only the cumulative return but also the frequency that each pattern hit up.  A dictionary is designed to have  unique key–> to one value paradigm.  Remember the keys are strings.  I wanted to have unique key–> to multiple values. And you can do this but it’s rather complicated.  If someone wants to do this and share, that would be great.  AndroidMarvin has written an excellent manual on OOEL and it can be found on the TradeStation forums.  

Ended Up Using A Dictionary With 2*Keys Plus an Array

So I didn’t want to take the time to figure out the nested dictionary approach or a vector of dictionaries – it gets deep quick.  So following the dictionary paradigm I came up with the idea that words have synonyms and those definitions are related to the original word.  So in addition to having keys like “+ + – -” or “- – + -” I added keys like “0”, “1” or “15”.  For every  + or – key string there exists a parallel key like “0” or “15”.  Here is what it looks like:

–  –  –  –  = “0”
– – – + = “1”
– – + – = “2”

You can probably see the pattern here.  Every “+” represents a 1 and every “0” represent 0 in a binary-based numbering system.  In the + or – key I store the last value of Wilders average and in the numeric string equivalent, I store the frequency of the pattern.

Converting String Keys to Numbers [Back and Forth]

To use this pattern mapping I had to be able to convert the “++–” to a number and then to a string.  I used the numeric string representation as a dictionary key and the number as an index into an array that store the pattern frequency.  Here is the method I used for this conversion.  Remember a method is just a function local to the analysis technique it is written.

//Lets convert the string to unique number
method int convertPatternString2Num(string pattString)
Vars: int pattLen, int idx, int pattNumber;
begin
pattLen = strLen(pattString);
pattNumber = 0;
For idx = pattLen-1 downto 0
Begin
If MidStr(pattString,pattLen-idx,1) = "+" then pattNumber = pattNumber + power(2,idx);
end;
Return (pattNumber);
end;
String Pattern to Number

This is a simple method that parses the string from left to right and if there is a “+” it is raised to the power(2,idx) where idx is the location of “+” in the string.  So “+  +  –  –  ” turns out to be 8 + 4 + 0 + 0 or 12.

Once I retrieve the number I used it to index into my array and increment the frequency count by one.  And then store the frequency count in the correct slot in the dictionary.

patternNumber = convertPatternString2Num(patternString); 
//Keep track of pattern hits
patternCountArray[patternNumber] = patternCountArray[patternNumber] + 1;
//Convert pattern number to a string do use as a Dictionary Key
patternStringNum = numToStr(patternNumber,2);
//Populate the pattern number string key with the number of hits
patternDict[patternStringNum] = patternCountArray[patternNumber] astype double;
Store Value In Array and Dictionary

Calculating Wilder’s Average Return and Storing in Dictionary

Once I have stored an instance of each pattern [16] and the frequency of each pattern[16] I calculate the average return of each pattern and store that in the dictionary as well.

//Calculate the percentage change after the displaced pattern hits
Value1 = (c - c[2])/c[2]*100;
//Populate the dictionary with 4 ("++--") day pattern and the percent change
if patternDict.Contains(patternString) then
Begin
patternDict[patternString] = (patternDict[patternString] astype double *
(patternDict[patternStringNum] astype double - 1.00) + Value1) / patternDict[patternStringNum] astype double;
end
Else
begin
patternDict[patternString] = value1;
// print("Initiating: ",patternDict[patternString] astype double);
end;
(pAvg * (N-1) + return) / N

When you extract a value from a collection you must us an identifier to expresses its data type or you will get an error message : patternDict[patternString] holds a double value {a real number}  as well as patternDict[patternStringNum] – so I have to use the keyword asType.  Once I do my calculation I ram the new value right back into the dictionary in the exact same slot.  If the pattern string is not in the dictionary (first time), then the Else statement inserts the initial three-day rate of return.

Sort Through All of The Patterns and Find the Best!

The values in a dictionary are stored in alphabetic order and the string patterns are arranged in the first 16 keys.  So I loop through those first sixteen keys and extract the highest return value as the “best pattern.”

//  get the best pattern that produces the best average 3 bar return
vars: hiPattRet(0),bestPattString("");
If patternDict.Count > 29 then
Begin
index = patternDict.Keys;
values = patternDict.Values;
hiPattRet = 0;
For iCnt = 0 to 15
Begin
If values[iCnt] astype double > hiPattRet then
Begin
hiPattRet = values[iCnt] astype double ;
bestPattString = index[iCnt] astype string;
end;
end;
// print(Date," BestPattString ",bestPattString," ",hiPattRet:8:4," CurrPattString ",currPattString);
end;
Extract Best Pattern From All History

If Today’s Pattern Matches the Best Then Take the Trade

// if the current pattern matches the best pattern then bar next bar at open
If currPattString = BestPattString then buy next bar at open;
// cover in three days
If barsSinceEntry > 2 then sell next bar at open;
Does Today Match the Best Pattern?

If today matches the best pattern then buy and cover after the second day.

Conclusion

I didn’t know if this code was worth proffering up but I decided to posit it because it contained a plethora of programming concepts: dictionary, method, string manipulation, and array.  I am sure there is a much better way to write this code but at least this gets the point across.

Contents of Dictionary at End of Run

++++    0.06
+++- -0.08
++-+ 0.12
++-- -0.18
+-++ 0.08
+-+- 0.40
+--+ -0.46
+--- 0.34
-+++ 0.20
-++- 0.10
-+-+ 0.23
-+-- 0.31
--++ 0.02
--+- 0.07
---+ 0.22
---- 0.46
0.00 103.00
1.00 128.00
10.00 167.00
11.00 182.00
12.00 146.00
13.00 168.00
14.00 163.00
15.00 212.00
2.00 157.00
3.00 133.00
4.00 143.00
5.00 181.00
6.00 151.00
7.00 163.00
8.00 128.00
9.00 161.00
Contents of Dictionary

Example of Trades

Pattern Dictionary System

 

Code in Universum

//Dictionary based trading sytem
//Store pattern return
//Store pattern frequency
// by George Pruitt
Using elsystem.collections;

vars: string keystring("");
vars: dictionary patternDict(NULL),vector index(null), vector values(null);
array: patternCountArray[100](0);

input: patternTests(8);

var: patternTest(""),tempString(""),patternString(""),patternStringNum("");
var: patternNumber(0);
var: iCnt(0),jCnt(0);
//Lets convert the string to unique number
method int convertPatternString2Num(string pattString)
Vars: int pattLen, int idx, int pattNumber;
begin
pattLen = strLen(pattString);
pattNumber = 0;
For idx = pattLen-1 downto 0
Begin
If MidStr(pattString,pattLen-idx,1) = "+" then pattNumber = pattNumber + power(2,idx);
end;
Return (pattNumber);
end;


once begin
clearprintlog;
patternDict = new dictionary;
index = new vector;
values = new vector;
end;

//Convert 4 day pattern displaced by 2 days
patternString = "";
for iCnt = 5 downto 2
begin
if(close[iCnt]> close[iCnt+1]) then
begin
patternString = patternString + "+";
end
else
begin
patternString = patternString + "-";
end;
end;

//What is the current 4 day pattern
vars: currPattString("");
currPattString = "";

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

//Get displaced pattern number
patternNumber = convertPatternString2Num(patternString);
//Keep track of pattern hits
patternCountArray[patternNumber] = patternCountArray[patternNumber] + 1;
//Convert pattern number to a string do use as a Dictionary Key
patternStringNum = numToStr(patternNumber,2);
//Populate the pattern number string key with the number of hits
patternDict[patternStringNum] = patternCountArray[patternNumber] astype double;
//Calculate the percentage change after the displaced pattern hits
Value1 = (c - c[2])/c[2]*100;
//Populate the dictionary with 4 ("++--") day pattern and the percent change
if patternDict.Contains(patternString) then
Begin
patternDict[patternString] = (patternDict[patternString] astype double *
(patternDict[patternStringNum] astype double - 1.00) + Value1) / patternDict[patternStringNum] astype double;
end
Else
begin
patternDict[patternString] = value1;
// print("Initiating: ",patternDict[patternString] astype double);
end;
// get the best pattern that produces the best average 3 bar return
vars: hiPattRet(0),bestPattString("");
If patternDict.Count > 29 then
Begin
index = patternDict.Keys;
values = patternDict.Values;
hiPattRet = 0;
For iCnt = 0 to 15
Begin
If values[iCnt] astype double > hiPattRet then
Begin
hiPattRet = values[iCnt] astype double ;
bestPattString = index[iCnt] astype string;
end;
end;
// print(Date," BestPattString ",bestPattString," ",hiPattRet:8:4," CurrPattString ",currPattString);
end;
// if the current pattern matches the best pattern then bar next bar at open
If currPattString = BestPattString then buy next bar at open;
// cover in three days
If barsSinceEntry > 2 then sell next bar at open;
Pattern Dictionary Part II

 

 

 

Working Around 0:00 Time in EasyLanguage

Let’s say you want to carve out a special session of data from the 24-hour data session – maybe keep track of the highest high and lowest low from 9:00 p.m. to 4:00 p.m. the next day.  How would you do it?

To start with you would need to reset the highest high and lowest low values each day.  So you could say if the current bars time > StartTime and the prior bars time <= StartTime then you know the first bar of your specialized session has started.  So far so good.  If the time falls outside the boundaries of your special session then you want to ignore that data -right?  What about this:

If t >StartTime and t <= EndTime then…

{Remember EasyLanguage uses the end time stamp for its intraday bars}

Sounds good.  But what happens when time equals 2300 or 11:00 p.m.?  You want to include this time in your session but the if-then construct doesn’t work.    2300 is greater than 2100 but it’s not less than 1600 so it doesn’t pass the test.  The problems arise when the EndTime < StartTime.  It really isn’t since the EndTime is for the next day, but the computer doesn’t know that.  What to do?  Here is a quick little trick to help you solve this problem:  use a special offset if the time falls in a certain range.

EndTimeOffset = 0 ;

If t >=StartTime and t <= 2359 then EndTimeOffset= 2400 – EndTime;

Going back to our example of the current time of 2300 and applying this little bit of code our EndTimeOffset would be equal to 2400 – 1600 or 800.  So if t = 2300, you subtract 800 and get 1500 and that works.

2300 – 800 = 1500 which is less than 1600 –> works

What if t = 300 or 3:00 a.m.  Then EndTimeOffset = 0; 300 – 0 is definitely less than 1600.

That solves the problem with the EndTime.  Or does it?  What if EndTime is like 1503?  So you have 2400 – 1503 which is something like 897.  What if time is 2354 and you subtract 897 you get 1457 and that still works since its less than 1503.  Ok, what about if EndTime = 1859 then you get 2400 – 1859 which equals 541.  If time  = 2354 and you subtract 541 you get 1843 and that still works.

Is there a similar problem with the StartTime?  If t = 3:00 a.m. then it is not greater than our StartTime of 2100, but we want it in our window.  We need another offset.  This time we want to make a StartTime offset equal to 2400 when we cross the 0:00 timeline.  And then reset it to zero when we cross the StartTime timeline.  Let’s see if it works:

t = 2200 : is t > StartTime?  Yes

t=0002 : is t > StartTime?  No, but should be.  We crossed the 0000 timeline so we need to add 2400 to t and then compare to StartTime:

t + 2400 = 2402 and it is greater than StartTime.  Make sense?

Probably not but look at the code:

inputs: StartTime(numericSimple),EndTime(numericSimple),StartTimeOffSet(numericRef),EndTimeOffSet(numericRef);

If t >= StartTime and t[1] < StartTime then StartTimeOffSet = 0;
EndTimeOffSet = 0;
If t >= StartTime and t <= 2359 then EndTimeOffSet = 2400 - EndTime;
If t < t[1] then StartTimeOffSet = 2400;

TimeOffsets = 1;
Function To Calculate Start and End Time Offsets

Here is an the indicator code that calls the function:

vars: startTimeWindow(2100),endTimeWindow(1600);
vars: startOffSet(0),endOffSet(0);
Value1 = timeOffSets(startTimeWindow,endTimeWindow,startOffSet,endOffSet);

If t+startOffset > startTimeWindow and t-endOffSet <=endTimeWindow then
Begin

end
Else
Begin
print(d," ",t," outside time window ");
end;
Calling TimeOffsets Function

Hope this helps you out.  I am posting this for two reasons: 1) to help out and 2) prevent me from reinventing the wheel every time I have to use time constraints on a larger time frame of data.

StartTimeWindow = 2300

EndTimeWindow = 1400

Time = 2200, FALSE

Time = 2315, TRUE [2315 > 2300 and 2315 – (2400 -1400) <1400)]

This code should work with all times.  Shoot me an email if you find it doesn’t.

 

Calculating Position Size with Optimal F

I had a reader of the blog ask how to use Optimal F.  That was really a great question.  A few posts back I provided the OptimalFGeo function but didn’t demonstrate on how to use it for allocation purposes.  In this post, I will do just that.

I Have Optimal F – Now What?

From Ralph Vince’s book, “Portfolio Management Formulas”, he states: “Once the highest f is found, it can readily be turned into a dollar amount by dividing the biggest loss by the negative optimal f.  For example, if our biggest loss is $100 and our optimal f is 0.25, then -$100/ 0.25 = $400.  In other words, we should bet 1 unit for every $400 we have in our stake.”

Convert Optimal F to dollars and then to number of shares

In my example strategy, I start out with an initial capital of $50,000 and allow reinvestment of profit or loss.  The protective stop is set as 3 X ATR(10).  A fixed $2000 profit objective is also utilized.  The conversion form Optimal F to position size is illustrated by the following lines of code:

//keep track of biggest loss
biggestLoss = minList(positionProfit(1),biggestLoss);
//calculate the Optimal F with last 10 trades.
OptF = OptimalFGeo(10);
//reinvest profit or loss
risk$ = initCapital$ + netProfit;
//convert Optimal F to $$$
if OptF <> 0 then numShares = risk$ / (biggestLoss / (-1*OptF));
Code snippet - Optimal F to Position Size
  1. Keep track of biggest loss
  2. Calculate optimal F with OptimalFGeo function – minimum 10 trades
  3. Calculate Risk$ by adding InitCapital to current NetProfit (Easylanguage keyword)
  4. Calculate position size by dividing Risk$  by the quotient of biggest loss and (-1) Optimal F

I applied the Optimal F position sizing to a simple mean reversion algorithm where you buy on a break out in the direction of the 50-day moving average after a lower low occurs.

Code listing:

vars: numShares(0),initCapital$(50000),biggestLoss(0),OptF(0),risk$(0);


//keep track of biggest loss
biggestLoss = minList(positionProfit(1),biggestLoss);
//calculate the Optimal F with last 10 trades.
OptF = OptimalFGeo(10);
//reinvest profit or loss
risk$ = initCapital$ + netProfit;
//convert Optimal F to $$$
if OptF <> 0 then numShares = risk$ / (biggestLoss / (-1*OptF));
numShares = maxList(1,numShares);
//if Optf <> 0 then print(d," ",t," ",risk$ / (biggestLoss / (-1*OptF))," ",biggestLoss," ",optF);

if c > average(c,50) and low < low[1] then Buy numShares shares next bar at open + .25* range stop;

setStopPosition;
setProfitTarget(2000);

setStopLoss(3*avgTrueRange(10)*bigPointValue);
Strategy Using Optimal F

I have included the results below.  At one time during the testing the number of contracts jumped up to 23.  That is 23 mini Nasdaq futures ($20 * 7,300) * 23.  That’s a lot of leverage and risk.  Optimal doesn’t  always mean the best risk mitigation.  Please let me know if you find any errors in the code or in the logic.

 

Here is the ELD that incorporates the Strategy and the Function.USINGOPTIMALF