For closing a few individual positions or modifying them or even adding, some examples where I examined orders to make sure this works as intended. Stemming from here with some comments worth seeing in Dan Whitnable and Karl contributions and one involving a leverage condition.
Frozen() says don't touch these, allowing a select number of other positions to be changed.
Simplified condensed version examples.
1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
to_close = [] # securities to be changed
ids = order_optimal_portfolio(
objective = opt.TargetWeights(
pd.Series(0, index = to_close) # the 0 means close them
),
constraints = [
opt.Frozen(
set(context.portfolio.positions.keys()) - set(to_close)
)
]
)
for i in ids:
o = get_order(i) # order object
s = o.sid
log.info('{} {} {}'.format(s.symbol, o.filled, o.amount))
2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
weight_new = {} # populate these
order_optimal_portfolio(
objective = opt.TargetWeights(weight_new),
constraints = [
opt.MaxGrossExposure(MAX_LV),
opt.Frozen(set(context.portfolio.positions.keys()) - set(weight_new.keys()))]
)
3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
weight_new = {} # populate this
try:
order_optimal_portfolio(
objective = opt.TargetWeights(weight_new),
constraints = [
opt.MaxGrossExposure(MAX_LV),
opt.Frozen(set(context.portfolio.positions.keys()) - set(weight_new.keys()))]
)
except Exception as e:
frozen = set(c.portfolio.positions.keys()) - set(weight_new.keys())
print str([s.symbol for s in frozen])
print e
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The latter with try except is because I ran into one instance with a mysterious error, the except can provide a bit of info (you decide what to log), it avoids a crash, allows the backtest to keep running.