31.07.2021 Views

Ultimate Algorithmic Trading System

Using automated systems for trading in stock markets

Using automated systems for trading in stock markets

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

That was the long entry logic only and now we must program the two exits

associated with this algorithm: a money management stop and a moving average

stop. Here is the money management stop logic:

if mp >= 1 and myLow[i] <= entryPrice[-1] - stopAmt and

barsSinceEntry > 1:

price = min(myOpen[i],entryPrice[-1] - stopAmt)

tradeName = "L-MMLoss"

exitDate =myDate[i]

numShares = curShares

exitQuant.append(numShares)

profit,trades,curShares = exitPos(price,myDate[i],

tradeName,numShares)

if curShares == 0 : mp = marketPosition[i] = 0

totProfit += profit

todaysCTE = profit

listOfTrades.append(trades)

maxPositionL = maxPositionL - 1

198

USING PYTHON TO BACKTEST YOUR ALGORITHM

If mp >= 1, then the algorithm’s current position is long. You could state if

mp == 1, but this software has the capability of pyramiding and scaling in and out.

So just always use >= to test for a long or short position. Since we are exiting on

stops, the low of the day is tested against the entryPrice - stopAmt ($3,000).

In Python the last element in a list can be easily accessed by using a -1 inside the

brackets. EntryPrice[-1] simply refers to the last price in the entryPrice list,

which turns out to be the price at which the algorithm assumed a long position.

I have put a small i in the entryPrice list more times than I would like to admit,

and this definitely will throw a monkey wrench into the works. So don’t do it. If

the low of the day is less than or equal to entryPrice - stopAmt, then an exit has

taken place and all you need to do is set the price and the tradeName. The rest

of the code in the block runs in the background. BarsSinceEntry is an internal

variable that keeps track of the number of bars since the last entry, and is used in this

logic to make sure an entry and an exit doesn’t occur on the same bar. This version

of the PSB doesn’t allow more than one entry per bar. Getting out on a stop at the

midpoint between the upper and lower bands is handled in the same manner. The

only difference is the price and the tradeName variables.

if mp >= 1 and myLow[i] <= exitLevel:

price = min(myOpen[i], exitLevel)

tradeName = "L-BollExit"

numShares = curShares

www.rasabourse.com

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!