Category Archives: EasyLanguage Indicator

How to Create a Dominant Cycle Class in Python

John Ehlers used the following EasyLanguage code to calculate the Dominant Cycle in a small sample of data.  If you are interested in cycles and noise reduction, definitely check out the books by John Ehlers – “Rocket Science for Traders” or “Cybernetic Analysis for Stocks and Futures.”  I am doing some research in this area and wanted to share how I programmed the indicator/function in Python.  I refer you to his books or online resources for an explanation of the code.  I can tell you it involves an elegantly simplified approach using the Hilbert Transform.

 

Inputs:	Price((H+L)/2);

Vars: Imult(.635),
Qmult (.338),
InPhase(0),
Quadrature(0),
count(0),
Re(0),
Im(0),
DeltaPhase(0),
InstPeriod(0),
Period(0);

If CurrentBar > 8 then begin
Value1 = Price - Price[7];
Inphase = 1.25*(Value1[4] - Imult*Value1[2]) + Imult*InPhase[3];

// print(price," ",price[7]," ",value1," ",inPhase," ",Quadrature," ",self.im[-1]," ",self.re[-1])
// print(d," ",h," ",l," ",c," ",Value1[4]," ",Imult*Value1[2]," ", Imult*InPhase[3]," ",Inphase);
Quadrature = Value1[2] - Qmult*Value1 + Qmult*Quadrature[2];
Re = .2*(InPhase*InPhase[1] + Quadrature*Quadrature[1]) + .8*Re[1];
Im = .2*(InPhase*Quadrature[1] - InPhase[1]*Quadrature) + .8*Im[1];
print(d," ",o," ",h," ",l," ",c," ",value1," ",inPhase," ",Quadrature," ",Re," ",Im);
If Re <> 0 then DeltaPhase = ArcTangent(Im/Re);

{Sum DeltaPhases to reach 360 degrees. The sum is the instantaneous period.}
InstPeriod = 0;
Value4 = 0;
For count = 0 to 50 begin
Value4 = Value4 + DeltaPhase[count];
If Value4 > 360 and InstPeriod = 0 then begin
InstPeriod = count;
end;
end;

{Resolve Instantaneous Period errors and smooth}
If InstPeriod = 0 then InstPeriod = InstPeriod[1];
Period = .25*InstPeriod + .75*Period[1];

Plot1(Period, "DC");
EasyLanguage Code For Calculating Dominant Cycle

In my Python based back tester an indicator of this type is best programmed by using a class.  A class is really a simple construct, especially in Python, once you familiarize yourself with the syntax.   This indicator requires you to refer to historical values to calculate the next value in the equation:  Value1[4], inPhase[1], re[2], etc.,.  In EasyLanguage these values are readily accessible as every variable is defined as a BarArray – the complete history of a variable is accessible by using indexing.  In my PSB I used lists to store values for those variables most often used such as Open, High, Low, Close.  When you need to store the values of let’s say the last five bars its best to just create a list on the fly or build them into a class structure.  A Class stores data and data structures and includes the methods (functions) that the data will be pumped into.  The follow code describes the class in two sections:  1) data declaration and instantiation and 2) the function to calculate the Dominant Cycle.  First off I create the variables that will hold the constant values: imult and qmult.  By using the word self I make these variables class members and can access them using “.” notation.  I will show you later what this means.  I also make the rest of the variables class members, but this time I make them lists and instantiate the first five values to zero.  I use list comprehension to create the lists and zero out the first five elements – all in one line of code.  This is really just a neat short cut, but can be used for much more powerful applications.  Once you create a dominantCycleClass object the object is constructed and all of the data is connected to this particular object.  You can create many dominantCycleClass objects and each one would maintain its own data.  Remember a class is just a template that is used to create an object.

class dominantCycleClass(object):
def __init__(self):
self.imult = 0.635
self.qmult = 0.338
self.value1 = [0 for i in range(5)]
self.inPhase = [0 for i in range(5)]
self.quadrature = [0 for i in range(5)]
self.re = [0 for i in range(5)]
self.im = [0 for i in range(5)]
self.deltaPhase = [0 for i in range(5)]
self.instPeriod = [0 for i in range(5)]
self.period = [0 for i in range(5)]
Data Portion of Class

 

