Back to Community
DIA Trend Within Trend

This is a concept that takes the basic turtle trend model and puts a little spin on it. The orders are on stock in the dow. Besides for the basic trend of the stock, it also includes the trend of the dow when starting. Pyramiding and moving stops based on N is included, or at least I think they are correctly included.

As you can see, its pretty volatile but when its working well its great. I need to figure out how to stop the bleeding when things are going poorly and I think it might be a good model. It can also easy be applied to other indexes as well.

Clone Algorithm
66
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# based off of rules from
# http://bigpicture.typepad.com/comments/files/turtlerules.pdf

# uses ETFs:
# http://etfdb.com/type/commodity/exposure/futures-based/no-leveraged/

# this is just a start, there additional rules that haven't yet been implemented

from collections import deque
import math

atr = ta.ATR(timeperiod=20) # used to calculate 20-period ATR

def initialize(context):
    
    # you can find other tickers at that ETF page above
    context.securities = [
                              sid(2174), # spider DIA
                              sid(4922), # MMM 3M
                              sid(6653), # T AT&T Inc
                              sid(679), # AXP American Express Co
                              sid(698), # BA Boeing Co
                              sid(1267), # CAT Caterpillar Inc
                              sid(23112), # CVX Chevron Corp
                              sid(1900), # CSCO Cisco Systems Inc
                              sid(2119), # DD Dupont E I De Nemours & Co
                              sid(8347), # XOM Exxon Mobil Corp
                              sid(3149), # GE General Electric Co
                              sid(20088), # GS Goldman Sachs Group Inc
                              sid(3496), # HD Home Depot Inc
                              sid(3951), # INTC Intel Corp
                              sid(3766), # IBM International Business Machines
                              sid(4151), # JNJ Johnson & Johnson
                              sid(25006), # JPM JPMorgan Chase and Co
                              sid(4707), # MCD McDonald's Corp
                              sid(5029), # MRK Merck & Co Inc
                              sid(5061), # MSFT Microsoft Corp
                              sid(5328), # NKE Nike Inc
                              sid(5923), # PFE Pfizer Inc
                              sid(5938), # PG Procter & Gamble Co
                              sid(4283), # KO The Coca-Cola Co
                              sid(7041), # TRV Travelers Companies Inc
                              sid(7883), # UTX United Technologies Corp
                              sid(7792), # UNH UnitedHealth Group Inc
                              sid(21839), # VZ Verizon Communications Inc
                              sid(35920), # V Visa Inc
                              sid(8229), # WMT Wal-Mart Stores Inc
                              sid(2190), # DIS Walt Disney Co
                        ]
    
    # define dict for various security values like prices, N and pyramids
    context.security_prices = dict()
    context.security_buyPrice = dict()
    context.security_direction = dict()
    context.security_N = dict()
    context.security_pyramids = dict()

    for security in context.securities:
        if security is not sid(2174):
            context.security_prices[security] = []
            context.security_buyPrice[security] = 0
            context.security_direction[security] = 0
            context.security_N[security] = 0
            context.security_pyramids[security] = 0

    # define list for dia prices
    context.dia_prices = []    
    
def addNewPrice(priceList, newPrice, pricesToKeep):
    try:
        priceList.append(newPrice)
        
        if len(priceList) > pricesToKeep:
            return priceList[1:pricesToKeep+1]
        else:
            return priceList
    except:
        return priceList

def securityHasOrders(context, security):
    if len(get_open_orders(security)) == 0:
        context.security_buyPrice[security] = 0
        context.security_direction[security] = 0
        context.security_N[security] = 0
        context.security_pyramids[security] = 0
        return False
    else:
        return True

def orderSecurity(context, data, security):
    N = context.security_N[security]
    stop = data[security].price + (context.security_direction[security]*2*N)
    trade_amt = math.ceil(context.portfolio.portfolio_value*.01/N)
    order_shares = (context.security_direction[security]*trade_amt)/data[security].price

    #loop through the current orders and update the stop
    for o in get_open_orders(security):
        log.info("updating security %s stop from %s to %s for direction %s" % (security.symbol, o.stop, stop, context.security_direction[security]))
        o.stop = stop
        
    log.info("ordering %s shares of %s at price %s with a stop of %s" % (order_shares, security.symbol, data[security].price, stop))

    order(security, order_shares, stop_price=stop)
    context.security_pyramids[security] += 1

