Python Script To Import List of Trades into TradeStation’s EasyLanguage – Sort of

Converting A List of Trades, Dates and Prices Into EasyLanguage Arrays:

As the old saying goes “a picture is worth a thousand words!”  Have you ever been given a list of trades like this:

Sell Short,20010622,1178.50 
Buy to Cover,20010626,1159.75 
Sell Short,20010801,1150.00 
Buy to Cover,20010807,1139.75 
Sell Short,20010814,1129.00 
Buy to Cover,20010816,1117.25 
Sell Short,20011001,976.75 
Buy to Cover,20011004,1016.75 
Sell Short,20011107,1053.00 
Buy to Cover,20011123,1069.50 
Sell Short,20011219,1076.25 
Buy to Cover,20020102,1075.00 
Sell Short,20020129,1067.25 
Buy to Cover,20020131,1046.75 
Sell Short,20020131,1046.75 
Buy to Cover,20020205,1026.75 
Sell Short,20020520,1033.25 
Buy to Cover,20020522,1011.50 
Sell Short,20020731,832.00 
Buy to Cover,20020805,792.50 
Sell Short,20020812,834.00 
Buy to Cover,20020814,811.75 
Sell Short,20020911,838.50 
Buy to Cover,20020913,816.75 
List of Trades : Order, Date, Price

But really wanted to see this:

I have created a small Python script that will take a list of trades like those listed in table above and create the following EasyLanguage:

arrays: DateArr[500](0),TradeArr[500](""),PriceArr[500](0);
DateArr[0]=1010622;TradeArr[0]="SS";PriceArr[0]=1178.5;
DateArr[1]=1010626;TradeArr[1]="SX";PriceArr[1]=1159.75;
DateArr[2]=1010801;TradeArr[2]="SS";PriceArr[2]=1150.0;
DateArr[3]=1010807;TradeArr[3]="SX";PriceArr[3]=1139.75;
DateArr[4]=1010814;TradeArr[4]="SS";PriceArr[4]=1129.0;
DateArr[5]=1010816;TradeArr[5]="SX";PriceArr[5]=1117.25;
DateArr[6]=1011001;TradeArr[6]="SS";PriceArr[6]=976.75;
DateArr[7]=1011004;TradeArr[7]="SX";PriceArr[7]=1016.75;
DateArr[8]=1011107;TradeArr[8]="SS";PriceArr[8]=1053.0;
DateArr[9]=1011123;TradeArr[9]="SX";PriceArr[9]=1069.5;
DateArr[10]=1011219;TradeArr[10]="SS";PriceArr[10]=1076.25;
DateArr[11]=1020102;TradeArr[11]="SX";PriceArr[11]=1075.0;
DateArr[12]=1020129;TradeArr[12]="SS";PriceArr[12]=1067.25;
DateArr[13]=1020131;TradeArr[13]="SX";PriceArr[13]=1046.75;
DateArr[14]=1020131;TradeArr[14]="SS";PriceArr[14]=1046.75;
DateArr[15]=1020205;TradeArr[15]="SX";PriceArr[15]=1026.75;
DateArr[16]=1020520;TradeArr[16]="SS";PriceArr[16]=1033.25;
DateArr[17]=1020522;TradeArr[17]="SX";PriceArr[17]=1011.5;
Converting list of trades to EasyLanguage

This just creates the arrays that you can use to graph the trades on a chart.  If you are using exact prices you got to make sure your data aligns with the prices in the list of trades.  If you are only entering on the open or the close of the bar then the price array isn’t necessary.

The following Python script will also be helpful if you want to learn how to open a file in csv format, read it into lists, convert it and then save the output to a file.

#-------------------------------------------------------------------------------
# Name:        Read csv file via askOpen and save txt file via askSave
# Purpose:     Read the trade metrics from a TradeStation csv format
#              and build arrays from the information to display on charts in
#              TradeStation
# Author:      georg
#
# Created:     29/08/2018
# Copyright:   (c) georg 2018
#-------------------------------------------------------------------------------
import csv
import tkinter as tk
import os.path
from tkinter.filedialog import askopenfilenames
from tkinter.filedialog import asksaveasfilename

tradeType = list()
tradeDate = list()
tradePrice = list()

