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.

Leave a Reply