def handle_data(context, data):
    #constant trend lengths
    diaLength = 10
    securityLength = 20
    maxPyramids = 6
    percentCash = context.portfolio.cash/(context.portfolio.cash + context.portfolio.positions_value)

    diaTrendDirection = 0

#    diaIsHigh = False
#    diaIsLow = False
    # for each security in the list        
    for security in context.securities:
        if security not in data or data[security] is None or data[security].price is None:
            continue

        if security is sid(2174):
            context.dia_prices = addNewPrice(context.dia_prices, data[security].price, diaLength)
            
#            diaIsHigh = True if data[security].price >= max(context.dia_prices) else False
#            diaIsLow = True if data[security].price <= min(context.dia_prices) else False
            #is high
            if data[security].price >= max(context.dia_prices):
                diaTrendDirection = 1
            #is low
            elif data[security].price <= min(context.dia_prices):
                diaTrendDirection = -1
            else:
                diaTrendDirection = 0
        
        else:
            context.security_prices[security] = addNewPrice(context.security_prices[security], data[security].price, securityLength)

            if percentCash > 0.1:
                if securityHasOrders(context, security) and (context.security_pyramids[security] < maxPyramids):
                    pyramidPrice = context.security_buyPrice[security] + (context.security_N[security] * context.security_pyramids[security])

                    #buying scenario where the direction of the price and the pyramid price are correct
                    if (context.security_direction[security] > 0 and data[security].price >= pyramidPrice) or (context.security_direction[security] < 0 and data[security].price <= pyramidPrice):
                         orderSecurity(context, data, security)

                else:   
                    if math.isnan(atr(data)[security]) is False and atr(data)[security] > 0:
                        securityTrendDirection = 0
                        # is high
                        if data[security].price >= max(context.security_prices[security]):
                            securityTrendDirection = 1
                        # is low
                        elif data[security].price <= min(context.security_prices[security]):
                            securityTrendDirection = -1

                        if (securityTrendDirection > 0 and diaTrendDirection > 0) or (securityTrendDirection < 0 and diaTrendDirection < 0):
                            # long
                            context.security_N[security] = atr(data)[security]
                            context.security_buyPrice[security] = data[security].price
                            context.security_direction[security] = securityTrendDirection
                            orderSecurity(context, data, security)
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.
9 responses

Yeah, I know but I figure you could use the same basic idea and use other close information to help prop up the trends.

I fixed an issue with the stop and I think its in better shape.

A question, is the way that I set up how I set and update stops good or is there a better way to do it?

Clone Algorithm
66
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# based off of rules from
# http://bigpicture.typepad.com/comments/files/turtlerules.pdf

# uses ETFs:
# http://etfdb.com/type/commodity/exposure/futures-based/no-leveraged/

# this is just a start, there additional rules that haven't yet been implemented

from collections import deque
import math

atr = ta.ATR(timeperiod=20) # used to calculate 20-period ATR

