Back to Community
Exiting a position based on time held

I am having some issues on finding a way to exit a position after it is open for X minutes. Perhaps someone has a good solution to this? Currently I convert the time to minutes by:

exchange_time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern')  
t = exchange_time.minute+exchange_time.hour*60  

I store the minute the position is opened and if current t is greater than X minutes I will exit. some positions were remaining open though, I added a line to print t at every minute bar and got this:
2011-01-05PRINT 803
2011-01-05PRINT 804
2011-01-05PRINT 3289
2011-01-05PRINT 805
2011-01-05PRINT 806
2011-01-05PRINT 807
Every so often there is a huge jump in t which should just be the time converted to minutes. So when I happen to open a position when t spikes, it will never close. Does anyone know why this is happening?

2 responses

Will this work for you?

import pandas as pd  
from datetime import timedelta

def initialize(context):  
    context.stock = sid(8554)  
def handle_data(context, data):  
    exchange_time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern')  
    plus_one_hour = exchange_time + timedelta(hours=1)  
    print "Current Time {} |\t Plus 1 Hour: {}".format(exchange_time, plus_one_hour)  

Yeah never used timedelta before, seems like it should provide a good work around