Back to Community
Need help about some points when backtesting US Future algorithm

I did backtestings on US Future algorithm by min bar, i need to check every min data to calculate signals and order,:
what's the timestamp of "data.current_dt" ? Is it the market timestamp or local timestamp?

Thanks...

Clone Algorithm
3
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
import quantopian.algorithm as algo
from quantopian.algorithm import calendars
from quantopian.pipeline import Pipeline   
import datetime
import pandas as pd
import numpy as np

def initialize(context):
    #初始化证券池
    context.future = continuous_future('ES', roll='calendar')
    context.bar_count = 5
    context.mean_width = 10
    context.check_list = [5, 10, 15]#
    context.tick = 0.25
    context.min_count = 0
    context.curr_position = 0
    context.curr_price_sum = 0
    context.curr_price_avg = 0
    
    context.price_curr_close = 0
    context.price_prev_close = 0
    context.price_curr_open = 0
    context.tradeDF = pd.DataFrame()

    #set_commission(us_futures=commission.PerContract(cost=1, exchange_fee=0.85, min_trade_cost=0))
    context.ifTrade = False
    #context.ifOpen = False
    context.ifStop = False
    context.ifClose = False
    context.ifHold = False
    context.Holiday = [datetime.date(2011,7,4), datetime.date(2011,9,5), datetime.date(2012,5,25), datetime.date(2012,5,28)
                      , datetime.date(2012,7,4), datetime.date(2012,11,23), datetime.date(2012,5,28), datetime.date(2012,7,4), datetime.date(2012,11,22), datetime.date(2013,1,21), datetime.date(2013,5,28), datetime.date(2013,12,24), datetime.date(2014,1,20), datetime.date(2014,7,3), datetime.date(2014,9,1), datetime.date(2014, 12, 24), datetime.date(2015,5,25), datetime.date(2017,9,4), datetime.date(2018,7,4)]
    