The second part of the class template contains the method or function for calculating the Dominant Cycle.  Notice how I index into the lists to extract prior values.  You will also see the word self. preceding the variable names used in the calculations Initially I felt like this redundancy hurt the readability of the code and in this case it might.  But by using self. I know I am dealing with a class member.  This is an example of the ” . ” notation I referred to earlier.  Basically this ties the variable to the class.

def calcDomCycle(self,dates,hPrices,lPrices,cPrices,curBar,offset):
tempVal1 = (hPrices[curBar - offset] + lPrices[curBar-offset])/2
tempVal2 = (hPrices[curBar - offset - 7] + lPrices[curBar-offset - 7])/2
self.value1.append(tempVal1 - tempVal2)
self.inPhase.append(1.25*(self.value1[-5] - self.imult*self.value1[-3]) + self.imult*self.inPhase[-3])
self.quadrature.append(self.value1[-3] - self.qmult*self.value1[-1] + self.qmult*self.quadrature[-2])
self.re.append(.2*(self.inPhase[-1]*self.inPhase[-2]+self.quadrature[-1]*self.quadrature[-2])+ 0.8*self.re[-1])
self.im.append(.2*(self.inPhase[-1]*self.quadrature[-2] - self.inPhase[-2]*self.quadrature[-1]) +.8*self.im[-1])
if self.re[-1] != 0.0: self.deltaPhase.append(degrees(atan(self.im[-1]/self.re[-1])))
if len(self.deltaPhase) > 51:
self.instPeriod.append(0)
value4 = 0
for count in range(1,51):
value4 += self.deltaPhase[-count]
if value4 > 360 and self.instPeriod[-1] == 0:
self.instPeriod.append(count)
if self.instPeriod[-1] == 0: self.instPeriod.append(self.instPeriod[-1])
self.period.append(.25*self.instPeriod[-1]+.75*self.period[-1])
return(self.period[-1])
Dominant Cycle Method

Okay we now have the class template to calculate the Dominant Cycle but how do we us it?

#---------------------------------------------------------------------------------
#Instantiate Indicator Classes if you need them
#---------------------------------------------------------------------------------
# rsiStudy = rsiClass()
# stochStudy = stochClass()
domCycle = dominantCycleClass()
#---------------------------------------------------------------------------------
#Call the dominantCycleClass method using " . " notation.
tempVal1 = domCycle.calcDomCycle(myDate,myHigh,myLow,myClose,i,0)
#Notice how I can access class members by using " . " notation as well!
tempVal2 = domCycle.imult
Dominant Cycle Object Creation

Here I assign domCycle the object created by calling the dominantCycleClass constructor.  TempVal1 is assigned the Dominant Cycle when the function or method is called using the objects name (domCycle) and the now familiar ” . ” notation.  See how you can also access the imult variable using the same notation.

Here is the code in its entirety.  I put this in the indicator module of the PSB.

class dominantCycleClass(object):
def __init__(self):
self.imult = 0.635
self.qmult = 0.338
self.value1 = [0 for i in range(5)]
self.inPhase = [0 for i in range(5)]
self.quadrature = [0 for i in range(5)]
self.re = [0 for i in range(5)]
self.im = [0 for i in range(5)]
self.deltaPhase = [0 for i in range(5)]
self.instPeriod = [0 for i in range(5)]
self.period = [0 for i in range(5)]

def calcDomCycle(self,dates,hPrices,lPrices,cPrices,curBar,offset):
tempVal1 = (hPrices[curBar - offset] + lPrices[curBar-offset])/2
tempVal2 = (hPrices[curBar - offset - 7] + lPrices[curBar-offset - 7])/2
self.value1.append(tempVal1 - tempVal2)
self.inPhase.append(1.25*(self.value1[-5] - self.imult*self.value1[-3]) + self.imult*self.inPhase[-3])
self.quadrature.append(self.value1[-3] - self.qmult*self.value1[-1] + self.qmult*self.quadrature[-2])
self.re.append(.2*(self.inPhase[-1]*self.inPhase[-2]+self.quadrature[-1]*self.quadrature[-2])+ 0.8*self.re[-1])
self.im.append(.2*(self.inPhase[-1]*self.quadrature[-2] - self.inPhase[-2]*self.quadrature[-1]) +.8*self.im[-1])
if self.re[-1] != 0.0: self.deltaPhase.append(degrees(atan(self.im[-1]/self.re[-1])))
if len(self.deltaPhase) > 51:
self.instPeriod.append(0)
value4 = 0
for count in range(1,51):
value4 += self.deltaPhase[-count]
if value4 > 360 and self.instPeriod[-1] == 0:
self.instPeriod.append(count)
if self.instPeriod[-1] == 0: self.instPeriod.append(self.instPeriod[-1])
self.period.append(.25*self.instPeriod[-1]+.75*self.period[-1])
return(self.period[-1])
Dominant Cycle Class - Python

 

