Tag Archives: Python

State of Trend Following – Part 1

Clenow’s Trend Following System

Its a new decade! Time to see what’s up with Trend Following.

I am a huge fan of Andreas Clenow’s books, and how he demonstrated that a typical trader could replicate the performance of most large Trend Following CTAs and not pay the 2% / 20% management/incentive combo fees.  So. I felt the system that he described in his book would be a great representation of The State of Trend Following.  At the same time I am going to demonstrate TradingSimula18 (the software included in my latest book).

System Description

Take a look at my last post.  I provide the EasyLanguage and a pretty good description of Clenow’s strategy.

TradingSimula18 Code [Python]

#---------------------------------------------------------------------------------------------------
#  Start programming your great trading ideas below here - don't touch stuff above
#---------------------------------------------------------------------------------------------------
#  Define Long, Short, ExitLong and ExitShort Levels - mind your indentations
            ATR = sAverage(myTrueRange,30,curBar,1)
            posSize = 2000/(ATR*myBPV)
            posSize = max(int(posSize),1)
            posSize = min(posSize,20)
            avg1 = xAverage(myClose,marketVal5[curMarket],50,curBar,1)
            avg2 = xAverage(myClose,marketVal6[curMarket],100,curBar,1)
            marketVal5[curMarket] = avg1
            marketVal6[curMarket] = avg2
            donchHi = highest(myHigh,50,curBar,1)
            donchLo = lowest(myLow,50,curBar,1)

            if mp == 1 : marketVal1[curMarket] = max(marketVal1[curMarket],myHigh[curBar-1]- 3 * ATR)
            if mp ==-1 : marketVal2[curMarket] = min(marketVal2[curMarket],myLow[curBar-1]+ 3 * ATR)
#  Long Entry
            if avg1 > avg2 and myHigh[curBar-1] == donchHi and mp !=1:
                price = myOpen[curBar]
                tradeName = "TFClenowB";numShares = posSize
                marketVal1[curMarket] = price - 3 * ATR
                if mp <= -1:
                profit,curShares,trades = bookTrade(entry,buy,price,myDate[curBar],tradeName,numShares)
                barsSinceEntry = 1
                marketMonitorList[curMarket].setSysMarkTrackingInfo(tradeName,cumuProfit,mp,barsSinceEntry,curShares,trades)
#  Long Exit
            if mp == 1 and myClose[curBar-1] <= marketVal1[curMarket] and barsSinceEntry > 1:
                price = myOpen[curBar]
                tradeName = "Lxit";numShares = curShares
                profit,curShares,trades = bookTrade(exit,ignore,price,myDate[curBar],tradeName,numShares)
                todaysCTE = profit;barsSinceEntry = 0
                marketMonitorList[curMarket].setSysMarkTrackingInfo(tradeName,cumuProfit,mp,barsSinceEntry,curShares,trades)
#  Short Entry
            if avg1 < avg2 and myLow[curBar-1] == donchLo and mp !=-1:
                price = myOpen[curBar];numShares = posSize
                marketVal2[curMarket] = price + 3 * ATR
                if mp >= 1:
                tradeName = "TFClenowS"
                profit,curShares,trades = bookTrade(entry,sell,price,myDate[curBar],tradeName,numShares)
                barsSinceEntry = 1
                marketMonitorList[curMarket].setSysMarkTrackingInfo(tradeName,cumuProfit,mp,barsSinceEntry,curShares,trades)
#  Short Exit
            if mp == -1 and myClose[curBar-1] >= marketVal2[curMarket] and barsSinceEntry > 1:
                price = myOpen[curBar]
                tradeName = "Sxit"; numShares = curShares
                profit,curShares,trades = bookTrade(exit,ignore,price,myDate[curBar],tradeName,numShares)
                todaysCTE = profit;barsSinceEntry = 0
                marketMonitorList[curMarket].setSysMarkTrackingInfo(tradeName,cumuProfit,mp,barsSinceEntry,curShares,trades)
#----------------------------------------------------------------------------------------------------------------------------
# - Do not change code below - trade, portfolio accounting - our great idea should stop here
#----------------------------------------------------------------------------------------------------------------------------
 
TradingSimula18 Python System Testing Environment

I am going to go over this very briefly.   I know that many of the readers of my blog have attempted to use Python and the various packages out there and have given up on it.  Quantopia and QuantConnect are great websites, but I feel they approach back-testing with a programmer in mind.  This was the main reason I created TS-18 – don’t get me wrong its not a walk in the park either, but it doesn’t rely on external libraries to get the job done.  All the reports I show here are generated from the data created solely by TS-18.  Plus it is very modular – Step 1 leads to Step2 and on and on.   Referring to the code I calculate the ATR (average true range) by calling the simple average function sAverage.  I pass it myTrueRanges, 30, curBar and 1.   I am looking for the average true range over the last 30 days.  I then move onto my position sizing – posSize = $2,000 / ATR in $s.  PosSize must fit between 1 and 20 contracts.  The ATR calculation can get rather small for some markets and the posSize can get rather large.  Avg1 and Avg2 are exponential moving averages of length 50 and 100DonchHi and donchLo are the highest high and lowest low of the past 50 days.   If mp == 1 (long position) then a trailing stop (marketVal1) is set to whichever is higher – the current marketVal1 or the yesterday’s High – 3 X ATR;  the trailing stop tracks new intra-trade highs.  The trailing stop for the short side, marketVal2 is calculated in a similar manner, but low prices are used as well as a positive offset of 3 X ATR.  