def main():
    root = tk.Tk()
    root.withdraw()
    files = askopenfilenames(filetypes=(('CSV files', '*.csv'),
                                       ('TXT files', '*.txt')),
                                       title='Select CSV format only!')
    fileList = root.tk.splitlist(files)
    fileListLen = len(fileList)


# make sure you know the format ahead of time
# I know "Buy",20180828,2745.75
#
    cnt = 0
    for files in range(0,fileListLen):
        head,tail = os.path.split(fileList[files])
        with open(fileList[files]) as f:
            f_csv = csv.reader(f)
            for row in f_csv:
                numCols = len(row)
                tradeType.append(row[0])
                tradeDate.append(int(row[1]))
                tradePrice.append(float(row[2]))
                cnt += 1
        f.close


    filename = asksaveasfilename(title="Will Save File with '.txt'",defaultextension=".txt")
#    filename = filename + '.txt'
    target1 = open(filename,'w')
    outString = 'arrays: DateArr[500](0),TradeArr[500](0),PriceArr[500](0);\n'
    target1.write(outString)
    for x in range(0,cnt):
        if tradeType[x] == "Sell Short": tradeType[x] = "SS"
        if tradeType[x] == "Buy": tradeType[x] = "B"
        if tradeType[x] == "Buy to Cover": tradeType[x] = "SX"
        if tradeType[x] == "Sell": tradeType[x] = "LX"
        outString = 'DateArr['+str(x)+']='+str(tradeDate[x]-19000000)+';TradeArr['+str(x)+']="'+tradeType[x]+'";PriceArr['+str(x)+']='+str(tradePrice[x])+';\n'
        target1.write(outString)
    target1.close


if __name__ == '__main__':
    main()
Python Script Open, Read, Convert and Write A File Using TK Dialogs

And here is the EasyLanguage code that will step through the arrays and place the trades accordingly.  I noticed that sometimes two trades could occur on the same bar, but only two and you will notice in the code where I programmed this occurrence.

vars: cnt(0);

If date of tomorrow = DateArr[cnt] then
Begin
	print("Inside: ",d," ",dateArr[cnt]);
	If tradeArr[cnt] = "B" then
	begin
		buy next bar at PriceArr[cnt] stop;
	end;
	If tradeArr[cnt] = "LX" then
	begin
		sell next bar at PriceArr[cnt] stop;
	end;
		If tradeArr[cnt] = "SS" then
	begin
		sellShort next bar at PriceArr[cnt] stop;
	end;
	If tradeArr[cnt] = "SX" then
	begin
		buyToCover next bar at PriceArr[cnt] stop;
	end;
	cnt = cnt + 1;
	If DateArr[cnt] = DateArr[cnt-1] then
	Begin
		print("two trades same day ",d," ",dateArr[cnt]);
		If tradeArr[cnt] = "B" then
		begin
			buy next bar at PriceArr[cnt] stop;
		end;
		If tradeArr[cnt] = "LX" then
		begin
			sell next bar at PriceArr[cnt] stop;
		end;
		If tradeArr[cnt] = "SS" then
		begin
	    	print("looking to go short at ",PriceArr[cnt]);
			sellShort next bar at PriceArr[cnt] stop;
		end;
		If tradeArr[cnt] = "SX" then
		begin
			buyToCover next bar at PriceArr[cnt] stop;
		end;
		cnt = cnt + 1;
	end;	
end;
EasyLanguage Snippet To Execute Trades Stored in Arrays

 

 

Using TradeStation’s COT Indicator to Develop a Trading System

TradeStation’s COT (Commitment of Traders) Indicator:

TradeStation COT Indicator

TradeStation now includes the historic COT (Commitment of Traders) report in the form of an indicator.

If you can plot it then you can use it in a Strategy.  The following code listing takes the Indicator code and with very few modifications turns it into a trading system.