def initialize(context):
    
    # you can find other tickers at that ETF page above
    context.securities = [
                              sid(2174), # spider DIA
                              sid(4922), # MMM 3M
                              sid(6653), # T AT&T Inc
                              sid(679), # AXP American Express Co
                              sid(698), # BA Boeing Co
                              sid(1267), # CAT Caterpillar Inc
                              sid(23112), # CVX Chevron Corp
                              sid(1900), # CSCO Cisco Systems Inc
                              sid(2119), # DD Dupont E I De Nemours & Co
                              sid(8347), # XOM Exxon Mobil Corp
                              sid(3149), # GE General Electric Co
                              sid(20088), # GS Goldman Sachs Group Inc
                              sid(3496), # HD Home Depot Inc
                              sid(3951), # INTC Intel Corp
                              sid(3766), # IBM International Business Machines
                              sid(4151), # JNJ Johnson & Johnson
                              sid(25006), # JPM JPMorgan Chase and Co
                              sid(4707), # MCD McDonald's Corp
                              sid(5029), # MRK Merck & Co Inc
                              sid(5061), # MSFT Microsoft Corp
                              sid(5328), # NKE Nike Inc
                              sid(5923), # PFE Pfizer Inc
                              sid(5938), # PG Procter & Gamble Co
                              sid(4283), # KO The Coca-Cola Co
                              sid(7041), # TRV Travelers Companies Inc
                              sid(7883), # UTX United Technologies Corp
                              sid(7792), # UNH UnitedHealth Group Inc
                              sid(21839), # VZ Verizon Communications Inc
                              sid(35920), # V Visa Inc
                              sid(8229), # WMT Wal-Mart Stores Inc
                              sid(2190), # DIS Walt Disney Co
                        ]
    
    # define dict for various security values like prices, N and pyramids
    context.security_prices = dict()
    context.security_buyPrice = dict()
    context.security_direction = dict()
    context.security_N = dict()
    context.security_pyramids = dict()

    for security in context.securities:
        if security is not sid(2174):
            context.security_prices[security] = []
            context.security_buyPrice[security] = 0
            context.security_direction[security] = 0
            context.security_N[security] = 0
            context.security_pyramids[security] = 0

    # define list for dia prices
    context.dia_prices = []    
    
def addNewPrice(priceList, newPrice, pricesToKeep):
    try:
        priceList.append(newPrice)
        
        if len(priceList) > pricesToKeep:
            return priceList[1:pricesToKeep+1]
        else:
            return priceList
    except:
        return priceList

def securityHasOrders(context, security):
    if len(get_open_orders(security)) == 0:
        context.security_buyPrice[security] = 0
        context.security_direction[security] = 0
        context.security_N[security] = 0
        context.security_pyramids[security] = 0
        return False
    else:
        return True

def orderSecurity(context, data, security):
    N = context.security_N[security]
    stop = data[security].price - (context.security_direction[security]*2*N)
    trade_amt = math.ceil(context.portfolio.portfolio_value*.02/N)
    order_shares = (context.security_direction[security]*trade_amt)/data[security].price

    #loop through the current orders and update the stop
    for o in get_open_orders(security):
        log.info("updating security %s stop from %s to %s for direction %s" % (security.symbol, o.stop, stop, context.security_direction[security]))
        o.stop = stop
        
    log.info("ordering %s shares of %s at price %s with a stop of %s" % (order_shares, security.symbol, data[security].price, stop))

    order(security, order_shares, stop_price=stop)
    context.security_pyramids[security] += 1

def handle_data(context, data):
    #constant trend lengths
    diaLength = 10
    securityLength = 20
    maxPyramids = 6
    percentCash = context.portfolio.cash/(context.portfolio.cash + context.portfolio.positions_value)

    diaTrendDirection = 0

    # for each security in the list        
    for security in context.securities:
        if security not in data or data[security] is None or data[security].price is None:
            continue

        if security is sid(2174):
            context.dia_prices = addNewPrice(context.dia_prices, data[security].price, diaLength)
            
            #is high
            if data[security].price >= max(context.dia_prices):
                diaTrendDirection = 1
            #is low
            elif data[security].price <= min(context.dia_prices):
                diaTrendDirection = -1
            else:
                diaTrendDirection = 0
        
        else:
            context.security_prices[security] = addNewPrice(context.security_prices[security], data[security].price, securityLength)

            if percentCash > 0.1:
                if securityHasOrders(context, security) and (context.security_pyramids[security] < maxPyramids):
                    pyramidPrice = context.security_buyPrice[security] + (context.security_N[security] * context.security_pyramids[security])

                    #buying scenario where the direction of the price and the pyramid price are correct
                    if (context.security_direction[security] > 0 and data[security].price >= pyramidPrice) or (context.security_direction[security] < 0 and data[security].price <= pyramidPrice):
                         orderSecurity(context, data, security)

                else:   
                    if math.isnan(atr(data)[security]) is False and atr(data)[security] > 0:
                        securityTrendDirection = 0
                        # is high
                        if data[security].price >= max(context.security_prices[security]):
                            securityTrendDirection = 1
                        # is low
                        elif data[security].price <= min(context.security_prices[security]):
                            securityTrendDirection = -1

                        if (securityTrendDirection > 0 and diaTrendDirection > 0) or (securityTrendDirection < 0 and diaTrendDirection < 0):
                            # long
                            context.security_N[security] = atr(data)[security]
                            context.security_buyPrice[security] = data[security].price
                            context.security_direction[security] = securityTrendDirection
                            orderSecurity(context, data, security)
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.

