Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Need some help on trade at open vs. trade at close

I am new to quantopian and still familiarize the code.

I was trying to test out trade on open and trade on close. The following codes are cloned from "Ivy Portfolio 200-SMA". The only difference between the following to codes is the schedule_function part. I changed market_close() to market_open(). But when I back-test it, both algo give me the same transaction prices for each asset classes. Can anyone help me on this? I just want both algo to check the signal on the same day using the previous 250 days data and trade at open using opening price or trade at close using closing price ( couple minutes after open or before close are fine too.)

trade on close

# Put any initialization logic here.  The context object will be passed to  
# the other methods in your algorithm.  
from pytz import timezone  
def initialize(context):  
    #This variable set whether you want to allocate your entire portfolio to the best performing assets, or do you want to put the underperforming piece os pie towards cash?  
    context.nocash = False  
    set_symbol_lookup_date('2015-11-30')  
    # list of all raa asset classes  
    context.stocks = symbols('SPY',  
                             'EFA',  
                             'VNQ',  
                             'DBC',  
                             'IEF')  
    schedule_function(rebalance,  
                      date_rule = date_rules.month_end(),  
                      time_rule = time_rules.market_close())  
def rebalance(context, data):  
    buylist = []  
    #find which asset classes are above their 200 day moving average  
    for s in context.stocks:  
        if s in data and data[s].price > data[s].mavg(250):  
            buylist.append(s)

    for s in context.portfolio.positions:  
        if s not in buylist:  
            order_target_percent(s, 0)  
    #if nothing is worth buying, don't open a black hold by dividing by zero  
    if len(buylist) == 0:  
        return  
    #Do you allocae all your portfolio to the best performing asset classes or do you allocate only 1/n?  
    if context.nocash:  
        weight = 0.995/len(buylist)  
    else:  
        weight = 0.995/len(context.stocks)  
    for s in buylist:  
        order_target_percent(s, weight)

def handle_data(context, data):  
    for stock in context.stocks:  
        print stock, data[stock].price  

trade on open

# Put any initialization logic here.  The context object will be passed to  
# the other methods in your algorithm.  
from pytz import timezone  
def initialize(context):  
    #This variable set whether you want to allocate your entire portfolio to the best performing assets, or do you want to put the underperforming piece os pie towards cash?  
    context.nocash = False  
    set_symbol_lookup_date('2015-11-30')  
    # list of all raa asset classes  
    context.stocks = symbols('SPY',  
                             'EFA',  
                             'VNQ',  
                             'DBC',  
                             'IEF')  
    schedule_function(rebalance,  
                      date_rule = date_rules.month_end(),  
                      time_rule = time_rules.market_open())  
def rebalance(context, data):  
    buylist = []  
    #find which asset classes are above their 200 day moving average  
    for s in context.stocks:  
        if s in data and data[s].price > data[s].mavg(250):  
            buylist.append(s)

    for s in context.portfolio.positions:  
        if s not in buylist:  
            order_target_percent(s, 0)  
    #if nothing is worth buying, don't open a black hold by dividing by zero  
    if len(buylist) == 0:  
        return  
    #Do you allocae all your portfolio to the best performing asset classes or do you allocate only 1/n?  
    if context.nocash:  
        weight = 0.995/len(buylist)  
    else:  
        weight = 0.995/len(context.stocks)  
    for s in buylist:  
        order_target_percent(s, weight)

def handle_data(context, data):  
    for stock in context.stocks:  
        print stock, data[stock].price  
3 responses

The most common reason for this is that you are running your backtest in "daily" mode, which you should change to "minute" mode.

Tristan

Thanks for the quick reply, I will try later.

I have another question. When I go to the transacton details, IEF has $108.70 for 2015-3-31, So I go to the research and see if I can replicate the price and see if it's matches the close price. It turns out that it doesn't. Do you have any idea why this happens?

code to run in research:

from pytz import timezone  
price = get_pricing(  
    'IEF',  
    fields = 'price',#modify to price, open_price, high, low or volume to change the field  
    start_date='2015-3-31', #customize your pricing date range  
    end_date = '2015-3-31',  
    frequency='minute', #change to daily for daily pricing  
)

eastern = timezone('US/Eastern')  
price.index = price.index.tz_convert(eastern)  
price[price==108.70]  

I changed it to "minute" mode and it does work but I still couldn't match the minute bar price if I use get_pricing in "research".

And I noticed that on transaction details, orders for one asset class get breakdown by a couple. I initially thought that it might have something to do with the initial capital amount ( orders get break down if liquidity is low), the problem persists as I lower the capital to 100k or even 50k.