def handle_data(context, data):
    #curr_time = data.current_dt
    #print curr_time
    if (data.current_dt.date() < datetime.date(2011, 3, 14))|((data.current_dt.date() >= datetime.date(2011, 11, 7))  & (data.current_dt.date() < datetime.date(2012, 3, 12)))|((data.current_dt.date() >= datetime.date(2012, 11, 5))  & (data.current_dt.date() < datetime.date(2013, 3, 11)))|((data.current_dt.date() >= datetime.date(2013, 11, 4))  & (data.current_dt.date() < datetime.date(2014, 3, 10)))|((data.current_dt.date() >= datetime.date(2014, 11, 3))  & (data.current_dt.date() < datetime.date(2015, 3, 9)))|((data.current_dt.date() >= datetime.date(2015, 11, 2))  & (data.current_dt.date() < datetime.date(2016, 3, 14)))|((data.current_dt.date() >= datetime.date(2016, 11, 7))  & (data.current_dt.date() < datetime.date(2017, 3, 13)))|((data.current_dt.date() >= datetime.date(2017, 11, 6))  & (data.current_dt.date() < datetime.date(2018, 3, 12))):   
        tz = 6
    else:
        tz = 5
    curr_time = data.current_dt - datetime.timedelta(hours=tz)
    
    #daily init...
    if curr_time.time() == datetime.time(8,30,0): 
        #print context.portfolio.positions
        #open_time     
        context.trade_contract = data.current(context.future, 'contract')      
        context.tradingDay = curr_time.date()   
        context.price_prev_close = context.price_curr_close        
        price0 = data.history(context.future, "open", 1, '1m')
        context.price_curr_open = price0[-1]
        context.min_count = 1
        context.curr_position = 0
        context.curr_price_sum = 0
        #print context.portfolio.positions
        
        #print abs(context.price_curr_open - context.price_prev_close)
        #print context.price_prev_close
        if curr_time.date() not in context.Holiday:
            if (context.price_prev_close != 0) & (abs(context.price_curr_open - context.price_prev_close) <= 25 * context.tick):
                context.ifTrade = True
        else:
            context.ifTrade = False
        #print context.ifTrade  
    if curr_time.time() > datetime.time(8,30,0): 
        context.min_count += 1
    
    if curr_time.time() == datetime.time(15,0,0):    #print curr_time
        price1 = data.history(context.future, "close", 1, '1m')
        context.price_curr_close = price1[-1]
        #print price1
        if  np.isnan(context.price_curr_close):
            price1d =  data.history(context.future, "close",1,'1d')
            context.price_curr_close = price1d[-1]
    

    
    
    if context.ifTrade:
        price_history = data.history(context.future, 
                                     fields=['price', 'low' , 'high'],
                                     bar_count=context.min_count,
                                     frequency="1m")
        price_std = price_history.price.iloc[-context.mean_width:].std()
        price_mean = price_history.price.iloc[-context.mean_width:].mean()
        price_price = price_history.price.iloc[-1]
        price_low = price_history.low.min()
        price_high = price_history.high.max()
        
        if context.min_count in context.check_list:
            if context.min_count == context.check_list[0]:
                bar_count = context.bar_count
            else:
                bar_count = context.bar_count + 1               
            price_history = data.history(context.future, 
                                     fields=["close","high","low"],
                                     bar_count=bar_count,
                                     frequency="1m") 
            #print price_history
            prev_close = price_history['close'].iloc[0]
            curr_close = price_history['close'].iloc[-1]
            prev_high = price_history['high'].iloc[0]
            curr_high = price_history['high'].iloc[-1]
            prev_low = price_history['low'].iloc[0]
            curr_low = price_history['low'].iloc[-1]
            #log.info('%s pClose: %d; cClose: %d; pHigh: %d; cHigh:%d'%(curr_time, prev_close, curr_close, prev_high, curr_high))
            if (curr_close > prev_close) & (curr_high > prev_high) & (context.curr_position >= 0):       
                context.curr_position += 1
                order_target(context.trade_contract, context.curr_position)
                context.curr_price_sum += curr_close
                #context.curr_price_sum += context.portfolio.positions[context.trade_contract]['last_sale_price']
                log.info('%s buylong %d contracts; curr_position is %d, cprice is %d, pprice is %d'%(curr_time, 1, context.curr_position, curr_close, context.portfolio.positions[context.trade_contract]['last_sale_price']))
            elif (curr_close < prev_close) & (curr_low < prev_low) & (context.curr_position <= 0): 
                context.curr_position -= 1                
                order_target(context.trade_contract, context.curr_position)               
                log.info('%s buyshort %d contracts; curr_position is %d, cprice is %d, pprice is %d'%(curr_time, -1, context.curr_position, curr_close, context.portfolio.positions[context.trade_contract]['last_sale_price']))
                #print '.......',get_open_orders() 
                #print context.curr_position
                context.curr_price_sum += curr_close
                #context.curr_price_sum += context.portfolio.positions[context.trade_contract]['last_sale_price']   
            if (context.curr_position != 0) & (context.min_count == context.check_list[-1]):    
                context.curr_price_avg = context.curr_price_sum / abs(context.curr_position)
                log.info('avgPrice = %d'%context.curr_price_avg)    
           
        if (context.min_count > 15) & (context.min_count < 390) & (context.curr_position != 0):
            if ((context.curr_position > 0) & (price_price < price_low - context.tick)) | ((context.curr_position < 0) & (price_price > price_high - context.tick)):
                log.info('%s stoploss %d contracts; curr_position is %d' % (curr_time,  -context.curr_position, 0))
                order_target(context.trade_contract, 0)
                context.curr_position = 0
                context.ifTrade = False

        if (context.min_count == 390) & (context.curr_position != 0):
            #print "current time : ", data.current_dt
            amount = context.curr_position
            context.curr_position = 0
            order_target(context.trade_contract, 0)
            #print context.portfolio.positions
            #context.ifTrade = False
            #order_target(trade_contract, 0)
            #print "amount-{}".format(o), get_order(o).amount
            #log.info('dayend close %s %d shares'%(trade_contract, context.curr_position))
            log.info('%s dayClose %d contracts; curr_position is %d'%(curr_time, amount, 0))
            context.ifTrade = False


def get_tradeDF(context, data):
    new_tradeDF = pd.DataFrame([[context.tradingDay, 
                                 context.trade_contract,
                                 context.Amount,
                                 context.Price,
                                 context.Direction, 
                                 context.offSetFlag]], 
                               columns = 
                               ['Date', 'Contract', 'Volume', 'Price', 'Direction', 'OffSetFlag'])
    return context.tradeDF.append(new_tradeDF)
There was a runtime error.