Hello John,

I've run the algo but from looking at the full backtest it only trades once on 2010-01-04.

P.

Peter,

Yeah, you are right, I just see this algo hanging on to the stocks long term and not letting go. Thats why I was wondering about the stops and if I'm doing them right. More specifically, if I'm updating the stops correctly on line 99 in the above backtest. The weird thing is that in even when testing on longer periods, it still performs pretty well, see the attached back test. With that said, I'm pretty sure its also over leveraged and I need to look into that as well.

Thanks for the input, keep it coming. I'm new to this community and Python so keep in coming.

John

Clone Algorithm
66
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# based off of rules from
# http://bigpicture.typepad.com/comments/files/turtlerules.pdf

# uses ETFs:
# http://etfdb.com/type/commodity/exposure/futures-based/no-leveraged/

# this is just a start, there additional rules that haven't yet been implemented

from collections import deque
import math

atr = ta.ATR(timeperiod=20) # used to calculate 20-period ATR

def initialize(context):
    
    # you can find other tickers at that ETF page above
    context.securities = [
                              sid(2174), # spider DIA
                              sid(4922), # MMM 3M
                              sid(6653), # T AT&T Inc
                              sid(679), # AXP American Express Co
                              sid(698), # BA Boeing Co
                              sid(1267), # CAT Caterpillar Inc
                              sid(23112), # CVX Chevron Corp
                              sid(1900), # CSCO Cisco Systems Inc
                              sid(2119), # DD Dupont E I De Nemours & Co
                              sid(8347), # XOM Exxon Mobil Corp
                              sid(3149), # GE General Electric Co
                              sid(20088), # GS Goldman Sachs Group Inc
                              sid(3496), # HD Home Depot Inc
                              sid(3951), # INTC Intel Corp
                              sid(3766), # IBM International Business Machines
                              sid(4151), # JNJ Johnson & Johnson
                              sid(25006), # JPM JPMorgan Chase and Co
                              sid(4707), # MCD McDonald's Corp
                              sid(5029), # MRK Merck & Co Inc
                              sid(5061), # MSFT Microsoft Corp
                              sid(5328), # NKE Nike Inc
                              sid(5923), # PFE Pfizer Inc
                              sid(5938), # PG Procter & Gamble Co
                              sid(4283), # KO The Coca-Cola Co
                              sid(7041), # TRV Travelers Companies Inc
                              sid(7883), # UTX United Technologies Corp
                              sid(7792), # UNH UnitedHealth Group Inc
                              sid(21839), # VZ Verizon Communications Inc
                              sid(35920), # V Visa Inc
                              sid(8229), # WMT Wal-Mart Stores Inc
                              sid(2190), # DIS Walt Disney Co
                        ]
    
    # define dict for various security values like prices, N and pyramids
    context.security_prices = dict()
    context.security_buyPrice = dict()
    context.security_direction = dict()
    context.security_N = dict()
    context.security_pyramids = dict()

    for security in context.securities:
        if security is not sid(2174):
            context.security_prices[security] = []
            context.security_buyPrice[security] = 0
            context.security_direction[security] = 0
            context.security_N[security] = 0
            context.security_pyramids[security] = 0

    # define list for dia prices
    context.dia_prices = []    
    
def addNewPrice(priceList, newPrice, pricesToKeep):
    try:
        priceList.append(newPrice)
        
        if len(priceList) > pricesToKeep:
            return priceList[1:pricesToKeep+1]
        else:
            return priceList
    except:
        return priceList