Learn to Program Pyramiding Algorithm

Would you like to learn how to do this?  Check back over the next few days and I will show you to do it.  Warning:  its not straightforward as it seems – some tricks are involved.  Remember to sign up for email notifications of new posts.

UPDATE[1]:  I have recorded an introductory webcast on how to program this pyramiding scheme.  This webcast is Part 1 and illustrates how to brainstorm and start thinking/programming about a problem.  Part 1 introduces some concepts that show how you can use and adapt some of EasyLanguage built-in reserved words and functions.  I start from the perspective of a somewhat beginning EasyLanguage programmer  – one that knows enough to maybe not get the problem solved, but at least get the ball rolling.  The final code may not look anything like the code I present in Part 1.  However it is sometimes important to go down the wrong trail so that you can learn the limitations of a programming language.  Once you know the limitations, you can go about programming workarounds and fixes.  I hope you enjoy Part 1  I should have Part 2 up soon.  Don’t be too critical, this is really the first webcast I have recorded.  You’ll notice I repeat myself and I refer  to one function input as a subscript.  Check it out:  https://youtu.be/ip-DyyKpOTo

Adding positions at fixed intervals.

Utilizing Indicator Functions with Multi-Data on MultiCharts

A good portion of my readers use MultiCharts and the similarities between their PowerLanguage and EasyLanguage is almost indistinguishable.  However, I came across a situation where one my clients was getting different values between an indicator function call and the actual plotted indicator when using Multi-Data.

Here is the code that didn’t seem to work, even though it was programmed correctly in TradeStation.

vars:
oDMIPlus1(0),oDMIMinus1(0),oDMI1(0),oADX1(0),oADXR1(0),oVolty1(0),
oDMIPlus2(0,data2),oDMIMinus2(0,data2),oDMI2(0,data2),oADX2(0,data2),oADXR2(0,data2),oVolty2(0,data2),
ema1(0),ema2(0,data2),trendUp(false);



Value1 = DirMovement( H, L, C , Data1ADXLen, oDMIPlus1, oDMIMinus1, oDMI1, oADX1, oADXR1, oVolty1 ) ;
Value2 = DirMovement( H of data2, L of data2, C of data2, Data2ADXLen, oDMIPlus2, oDMIMinus2, oDMI2, oADX2, oADXR2, oVolty2 );

 

Pretty simple – so what is the problem.  Data aliasing was utilized in the Vars: section – this keeps the indicator from being calculated on the time frame of data1.  Its only calculated on the data2 time frame – think of data1 being a 5 min. chart and data2 a 30 min. chart.  I discovered that you have to also add data aliasing to not just the variables used in the indicator function but also to the function call itself.  This line of code fixed the problem:


DirMovement( H of data2, L of data2, C of data2, Value2, oDMIPlus2, oDMIMinus2, oDMI2, oADX2, oADXR2, oVolty2 )data2;
Add data2 after the function call to tie it to data2.

 

See that!  Just add Data2 to the end of the function call.  This verifies in TradeStation and compiles in MC with no problems.

 

Hash Table In EasyLanguage [Part 2]

Using The Hash Table

Now that we have created an empty Hash Table and the Hash Index it is now time to start filling the table up with the appropriate information.  As I pointed out in my last post, every day of any given year can be represented by a nine character string. If January 1st lands on a Tuesday, you can express this day with the following string, “1stTueJan.” That is if you want to ignore the year and in this case, we do.

Mapping Into the Hash Table

The table has already been prepared as well as the index.  All we have to do is map the current day into the index.  The location of the index value in the Hash Index array will then be used to locate the day’s location in the Hash Table.  We will use a function to convert the current day of the year into a value our Hash Index can interpret.