Now the next section of code is quite a bit different than say EasyLanguage, but parallels some of the online Python paradigms. Here you must test the current bar’s extremes against the donchHi if you are flat and marketVal1 (the trailing stop variable) if you are long.  If flat you also test the low of the bar against donchLo.  The relationship between avg1 and avg2 are also examined.  If the testing criteria is true, then its up to you to assign the correct price, posSize and tradeName.  So you have four independent if-then constructs:

  • Long Entry – if flat test to see if a long position should be initiated
  • Long Exit – if Long then test to see if a liquidation should be initiated
  • Short Entry – if flat test to see if a short position should be initiated
  • Short Exit – if Short then test to see if a liquidation should be initiated

That’s it – all of the other things are handled by TS-18.  Now that I have completely bored you out of your mind, let’s move onto some results.

Results from 2000 – risking $2,000 per trade:

Roller Coaster Ride for most CTAs, Last one out turn off the lights!

Sector Performance from 2000

Sector Performance from 2000

From this chart it doesn’t make much sense to trade MEATS, SOFTS or GRAINS with a Trend Following approach or does it?

In the next post, I will go over the results with more in depth and possibly propose some ideas that might or might not help.  Stay Tuned!

 

Please follow and like us:
error

Turtle Volatility Loss in Python Back Tester – Part 3 in Series

The Turtle N or Volatility is basically a 20-day Average True Range in terms of  Dollars.  This amount is considered the market volatility.  In other words the market, based on the average, can either move up or down by this amount.  It can move much less or much further; this is just an estimate.  If the market moves 2 N against a position, then as a Turtle you were to liquidate your stake in that commodity.  The logic indicates that if the market has a break out and then moves 2 N in the opposite direction, then the break out has failed.  First the code must be defined to represent the market volatility.  This is simple enough by using the sAverage function call and passing it the trueRanges and 20 days.  There’s no use in converting this to dollars because what we want is a price offset.  Once a position is entered the turtleN  is either added to the price [short position] or subtracted from the price [long position] to determine the respective stop levels.  Look at lines 2, 8 and 17 to see how this is handled.  An additional  trade code block must be added to facilitate this stop.  Lines 17 to 28 takes care of exiting a long position when the market moves 2 N in the opposite direction.   This new stop is in addition to the highest/lowest high/low stops for the past 10 -20 days.

        atrVal = sAverage(trueRanges,20,i,1)
        turtleN = atrVal*2


            if lastTradeLoser == True :
                tradeName = "Turt20Buy"
                mp += 1
                longNExitStop = price - turtleN
                marketPosition[i] = mp
                entryPrice.append(price)
                entryQuant.append(numShares)
                curShares = curShares + numShares
                trades = tradeInfo('buy',myDate[i],tradeName,entryPrice[-1],numShares,1)
                barsSinceEntry = 1
                listOfTrades.append(trades)
#long Exit - 2 N Loss
        if mp >= 1 and myLow[i] <= longNExitStop and barsSinceEntry > 1:
            price = min(myOpen[i],longNExitStop)
            tradeName = "LongNExitLoss"
            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
Turtle Part 3

 

Please follow and like us:
error

Implementing Turtle Algorithm into the Python Backtester

I include the Python Backtester in my latest book “The Ultimate Algorithmic Trading System Toolbox” book.  A good tutorial on how to use it would be to program the Turtle Algorithm in three different parts.   Here is part 1:

Entry Description: Buy on stop at highest high of last twenty days.  Short on lowest low of last twenty days.

Exit Description: Exit long on stop at lowest low of last ten days.  Exit short on highest high of past ten days.

Position Sizing:  Risk 2% of simulated 100K account on each trade.  Calculate market risk by utilizing the ten day ATR.  Size(shares or contracts) = $2,000/ATR in dollars.

Python code to  input into the backtester:

 

initCapital = 100000
riskPerTrade = .02
dollarRiskPerTrade = initCapital * riskPerTrade

        hh20 = highest(myHigh,20,i,1)
        ll20 = lowest(myLow,20,i,1)
        hh10 = highest(myHigh,10,i,1)
        ll10 = lowest(myLow,10,i,1)
        hh55 = highest(myHigh,55,i,1)
        ll55 = lowest(myLow,55,i,1)
        
        atrVal = sAverage(trueRanges,10,i,1)

 #Long Entry Logic
        if (mp==0 or mp==-1) and barsSinceEntry>1 and myHigh[i]>=hh20:
            profit = 0
            price = max(myOpen[i],hh20)
            numShares = max(1,int(dollarRiskPerTrade/(atrVal*myBPV)))
            tradeName = "Turt20Buy"

 #Short Logic
        if (mp==0 or mp==1) and barsSinceEntry>1 and myLow[i] <= ll20: 
            profit = 0 
            price = min(myOpen[i],ll20) 
            numShares = max(1,int(dollarRiskPerTrade/(atrVal*myBPV)))
            tradeName = "Turt20Shrt"

 #Long Exit Loss 
        if mp >= 1 and myLow[i] <= ll10 and barsSinceEntry > 1:
            price = min(myOpen[i],ll10)
            tradeName = "Long10-Liq"

 #Short Exit Loss
        if mp <= -1 and myHigh[i] >= hh10 and barsSinceEntry > 1:
            price = max(myOpen[i],hh10)
            tradeName = "Shrt10-Liq"
Turtle Part 1

 

This snippet only contains the necessary code to use in the Python Backtester – it is not in its entirety.

This algorithm utilizes a fixed fractional approach to position sizing.  Two percent or $2000 is allocated on each trade and perceived market risk is calculated by the ten-day average true range (ATR.)   So if we risk $2000 and market risk is $1000 then 2 contracts are traded.  In Part 2, I will introduce the N risk stop and the LAST TRADE LOSER Filter.

Please follow and like us:
error