What is the most robust way to access the number of days a security has been held? I've been using self.PurchaseDate[stock], as in the code below. The code below works perfect, unless my live algorithm crashes, or I stop it while securities are owned. So then, if I try to launch my algorithm, with securities already owned, it doesn't appear that a value for self.PurchaseDate[stock] exists anymore. Is there a better way to determine the number of days held?

 

for stock in self.stock_list: if self.Portfolio[stock].Invested == True: bought = self.PurchaseDate[stock] time_owned_raw = now - bought days_owned = time_owned_raw.days + 1 #need the +1 to compensate self.do[stock] = days_owned