def securityHasOrders(context, security):
    if len(get_open_orders(security)) == 0:
        context.security_buyPrice[security] = 0
        context.security_direction[security] = 0
        context.security_N[security] = 0
        context.security_pyramids[security] = 0
        return False
    else:
        return True

def orderSecurity(context, data, security):
    N = context.security_N[security]
    stop = data[security].price - (context.security_direction[security]*2*N)
    trade_amt = math.ceil(context.portfolio.portfolio_value*.02/N)
    order_shares = (context.security_direction[security]*trade_amt)/data[security].price

    #loop through the current orders and update the stop
    for o in get_open_orders(security):
        log.info("updating security %s stop from %s to %s for direction %s" % (security.symbol, o.stop, stop, context.security_direction[security]))
        o.stop = stop
        
    log.info("ordering %s shares of %s at price %s with a stop of %s" % (order_shares, security.symbol, data[security].price, stop))

    order(security, order_shares, stop_price=stop)
    context.security_pyramids[security] += 1

def handle_data(context, data):
    #constant trend lengths
    diaLength = 10
    securityLength = 20
    maxPyramids = 6
    percentCash = context.portfolio.cash/(context.portfolio.cash + context.portfolio.positions_value)

    diaTrendDirection = 0

    # for each security in the list        
    for security in context.securities:
        if security not in data or data[security] is None or data[security].price is None:
            continue

        if security is sid(2174):
            context.dia_prices = addNewPrice(context.dia_prices, data[security].price, diaLength)
            
            #is high
            if data[security].price >= max(context.dia_prices):
                diaTrendDirection = 1
            #is low
            elif data[security].price <= min(context.dia_prices):
                diaTrendDirection = -1
            else:
                diaTrendDirection = 0
        
        else:
            context.security_prices[security] = addNewPrice(context.security_prices[security], data[security].price, securityLength)

            if percentCash > 0.1:
                if securityHasOrders(context, security) and (context.security_pyramids[security] < maxPyramids):
                    pyramidPrice = context.security_buyPrice[security] + (context.security_N[security] * context.security_pyramids[security])

                    #buying scenario where the direction of the price and the pyramid price are correct
                    if (context.security_direction[security] > 0 and data[security].price >= pyramidPrice) or (context.security_direction[security] < 0 and data[security].price <= pyramidPrice):
                         orderSecurity(context, data, security)

                else:   
                    if math.isnan(atr(data)[security]) is False and atr(data)[security] > 0:
                        securityTrendDirection = 0
                        # is high
                        if data[security].price >= max(context.security_prices[security]):
                            securityTrendDirection = 1
                        # is low
                        elif data[security].price <= min(context.security_prices[security]):
                            securityTrendDirection = -1

                        if (securityTrendDirection > 0 and diaTrendDirection > 0) or (securityTrendDirection < 0 and diaTrendDirection < 0):
                            # long
                            context.security_N[security] = atr(data)[security]
                            context.security_buyPrice[security] = data[security].price
                            context.security_direction[security] = securityTrendDirection
                            orderSecurity(context, data, security)
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.

Hello John,

I'm looking at stop and limit orders myself and I think the documentation is not clear. I believe that the order and the stop are placed separately as in:

price = data[sid(24)].close_price  
order(sid(24), 110)  
order(sid(24), -110, stop_price = price * 0.95)  

which results in two orders i.e. a filled market order and an open stop order.

The stupid thing is I made a tiny contribution to zipline relating to stop and limit orders but that was so long ago I've forgotten most of what I did.

P.

Hello AM,

Thanks. How should the attached be better implemented?

P.

Clone Algorithm
20
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
from pytz import timezone

def initialize(context):
    context.first = True

    
def handle_data(context, data):
    if not intradingwindow_check(context) and not context.first:
        return
    
    print get_open_orders()
    
    record(Price=data[sid(24)].close_price)
    
    # This code does not work i.e. buy, price drops, nothing
    '''if context.first:
        order(sid(24), 100, stop_price=300)
        context.first = False'''
        
    # This code works i.e. buy, price drops, sell
    if context.first:
        log.info("Placing orders...")
        order(sid(24), 110)
        order(sid(24), -110, stop_price = 300 )
        context.first = False

        
