It's been confirmed that any expando property hung off of the "context" object will be persisted across sessions and across system disruptions (if running in real time). So you could manage another collection, like what Ethan mentioned, to keep track of dates of position opening.
Alternatively, you can use the expando off of the data[stock] object. NOTE: this technique has not been confirmed as persistent by the Quantopian techs.
def initialize(context):
context.ZZZ = symbols("SPY")[0]
def handle_data(context, data):
for stock in data:
if ('OpenDate' not in data[stock]):
order_target_percent(stock, 1.0 / len(data))
data[stock].OpenDate = get_datetime()
data[stock].CountDown = 50
print("{0} opened: {1}".format(
stock.symbol, data[stock].OpenDate))
else:
data[stock].CountDown -= 1
if (data[stock].CountDown <= 0):
order_target_percent(stock, 0.0)
del data[stock].OpenDate
del data[stock].CountDown
print("{0} closed: {1}".format(
stock.symbol, get_datetime()))
if ('CountDown' in data[context.ZZZ]):
record(CountDown = data[context.ZZZ].CountDown)
Note the use of the following expandos that are made available throughout the test:
data[stock].OpenDate = get_datetime()
data[stock].CountDown = 50
Once not needed one would use the del data[stock].OpenDate. to remove it.
And one would use the test if ('OpenDate' not in data[stock]): to determine if the expando existed.