Back to Community
Getting incorrect values from before_trading_start()

When I access previous day's close price values from before_trading_start(), it gives me the value of close price but as it was at the open of the previous day. Could someone please guide me what am I doing wrong here?
For example the log output for 2015-01-06, gives me the close price for 2015-01-05 as "2015-01-05 14:31:00+00:00 103.62" , which is incorrect as the time suggests, the same value as taken from log output for 2015-01-07 is "2015-01-05 21:00:00+00:00 103.87", which is the correct value. I can't figure out why it is working like this.

Thanks

Clone Algorithm
1
Loading...
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 quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
#from quantopian.pipeline.factors import SimpleMovingAverage
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import talib

def inspect(context, data):  
    HIGH = history(60, '1d', 'high', ffill=False)  
    HIGH = HIGH.dropna(axis=1)  
    context.good_sids = [Sid for Sid in HIGH if Sid in data]  
    #HIGH = HIGH[Good_Sids]  
    # only use Sid's from the Good_Sids list from now on 

# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
    #set_universe(universe.DollarVolumeUniverse(95,100))
    #set_commission(commission.PerShare(cost=0.01, min_trade_cost=1))
    #set_slippage(slippage.FixedSlippage(spread=0.00))

    context.stocks = symbols('CLX')
    context.i = 0
    context.date = None
    context.trend = None
    context.close_p = None
    context.high_p = None
    context.low_p = None
    context.buy_position = None
    context.buy_price = None
    context.tgt_price = {}
    context.open_positions = {}
    context.order_main = {}
    context.sell_orders = {}
    context.rsi = None
    schedule_function(close_all_open_orders, date_rules.every_day(), time_rules.market_open(minutes=1), half_days=True) 
    schedule_function(order_at_open, date_rules.every_day(), time_rules.market_open(minutes=2), half_days=True) 
    
    
def before_trading_start(context,data):
    if context.i == 0:
        return
    #context.trend = DataFrame(np.where(context.close_p > context.close_p.shift(1), 1, -1), context.close_p.index, context.close_p.columns)
    inspect(context,data)
    context.close_p = context.close_p[context.good_sids]
    context.high_p = context.high_p[context.good_sids]
    context.low_p = context.low_p[context.good_sids]
    context.trend = DataFrame(0, context.close_p.index,  context.close_p.columns)
    context.buy_position = DataFrame(0, context.close_p.index,  context.close_p.columns)
    #context.buy_price = DataFrame(np.nan, context.close_p.index,  context.close_p.columns)
    #context.close_p.dropna()
    context.rsi = context.close_p.apply(talib.RSI, timeperiod=12).iloc[-1]
    
    for stock in context.close_p.columns:
        trend = context.trend[stock].values
        close_p = context.close_p[stock].values
        high_p = context.high_p[stock].values
        low_p = context.low_p[stock].values
        rows = len(context.close_p.index)
        for i in xrange(1,rows):
            if close_p[i] > high_p[i-1]:
                trend[i] = 1
            elif close_p[i] < low_p[i-1]:
                trend[i] = -1
            else:
                trend[i] = 0
                
            
    
    #print 'print from before_trading_start'
    print context.trend.tail(2)
    print context.close_p.tail(2)

# Will be called on every trade event for the securities you specify. 
def handle_data(context, data):
    todays_date = get_datetime().date()
    
    if context.sell_orders:
        for stock, _ in context.sell_orders.items():
            order = get_order(context.sell_orders[stock])
            if (order is not None) and (order.status == 1):
                #print 'Sold {amt} shares of {name}'.format(name=stock.symbol, amt=order.filled)
                if stock.symbol in context.open_positions:
                    del context.open_positions[stock.symbol]
                if stock.symbol in context.tgt_price:
                    del context.tgt_price[stock.symbol]
                
                post_sell(context, stock)
                #print str(context.buy_position_r[stock].tail(2)) + str(stock)
                del context.sell_orders[stock]
                
    
    if context.order_main:
        #print 'entering loop'
        for stock, _ in context.order_main.items():
            order = get_order(context.order_main[stock])
            if (order is not None) and  (order.status == 1):
                #print 'Bought {amt} shares of {name}'.format(name=stock.symbol, amt=order.filled)                
                if stock.symbol in context.open_positions:
                    context.open_positions[stock.symbol] += 1
                else:
                    context.open_positions[stock.symbol] = 1
                #print str(context.buy_position_r[stock].tail(2)) + str(stock)
                del context.order_main[stock]
    
    if todays_date == context.date:
        return
    context.date = todays_date
    context.i = context.i + 1  
    
    context.close_p = history(50, '1d', 'close_price')
    context.high_p = history(50, '1d', 'high')
    context.low_p = history(50, '1d', 'low')
    """
    if context.trend is not None:
        print 'print from handle_data'
        print context.trend.tail(2)
        print context.close_p.tail(2)
    """
        


def close_all_open_orders(context,data): 
    if context.i > 1:
        orders = get_open_orders()  
        if orders:  
            for pos in orders:  
                for order in get_open_orders(pos):
                    #message = 'Canceling order for {amount} shares in {stock}'  
                    #message = message.format(amount=order.amount, stock=str(order.sid))  
                    #log.debug(message)  
                    cancel_order(order)
                
def order_at_open(context,data):
    
    if context.i > 1:
        context.order_main = {}
        context.sell_orders = {}
        positions = context.portfolio.positions
        for pos in positions:
            this_position = context.portfolio.positions[pos]
            pos_name = pos.symbol
            
            if (pos_name not in context.tgt_price) :
                context.tgt_price[pos_name] = this_position.cost_basis + (context.high_p[pos][-2]  - context.low_p[pos][-2])/2
            else:
                context.tgt_price[pos_name] = min(context.tgt_price[pos_name], this_position.cost_basis + (context.high_p[pos][-2]  - context.low_p[pos][-2])/2)
                
            if pos in get_open_sell_orders():
                continue
            
            if (context.trend[pos][-1] == -1):# or context.sell[pos][-1]:
                context.sell_orders[pos] = order_target(pos, 0)
            elif pd.notnull(context.tgt_price[pos_name]): 
                context.sell_orders[pos] = order_target(pos,0, style=LimitOrder(context.tgt_price[pos_name]))
                
        for stock in data:
            if stock in get_open_buy_orders():
                continue
            if (stock in context.trend.columns) and (context.trend[stock][-1] == 1) and (context.trend[stock][-2] == -1) and context.rsi is not None and (context.rsi[stock] >60 ):
                if (stock.symbol not in context.open_positions):
                    print 'order sending: ' + str(context.close_p[stock][-2])
                    context.order_main[stock] = order_target_percent(stock, 0.05)
                    #context.order_main[stock] = order_target_percent(stock, 0.05, style=LimitOrder(context.high_p[stock][-2] ))
                
    
 

def post_sell(context, stock):
        pass
    
def get_open_buy_orders():
    buy_orders = {}
    if get_open_orders():
        for stock in get_open_orders():
            order_list = []
            if get_open_orders(stock):
                for order_id in get_open_orders(stock):
                    if order_id.amount > 0:
                        order_list.append(order_id)
                if len(order_list) > 0:
                    buy_orders[stock] = order_list
    return buy_orders

def get_open_sell_orders():
    sell_orders = {}
    if get_open_orders():
        for stock in get_open_orders():
            order_list = []
            if get_open_orders(stock):
                for order_id in get_open_orders(stock):
                    if order_id.amount < 0:
                        order_list.append(order_id)
                if len(order_list) > 0:
                    sell_orders[stock] = order_list
    return sell_orders
There was a runtime error.