Here is the code to the function.  Don’t fret too much at the number of lines of code!

inputs: testDate(numericSeries);

vars: testMonth(0),tempStr("");
Array : prefixStrArr[6](""),dayofweekStr[5](""),monthName[12]("");
vars: monCnt(0),tueCnt(0),wedCnt(0),thuCnt(0),friCnt(0),tempDate1(0),tempDate2(0);
vars: freshStart(false),occurString(""),dayString(""),monthString("");
vars: whatOccurOfMonthStr(""),cnt(0),td(0),myCnt(0),daysBack(0);

preFixStrArr[1] = "1st";
preFixStrArr[2] = "2nd";
preFixStrArr[3] = "3rd";
preFixStrArr[4] = "4th";
preFixStrArr[5] = "5th";
preFixStrArr[6] = "6th";

dayOfWeekStr[1] = "Mon";
dayOfWeekStr[2] = "Tue";
dayOfWeekStr[3] = "Wed";
dayofWeekStr[4] = "Thu";
dayOfWeekStr[5] = "Fri";

monthName[1] = "Jan";
monthName[2] = "Feb";
monthName[3] = "Mar";
monthName[4] = "Apr";
monthName[5] = "May";
monthName[6] = "Jun";
monthName[7] = "Jul";
monthName[8] = "Aug";
monthName[9] = "Sep";
monthName[10] = "Oct";
monthName[11] = "Nov";
monthName[12] = "Dec";

tempDate1 = month(testDate[0]);
tempDate2 = month(testDate[1]);
cnt = 0;monCnt = 0;tueCnt=0;wedCnt=0;thuCnt=0;friCnt=0;
While (month(date) = month(date[cnt])) and cnt < 30
Begin
// print(date," ",date[cnt]," ",cnt);
cnt = cnt + 1;
end;
daysBack = cnt -1;

If daysBack < 0 then daysBack = 0;

For cnt = daysBack downto 0
begin
If dayOfWeek(date[cnt]) = 1 then monCnt = monCnt + 1;
If dayOfWeek(date[cnt]) = 2 then tueCnt = tueCnt + 1;
If dayOfWeek(date[cnt]) = 3 then wedCnt = wedCnt + 1;
If dayOfWeek(date[cnt]) = 4 then thuCnt = thuCnt + 1;
If dayOfWeek(date[cnt]) = 5 then friCnt = friCnt + 1;
end;
//print("counts: ",monCnt," ",tueCnt," ",wedCnt," ",thuCnt," ",friCnt);

If dayOfWeek(date) = Monday then tempStr = preFixStrArr[monCnt];
If dayOfWeek(date) = Tuesday then tempStr = preFixStrArr[tueCnt];
If dayOfWeek(date) = Wednesday then tempStr = preFixStrArr[wedCnt];
If dayOfWeek(date) = Thursday then tempStr = preFixStrArr[thuCnt];
If dayOfWeek(date) = Friday then tempStr = preFixStrArr[friCnt];

tempStr = tempStr + dayOfWeekStr[dayOfWeek(date)];
tempStr = tempStr + monthName[month(date)];
GetWhichWeekMonth = tempStr;
GetWhichWeekMonth Function

Here is where using an integer representation of the date would reduce the number of lines of code tremendously.  Well, I made my bed I might as well sleep in it.  You will see some duplication between this code and the Hash Table creator function.  I have to store names for the week rank, day of the week, and month in arrays.  There isn’t a simple function that will pull the week rank from any given date.  So I simply take the date and work my way back to the beginning of the month counting each weekday as I go along.

For cnt = daysBack downto 0
begin
If dayOfWeek(date[cnt]) = 1 then monCnt = monCnt + 1;
If dayOfWeek(date[cnt]) = 2 then tueCnt = tueCnt + 1;
If dayOfWeek(date[cnt]) = 3 then wedCnt = wedCnt + 1;
If dayOfWeek(date[cnt]) = 4 then thuCnt = thuCnt + 1;
If dayOfWeek(date[cnt]) = 5 then friCnt = friCnt + 1;
end;

Getting The Hash Index