{
Net positions of various groups of traders from the CFTC's weekly Commitments of
Traders report.  "Net" positions are calculated by taking the number of contracts
that a group of traders is long and subtracting the number of contracts that that
group of traders is short.

The user input "FuturesOnly_Or_FuturesAndOptions_1_or_2" determines whether the
CFTC's "Futures Only" report is used, or the "Futures and Options" report is
used to determine the positions of the various groups of traders.  By default, the
"Futures Only" report is used.

Plot1:  Commercial traders' net position
Plot2:  Non-commercial traders' net position
Plot3:  Speculators' net positions, for speculators not of reportable size
Plot4:  Zero line

If an error occurs retrieving one of the values used by this study, or if the value
is not applicable or non-meaningful, a blank cell will be displayed in RadarScreen or
in the OptionStation assets pane.  In a chart, no value will be plotted until a value
is obtained without generating an error when retrieved.
}

input:  FuturesOnly_Or_FuturesAndOptions_1_or_2( 1 ) ; { set to 1 to use the CFTC's
 "Futures Only" report, set to 2 (or to any value other than 1) to use the "Futures
 and Options" report }

variables:
	Initialized( false ),
	FieldNamePrefix( "" ),
	CommLongFieldNme( "" ),
	CommShortFieldNme( "" ),
	NonCommLongFieldNme( "" ),
	NonCommShortFieldNme( "" ),
	SpecLongFieldNme( "" ),
 	SpecShortFieldNme( "" ),
    CommLong( 0 ),
	oCommLongErr( 0 ),
	CommShort( 0 ),
	oCommShortErr( 0 ),
	NonCommLong( 0 ),
	oNonCommLongErr( 0 ),
	NonCommShort( 0 ),
	oNonCommShortErr( 0 ),
	SpecLong( 0 ),
	oSpecLongErr( 0 ),
	SpecShort( 0 ),
	oSpecShortErr( 0 ),
	CommNet( 0 ),
	NonCommNet( 0 ),
	SpecNet( 0 ) ;

if Initialized = false then
	begin
	if Category > 0 then
		RaiseRuntimeError( "Commitments of Traders studies can be applied only to" +
		 " futures symbols." ) ;
	Initialized = true ;
	FieldNamePrefix = IffString( FuturesOnly_Or_FuturesAndOptions_1_or_2 = 1,
	 "COTF-", "COTC-" ) ;
	CommLongFieldNme = FieldNamePrefix + "12" ;
	CommShortFieldNme = FieldNamePrefix + "13" ;
	NonCommLongFieldNme = FieldNamePrefix + "9" ;
	NonCommShortFieldNme = FieldNamePrefix + "10" ;
	SpecLongFieldNme = FieldNamePrefix + "16" ;
 	SpecShortFieldNme = FieldNamePrefix + "17" ;	
	end ;

CommLong = FundValue( CommLongFieldNme, 0, oCommLongErr ) ;
CommShort = FundValue( CommShortFieldNme, 0, oCommShortErr) ;
NonCommLong = FundValue( NonCommLongFieldNme, 0, oNonCommLongErr ) ;
NonCommShort = FundValue( NonCommShortFieldNme, 0, oNonCommShortErr );
SpecLong = FundValue( SpecLongFieldNme, 0, oSpecLongErr ) ; 
SpecShort = FundValue( SpecShortFieldNme, 0, oSpecShortErr ) ;

if oCommLongErr = fdrOk and oCommShortErr = fdrOk then
	begin
	CommNet = CommLong - CommShort ;
	Print ("CommNet ",commNet);
	end ;

if oNonCommLongErr = fdrOk and oNonCommShortErr = fdrOk then
	begin
	NonCommNet = NonCommLong - NonCommShort ;
	end ;

if oSpecLongErr = fdrOk and oSpecShortErr = fdrOk then
	begin
	SpecNet = SpecLong - SpecShort ;
	end ;
If CommNet < 0  then sellShort tomorrow at open;
If CommNet > 0 then buy tomorrow at open;


{ ** Copyright (c) 2001 - 2010 TradeStation Technologies, Inc. All rights reserved. ** 
  ** TradeStation reserves the right to modify or overwrite this analysis technique 
     with each release. ** }
COT Indicator Converted To Strategy

Line numbers 90 and 91 informs TS to take a long position if the Net Commercial Interests are positive and a short position if the Commercials are negative.  I kept the original comments in place in  case you wanted to see how the indicator and its associated function calls work.  The linchpin of this code lies in the function call FundValue.  This function call pulls fundamental data from the data servers and provides it in an easy to use format.  Once you have the data you can play all sorts of games with it.  This is just a simple system to see if the commercial traders really do know which direction the market is heading.

if you test this strategy on the ES you will notice a downward sloping 45 degree equity curve.  This leads me to believe the commercials are trying their best to  use the ES futures to hedge other market positions.  If you go with the non Commercials you will see  a totally different picture.  To do this just substitute the following two lines:

If CommNet < 0 then sellShort tomorrow at open;
If CommNet > 0 then buy tomorrow at open;

With:

If NonCommNet < 0 then sellShort tomorrow at open;
If NonCommNet > 0 then buy tomorrow at open;

I said a totally different picture not a great one.  Check out if the speculators know better.

Back Adjusted Continuous Contract Data from Quandl

I finally got around to programming an easy Python down loader for CME data from Quandl.  I promised this in my last book, but haven’t got that many requests.   On the Ultimate Algorithmic Trading System…. page I have provided some data going back to early 2008 on several markers.  This is a work in progress.  I also wrote a back adjuster that rolls when the Open Interest + Volume is greater in the next contract and adjusts the data retroactively (Panama process) by the discount on the roll date.  As I state on the web page this data is not all that great even though it looks like it comes directly from CME.   I do fill in gaps and try to fix glaring errors so take it for what it is.  Its good data for preliminary testing, but to finalize an algorithm or to trade by I would definitely go the “paid” route.  Although the later data looks pretty good.

Before downloading the data I would sign up for Quandl and get an API key.  You will be amazed at the amount of data they make available – free and paid subscriptions.

 

 

Anatomy Of Mean Reversion in EasyLanguage

Look at this equity curve:

As long as you are in a bull market buying dips can be very consistent and profitable.  But you want to use some type of entry signal and trade management other than just buying a dip and selling a rally.  Here is the anatomy of a mean reversion trading algorithm that might introduce some code that you aren’t familiar.  Scroll through the code and I will  summarize below.

inputs: mavlen(200),rsiLen(2),rsiBuyVal(20),rsiSellVal(80),holdPeriod(5),stopLoss$(4500);
vars: iCnt(0),dontCatchFallingKnife(false),meanRevBuy(false),meanRevSell(false),consecUpClose(2),consecDnClose(2);

Condition1 = c > average(c,mavLen);

Condition2 = rsi(c,rsiLen) < rsiBuyVal;
Condition3 = rsi(c,rsiLen) > rsiSellVal;


Value1 = 0;
Value2 = 0;

For iCnt = 0 to consecUpClose - 1 
Begin
	value1 = value1 + iff(c[iCnt] > c[iCnt+1],1,0);
end;

For iCnt = 0 to consecDnClose - 1 
Begin
	Value2 = value2 + iff(c[iCnt] < c[iCnt+1],1,0);
end;

dontCatchFallingKnife = absValue(C - c[1]) < avgTrueRange(10)*2.0;

meanRevBuy = condition1 and condition2 and dontCatchFallingKnife;
meanRevSell =  not(condition1) and condition3 and dontCatchFallingKnife;

If meanRevBuy then buy this bar on close;
If marketPosition = 1 and condition1 and value1 >= consecUpClose then sell("ConsecUpCls") this bar on close;

If meanRevSell then sellShort this bar on close;
If marketPosition = -1 and not(condition1) and value2 >= consecDnClose then buyToCover this bar close;

setStopLoss(stopLoss$);


If barsSinceEntry = holdPeriod then
Begin
	if marketPosition = 1 and not(meanRevBuy) then sell this bar on close;
	if marketPosition =-1 and not(meanRevSell) then buytocover this bar on close;
end;
Mean Reversion System

I am using a very short term RSI indicator, a la Connors, to initiate long trades.  Basically when the 2 period RSI dips below 30 and the close is above the 200-day moving average I will buy only if I am not buying “a falling knife.”  In February several Mean Reversion algos kept buying as the market fell and eventually got stopped out with large losses.  Had they held on they probably would have been OK.  Here I don’t buy if the absolute price difference between today’s close and yesterday’s is greater than 2 X the ten day average true range.  Stay away from too much “VOL.”

Once a trade is put on I use the following logic to keep track of consecutive closing relationships:

For iCnt = 0 to consecUpClose - 1 
Begin
	value1 = value1 + iff(c[iCnt] > c[iCnt+1],1,0);
end;
Using the IFF function in EasyLanguage

Here I am using the IFF function to compare today’s close with the prior day’s.  iCnt is a loop counter that goes from 0 to 1. IFF checks the comparison and if it’s true it returns the first value after the comparison and if false it returns the last value.  Here if I have two consecutive up closes value1 accumulates to 2.  If I am long and I have two up closes I get out.  With this template you can easily change this by modifying the input:  consecUpClose.  Trade management also includes a protective stop and a time based exit.  If six days transpire without two up closes then the system gets out – if the market can’t muster two positive closes, then its probably not going to go anywhere.  The thing with mean reversion, more so with other types of systems, is the use or non use of a protective stop.  Wide stops are really best, because you are betting on the market to revert.  Look at the discrepancy of results using different stop levels on this system:

Here an $1,800 stop only cut the max draw down by $1,575.  But it came at a cost of $17K in profit.  Stops, in the case of Mean Reversion, are really used for the comfort of the trader.

This code has the major components necessary to create a complete trading system.  Play around with the code and see if you can come up with a better entry mechanism.

Updated Pattern Smasher in EasyLanguage

Update To Original Pattern Smasher

What will you learn : string manipulation, for-loops, optimization

Before proceeding I would suggest reading my original post on this subject.    If you believe the relationship of the last few bars of data can help determine future market direction, then this post will be in you wheel house.  Another added benefit is that you will also learn some cool EasyLanguage.

Original post was limited to four day patterns!

This version is limitless (well not really, but pretty close).  Let’s stick with the original string pattern nomenclature (+ + – – : two up closes followed by two down closes.)  Let’s also stick with our binary pattern representation:

Pattern # 2^3 2^2 2^1 1
3 0 0 1 1
4 0 1 0 0
5 0 1 0 1
6 0 1 1 1

Remember a 0 represents a down close and a 1 represents an up close.  We will deviate from the original post by doing away with the array and stick with only strings (which are really just arrays of characters.)  This way we won’t have to worry about array manipulation.

How to create a dynamic length string pattern

This was the difficult part of the programming.  I wanted to be able to optimize 3, 4 and 5 day patterns and I wanted to control this with using just inputs.  I discovered that pattern three is different in a three day pattern than it is in a four day pattern: in a three day pattern it is 011 or – + + and in a four day pattern it is 0011 or – – + +.  Since I am counting 0’s as down closes, pattern #3 depends on the ultimate size of the pattern string.  No worries I will have eventually have another version where I utilize a different value for down closes and we can then have holes in our string patterns.  But I digress – so to differentiate the patterns based on the pattern length I included a maxPatternLen input.  So if maxPatternLen is three and we are trying to match pattern #3 then we will be looking for 011 and not 0011.  That was an easy fix.  But then I wanted to build a string pattern based on this input and the pattern number dynamically.  Here is some psuedo code on how I figured it out.


{Psuedo code to translate pattern number into binary number}
patternNumber = 3
maxPatternLen = 3

numBits = 0    						// stick with binary representation
testValue = 0						// temporary test value
numBits = maxPatternLen-1  			// how many bits will it take to get to the
									// center of - or numBits to represent max
									// number of patterns or 2^numBits
currentBit =numBits					// start wit current bit as total numBits

value1 = patternOptTest				// value1 represents current pattern number
testString = ""  					// build test string from ground up


for icnt = numBits downto 0			//building string from left to right
begin       						// notice keyword downto
	if power(2,currentBit) > value1 then  // must use power function in EL
	begin							// if the very far left bit value > 
		testString = testString + "-"	  // patten number then plug in a "-"
	end
	else
	begin							// else plug in a "+" and deccrement by
		testString = testString + "+"	 // that bits value - if its the 3rd bit
	value1 = value1 - power(2,currentBit)// then decrement by 8
	end;
	currentBit = currentBit - 1		// move onto the next bit to the right
end;
Pseudocode for Binary Representation of Pattern #

Now if you want to optimize then you must make sure your pattern number search space or range can be contained within maxPatternLen.  For example, if you want to test all the different combinations of a four day pattern, then your maxPatternLen would naturally be four and you would optimize the pattern number from 0 to 15.  Don’t use 1-16 as I use zero as the base.  A five day pattern would include the search space from 0 – 31.  The rest of the code was basically hacked from my original post.   Here is the rest of the code to do optimizations on different length pattern strings.  Notice how I use strings, for-loops and comparisons.

input: buyPattern("+++-"),sellPattern("---+"),patternOptimize(True),patternOptTest(7),maxPatternLen(3),patternOptBuySell(1),
	   stopLoss$(2000),profitTarg$(2000),holdDays(5);
vars: buyPatternString(""),sellPatternString(""),buyPatternMatch(""),sellPatternMatch(""),numBits(0),testValue(0),currentBit(0),
      remainder(0),value(0),icnt(0),testString(""),numCharsInBuyPattern(0),numCharsInSellPattern(0);
vars:okToBuy(false),okToSell(false);

buyPatternMatch = buyPattern;
sellPatternMatch = sellPattern;
numCharsInBuyPattern = strLen(buyPatternMatch);
numCharsInSellPattern = strLen(sellPatternMatch);

If patternOptimize then
begin
	numBits = 0;
    testValue = 0;
    value = maxPatternLen;
    numBits = maxPatternLen-1;  
    currentBit =numBits;
    remainder = patternOptTest;
    testString = "";
    for icnt = numBits downto 0
    begin       
        if power(2,currentBit) > value1 then
        begin
            testString = testString + "-";
        end
        else
        begin
            testString = testString + "+";
            remainder = remainder - power(2,currentBit);
        end;
        currentBit = currentBit - 1;
	end;
	numCharsInBuyPattern = maxPatternLen;
	numCharsInSellPattern = maxPatternLen;
	if patternOptBuySell = 1 then
	Begin
		buyPatternMatch = testString;
		sellPatternMatch = "0";
	end;
	If patternOptBuySell = 2 then
	Begin
		buyPatternMatch = "0";
		sellPatternMatch = testString;
	end;
end;
	

buyPatternString = "";
sellPatternString = "";

For icnt = numCharsInBuyPattern-1 downto 0
Begin
	If close[icnt] >= close[icnt+1] then buyPatternString = buyPatternString + "+";
	If close[icnt] < close[icnt+1] then buyPatternString = buyPatternString + "-";
end;
For icnt = numCharsInSellPattern-1 downto 0
Begin
	If close[icnt] >= close[icnt+1] then sellPatternString = sellPatternString + "+";
	If close[icnt] < close[icnt+1] then sellPatternString = sellPatternString + "-";
end;


okToBuy = false;
okToSell = false;

if buyPatternMatch <> "" then
	If buyPatternString = buyPatternMatch then okToBuy = true;
If buyPatternMatch = "" then
	okToBuy = true;
If sellPattern <> "" then
	If sellPatternString = sellPatternMatch then okToSell = true;
If sellPatternMatch = "" then
	okToSell = true;
	
If okToBuy then buy next bar at open;
If okToSell then sellshort next bar at open;

If marketPosition = 1 and barsSinceEntry > holdDays then sell next bar at open;
If marketPosition = -1 and barsSinceEntry > holdDays then buytocover next bar at open;

setStopLoss(stopLoss$);
setProfitTarget(profitTarg$);

If lastBarOnChart then print(d," ",buyPatternMatch);
Final Version of New Pattern Smasher

Also see how I incorporate a profit target and protective stop.  I use the built in BarsSinceEntry function to count the number of days I am in a trade so I can utilize a time based exit.  Here is an interesting equity curve I developed using a two day pattern ( – –) to go long.

Register on the website and I will email you an ELD of the improved Pattern Smasher.  Or just shoot me an email.

 

 

Making Trading Decisions on Current Month’s Profit/Loss

Keeping track of intra-month profit or loss

In real time trading I have noticed that once you reach a certain loss for the month its best, sometimes, to circle the wagons and quit trading until the beginning of the next month.  This concept works best for very short term or day trade algorithms, as its very easy to get started back up.  You can do this with Trend Following, but you must build a logical and replicable process for re-entering existing positions.  Let’s assume a trading algorithm whose averaging losing month is $1500 and you are currently down $2000 – what are the chances that you will revert to the mean or draw down further?  Probably 50/50.  Who knows you might turn around and actually make money by month’s end.  If you review a track record of a hedge fund manager, trader, or algorithm and they show a bar chart of monthly returns and there sticking out like a sore thumb is a big down bar, that kind of makes you think that could happen again.  If you can control the monthly downside without sacrificing the existing Profit:DrawDown ratio, then why not do it.

Sample Code To Monitor IntraMonth $P/L

if month(date) <> month(date[1]) then
Begin
	begMonthProf = netProfit; 
	print(d," ",t," ",begMonthProf);
	canTrade = true;
end;
Capture Beginning Of Month Net Profit

Here I am comparing the month of the current bar against the month of the prior bar.  If they are not equal, then we have a new month.  Store the netProfit in the variable begMonthProf.  All you have to do is compare the current bar’s netProfit to begMonthProf and make a decision.  Here is some code:

Making a Trading Decision Based on Monthly $P/L

		If dayOfMonth(date) > 15 and begMonthProf - netProfit >= intraMonthMaxLoss then canTrade = false;
If Down MaxLoss for Month and Past Mid-Month - Quit Trading

If the day of the month is greater than 15 (month half over) and the difference between the current netProfit and begMonthProfit is greater than a negative intraMonthMaxLoss then quit trading for the month.  Only turn it back on the first bar of the next month.  See how this works for your algos.

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

 

Mean Reversion Regime Change?

Many traders of late have done quite well buying the dips (Mean Reversion) in the stock market.  I mean if you look at the big picture and just not the last two months.  The hyper aggressive buyers might have bitten off more than they could chew.  The laid back fully funded traders were able to shrug off the volatility – even when the DOW was down nearly quadruple digits some kept going in and buying in a very respectful manner.  Of course they had their protective stops as well as profit objectives in place as soon as their buys went in.  Take a look at this equity curve:The huge draw down in just a matter of a few days shook out a ton of traders – even though the drawdown had probably been seen a few times in the history of the algorithm.   When you buy after the DOW was down 1175 you have to be crazy right?  That’s exactly what a lot of systems did and if you didn’t have a relatively respectable stop then you might have gotten wiped out.  This system risks $1000 to make $4000 and only buys when you have two lower lows.  Oh and the close has to be above the 200 day moving average.  The intra-trade draw down was around $6000 during the February Vixpocalypse.  How can that be?  If I am only risking $1000 why did I lose almost $6000 on one given trade.

Many of the more popular mean reversion systems fell into this same situation because they utilized a stop on a close basis only.  In other words the market could collapse during the day, but you had to wait to get out on the close.  This can be dangerous even if historical performance has shown respectable performance metrics.  Waiting for the close has been able to turn large losing trades into either much smaller losing trades or even winners.

Here is the same system with an intraday stop of $2000.  I had to increase the stop to get a similar looking equity curve.  I also expanded the profit objective.  Trading these systems requires a balancing act – do you want the security of a daily fixed stop or the chance at a better looking equity curve.

A volatility cut off could definitely help with draw down but at the same time its going to bite into the bottom line.  I don’t see a regime change yet.  A fixed stop might provide enough safety to continue trading with these types of algorithms.

 

How to Keep Track of BuysToday and SellsToday

The Useful MP

We all know how to use the reserved word/function MarketPosition – right?  Brief summary if not – use MarketPosition to see what your current position is: -1 for short, +1 for long and 0 for flat.  MarketPosition acts like a function because you can index it to see what you position was prior to the current position – all you need to do is pass a parameter for the number of positions ago.  If you pass it a one (MarketPosition(1)) then it will return the your prior position.  If you define a variable such as MP you can store each bars MarketPosition and this can come in handy.

mp = marketPosition;

If mp[1] <> 1 and mp = 1 then buysToday = buysToday + 1;
If mp[1] <> -1 and mp = -1 then sellsToday = sellsToday + 1;
Keeping Track of Buy and Sell Entries on Daily Basis

The code compares prior bar’s MP value with the current bar’s.   If there is a change in the value, then the current market position has changed.   Going from not 1 to 1 indicates a new long position.  Going from not -1 to -1 implies a new short.  If the criteria is met, then the buysToday or sellsToday counters are incremented.  If you want to keep the number of buys or sells to a certain level, let’s say once or twice,  you can incorporate this into your code.

If  time >= startTradeTime and t < endTradeTime and 
	buysToday < 1 and 
	rsi(c,rsiLen) crosses above rsiBuyVal then buy this bar on close;
If  time >= startTradeTime and t < endTradeTime and 
	sellsToday < 1 and 
	rsi(c,rsiLen) crosses below rsiShortVal then sellShort this bar on close;
Using MP to Keep Track of BuysToday and SellsToday

This logic will work most of the time, but it depends on the robustness of the builtin MarketPosition function Look how this logic fails in the following chart:

I didn't want entries in the same direction per day!
I only wanted 1 short entry per day!

MarketPosition Failure

Failure in the sense that the algorithm shorted twice in the same day.  Notice on the first trade how the profit objective was hit on the very next bar.  The problem with MarketPosition is that it only updates at the end of the bar one bar after the entry.  So MarketPosition stays 0 during the duration of this trade.  If MarketPosition doesn’t change then my counter won’t work.  TradeStation should update MarketPosition at the end of the entry bar.  Alas it doesn’t work this way.  I figured a way around it though.  I will push the code out and explain it later in more detail.

Input: rsiLen(14),rsiBuyVal(30),rsiShortVal(70),profitObj$(250),protStop$(300),startTradeTime(940),endTradeTime(1430);

Vars: mp(0),buysToday(0),sellsToday(0),startOfDayNetProfit(0);

If d <> d[1] then
Begin
	buysToday = 0;
	sellsToday = 0;
	startOfDayNetProfit = netProfit;
end;

{mp = marketPosition;

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

If entriesToday(date) > buysToday + sellsToday then 
Begin
	If marketPosition = 1 then buysToday = buysToday + 1;
	If marketPosition =-1 then sellsToday = sellsToday + 1;
	If marketPosition = 0 then
	Begin
		if netProfit > startOfDayNetProfit then
		begin
			if exitPrice(1) > entryPrice(1) then buysToday = buysToday + 1;
			If exitPrice(1) < entryPrice(1) then sellsToday = sellsToday + 1;
		end;;
		if netProfit < startOfDayNetProfit then
		Begin
			if exitPrice(1) < entryPrice(1) then buysToday = buysToday + 1;
			If exitPrice(1) > entryPrice(1) then sellsToday = sellsToday + 1;
		end;
	end;
	print(d," ",t," ",buysToday," ",sellsToday);
end;

If  time >= startTradeTime and t < endTradeTime and 
	buysToday < 1 and 
	rsi(c,rsiLen) crosses above rsiBuyVal then buy this bar on close;
If  time >= startTradeTime and t < endTradeTime and 
	sellsToday < 1 and 
	rsi(c,rsiLen) crosses below rsiShortVal then sellShort this bar on close;

SetProfittarget(profitObj$);
SetStopLoss(protStop$);

SetExitOnClose;
A Better Buy and Short Entries Counter

TradeStation does update EntriesToday at the end of the bar so you can use this keyword/function to help keep count of the different type of entries.  If MP is 0 and EntriesToday increments then you know an entry and an exit has occurred (takes care of the MarketPosition snafu) – all you need to do is determine if the entry was a buy or a sell.  NetProfit is also updated when a trade is closed.   I establish the StartOfDayNetProfit on the first bar of the day (line 9 in the code) and then examine EntriesToday and if NetProfit increased or decreased.  EntryPrice and ExitPrice are also updated at the end of the bar so I can also use them to extract the information I need.   Since MarketPosition is 0  I have to pass 1 to the EntryPrice and ExitPrice functions – prior position’s prices.  From there I can determine if a Long/Short entry occurred.  This seems like a lot of work for what you get out of it, but if you are controlling risk by limiting the number of trades (exposure) then an accurate count is so very important.

An alternative is to test on a higher resolution of data – say 1 minute bars.  In doing this you give a buffer to the MarketPosition function – more bars to catch up.

 

Backtesting with [Trade Station,Python,AmiBroker, Excel]. Intended for informational and educational purposes only!

Follow

Get every new post delivered to your Inbox

Join other followers: