Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Is there anyway I could sell any buys exactly after 2 years?

I need some help with a technique that lets me sell exactly after 2 years of holding it. But I didn't find any simple way to do this. I am buying different stocks at different dates. I can sell any of the buys when a conditions are met before the 2 years. Then I need to buy a new one to fill the empty seat. So each stocks will have different buy dates. I need some neat way to store the buy date for each different securities so that if certain conditions never met, I can still sell it after 2 years.

I know I got to add something around code line 191 and after...

Thank you

6 responses

I am getting sense that there is no short cut to this. Is a dataframe work in order to track initial purchase date an answers?

I have asked them to add some dates to the position objects, but they've said it's quite difficult...

I've done some fixed buy-sell timeframe work by just creating a dict object in initialization:

def initialize(context):  
   [...]  
  context.maxdays = 14    # Max number of calendar days to hold a trade  
  context.tradedates = {}

Then, I created "buy" and "sell" functions to populate / de-populate the dict and call those in place of "order_target_percent()":

def buy(context, sid, pct):  
  if sid not in get_open_orders():  
    order_target_percent(sid, pct)  
    if sid not in context.tradedates:  # Don't update if we already have a position  
      context.tradedates[sid] = get_datetime()

def sell(context, sid):  
  if sid not in get_open_orders():  
    order_target_percent(sid, 0)  
    del(context.tradedates[sid])

Then, at regular intervals, just do:

for sid, tradedate in context.tradedates.items():  
  if (get_datetime() - tradedate).days > context.max_days:  
    sell(context, sid)  

Yeah I think that is basically required, with the downside that if you restart your algorithm, you lose track of how long you've owned everything. If the holding period is 2 years, that's a hefty limitation...

K.C. Budd,
Really Appreciated!

I don't understand how the IB thing works but my current generating engine copes with this by running a back test for say the past two years so as to populate the variables necessary and then spitting out orders. So that starting and then having to restart is not a problem.

Zipline works differently?