The number that is stored in the individual counters (monCnt, tueCnt, etc.) determines which week of the month the current day is located.  I build the string through concatenation.  First I get the week rank (“1st”, “2nd”, “3rd”, “4th”, “5th”), add the name of the day and then add the month.  The end result looks like “1stMonJan”.  From here I cross-reference the Hash Index and pull out the location of the of the string (aka index.)  Here is the function GetHashIndex.

input: hashIndex[n](stringArrayRef),hashTableRows(numericSimple),searchString(string);
vars: iCnt(0),done(false);

GetHashIndex = 0;
done = false;

For iCnt = 1 to hashTableRows
Begin
// print("Looking for: ",searchString," ",hashIndex[iCnt]," ",iCnt);
If searchString = hashIndex[iCnt] then
begin
done = true;
GetHashIndex = iCnt;
end;
If done then break;
end;
GetHashIndex

As you can see it is a linear search that returns the Hash Index’s Index.  Check out how I prematurely exit the loop by using the keyword Break.  This keyword knocks you out of any loop where it is located.  If you have a nested loop, the break only gets you out of that current loop where it is located.

Hast Table Indicator

Now how can we pull all this together to create a useful trading tool.  I used these tools to create an indicator that plots the average daily change from one day to the next.  So, if today is the “3rdMonJune” and the indicator reads 0.52, this represents that over the last X years the average percentage change is a plus .5%.  Would it make sense to buy the “2ndFriJun” and exit on the close of the “3rdMonJune?”  Maybe.

Here is the code for the Hash Table indicator.

vars: returnValString(""),iCnt(0),jCnt(0); 
array: weekDayMonthIndex[300]("");
array: HashTable[300,100](0);
array: timeLine[300](0);
vars: searchString(""),numYearsCollected(0),hashIndex(0);
vars: yCnt(0),numYears(0);
vars: hashRows(300);
vars: myBarCount(0),maxNumYearsInHash(0),avgDailyChange(0),dailyChangeSum(0);

If barNumber = 1 then //build the hash index - index form "1stMonJul" "2ndFriDec"
begin
Value1 = HashIndexCreator(weekDayMonthIndex);
end;

numYearsCollected = HashTableCreator(HashTable,weekDayMonthIndex); {Build hash table as we go along}

If year(date) <> year(date[1]) then numYears = numYears + 1;

If numYearsCollected > 3 then // only pull information if there is at least three years of data
Begin
searchString = GetWhichWeekMonth(date); // convert today's date into a compatible Hash Index value
hashIndex = GetHashIndex(weekDayMonthIndex,hashRows,searchString); // find the location of today's value in the Hash Index
dailyChangeSum = 0;;
// print(d," ",searchString," ",hashIndex);
For yCnt = 2 to numYearsCollected
Begin
dailyChangeSum = dailyChangeSum + HashTable[hashIndex,yCnt];
end;
avgDailyChange = dailyChangeSum/numYearsCollected;
if year(date) = 116 then print(d," ",searchString," ",numYearsCollected," ",avgDailyChange);
if numYearsCollected > numYears-1 then plot1(avgDailyChange,"AvgChgFromYesterday");
End;
HashTableIndicator

Results of Using the Hash Table

Here is a simple output of the results from the indicator for the year of 2016.  I sorted the data based on highest average daily change and number of years collected.

1160729 5thFriJul 7 0.95
1161031 5thMonOct 5 0.62
1160115 2ndFriJan 16 0.56
1160830 5thTueAug 7 0.55
1160713 2ndWedJul 17 0.52
1160812 2ndFriAug 17 0.52
1160519 3rdThuMay 16 0.43
1161003 1stMonOct 17 0.38
1160112 2ndTueJan 16 0.38
1160223 4thTueFeb 16 0.38
1161122 4thTueNov 16 0.37
1160804 1stThuAug 17 0.35
1160316 3rdWedMar 16 0.35
1160711 1stMonJul 17 0.34
1161121 3rdMonNov 17 0.34
1160225 4thThuFeb 16 0.34
1160517 3rdTueMay 16 0.34
1160610 2ndFriJun 16 0.34
1161215 3rdThuDec 17 0.33

It looks like the buying the close “4thThuJul” is the way to go!  But since there are only seven observations I think would think twice.  But, buying the close on the day prior to “2ndFriJan” might offer that technical advantage you’re looking for.