def intradingwindow_check(context):  
    # Converts all time-zones into US EST to avoid confusion  
    loc_dt = get_datetime().astimezone(timezone('US/Eastern'))  
    # if loc_dt.hour > 12 and loc_dt.hour < 15:  
    # if loc_dt.hour == 10 and loc_dt.minute == 0:  
    if loc_dt.hour == 9 and loc_dt.minute == 31:  
        return True  
    else:  
        return False         
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.

Hello AM,

Thanks - your test is attached for others to see. I've asked for feedback from Quantopian about the syntax of stop and limit orders. Looking back at some zipline work I did I was writing this i.e. a market order followed by a stop order:

from datetime import datetime  
import pytz  
from zipline.transforms.utils import EventWindow

from zipline.algorithm import TradingAlgorithm  
from zipline.utils.factory import load_from_yahoo


class BuyApple(TradingAlgorithm):

    def initialize(self):  
        self.firstOrderplaced = False

    def handle_data(self, data):  
        print "--------------------"  
        print "Datetime in handle_data : " + str(self.datetime)  
        print data['AAPL'].price  
        print self.portfolio.cash  
        if not self.firstOrderplaced:  
            self.order('AAPL', 100,)  
            self.order('AAPL', -100, stop_price=118.00)  
            #slf.order('AAPL', -100, limit_price=131.00)  
            #self.order('AAPL', -100, limit_price=123.00, stop_price=125.60)  
            self.firstOrderplaced = True  


if __name__ == '__main__':  
    start = datetime(2008, 1, 26, 0, 0, 0, 0, pytz.utc)  
    end = datetime(2008, 4, 1, 0, 0, 0, 0, pytz.utc)  
    data = load_from_yahoo(stocks=['AAPL'], indexes={}, start=start,  
                           end=end)  
    simple_algo = BuyApple(instant_fill=True)  
    results = simple_algo.run(data)  

When run in IDLE the output is:

>>>  
AAPL  
--------------------  
Datetime in handle_data : 2008-01-28 00:00:00+00:00  
125.71  
100000.0  
--------------------  
Datetime in handle_data : 2008-01-29 00:00:00+00:00  
127.19  
87413.429  
--------------------  
Datetime in handle_data : 2008-01-30 00:00:00+00:00  
127.81  
87413.429  
--------------------  
Datetime in handle_data : 2008-01-31 00:00:00+00:00  
130.88  
87413.429  
--------------------  
Datetime in handle_data : 2008-02-01 00:00:00+00:00  
129.32  
87413.429  
--------------------  
Datetime in handle_data : 2008-02-04 00:00:00+00:00  
127.29  
87413.429  
--------------------  
Datetime in handle_data : 2008-02-05 00:00:00+00:00  
125.08  
87413.429  
--------------------  
Datetime in handle_data : 2008-02-06 00:00:00+00:00  
117.96  
87413.429  
--------------------  
Datetime in handle_data : 2008-02-07 00:00:00+00:00  
117.23  
99194.633  
--------------------  

P.

Clone Algorithm
20
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Trading Daily data, starting 1/1/2013

def initialize(context):  
    context.first = True  
    context.stock = sid(24)  
def handle_data(context, data):  
    record(Price = data[context.stock].close_price)  
    record(OpenOrders = 1 if get_open_orders() else 0)  
    # Order is submitted and "something" is executed immediately  
    if context.first:  
        order(context.stock, 100, stop_price=400)  
        context.first = False  
    # We get a notional amount immediately, when we should not have an amount until 4/18/2013  
    if (context.portfolio.positions[context.stock].amount != 0):  
        record (Notional = context.portfolio.positions[context.stock].amount * data[context.stock].close_price)
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.

Hello John,

Apologies for high-jacking your thread. I'll start a new one on order syntax at https://www.quantopian.com/posts/usage-and-syntax-of-stop-orders.

P.

No problem at all. Feel free to high-jack my thread. It helps me learn. Thanks for the help so far.