My fault. I misunderstood your original intent. I was thinking you wanted to close positions after a maximum of n days. However, a position could be closed earlier if it fell out of the selection logic. From what I believe you are saying you want sort of the opposite. Keep positions open for a minimum of n days. Is that correct?
If so, just freeze any securities held less than n days. Do this by creating a Frozen constraint and add that to your ordering method. Something like this.
# Freeze any securities held less than dth days
dth = 10
held_days_series = pd.Series(context.days_elapsed)
securities_to_hold_list = held_days_series[held_days_series < dth].index.tolist()
freeze_securities_to_hold = opt.Frozen(securities_to_hold_list)
securities_to_trade_with_weights = pd.Series(securities_to_trade_dict)
weight_objective = opt.TargetWeights(securities_to_trade_with_weights)
order_optimal_portfolio(objective = weight_objective, constraints =[freeze_securities_to_hold])
Attached is a backtest showing this. Check the logs and you will see that securities are always held 9 days (ie held if less than 10 days).
A separate issue you will have is determining weights. The current method doesn't take into account those securities being held. Good luck.