Hi there, because my account does not have margin, I have to rebalance my account by sell first and buy in 2 days later.
So I use schedule_function() to run two jobs: clear_position and buyin_position.
There is another update job where context.STOCKS and context.bond_weights will be updated.
If context.bond_weights is non-zero, that means I am holding bonds.
Sample codes:
def clear_position(context, data):
# Sell stocks if they are not hold anymore
sell_list = []
for s in context.portfolio.positions:
s = str(s.symbol)
if s not in context.STOCKS:
sell_list.append(s)
# Sell bonds if they are not hold anymore
for s in context.BONDS:
if s in context.portfolio.positions and context.bond_weights == 0:
sell_list.append(str(s.symbol))
if len(sell_list) > 0:
log.info("Sell:" + str(sell_list))
weights = pd.Series(index=sell_list, data=0.0)
weights = opt.TargetWeights(weights)
order_optimal_portfolio(
objective = weights,
constraints = []
)
else:
log.info("Hold current portfolio")
def buyin_position(context, data):
"""
Execute trades using optimize.
Expects securities (stocks and bonds) with weights to be in context.weights
"""
# Create a single series from our stock and bond weights
total_weights = pd.concat([context.stock_weights, context.bond_weights])
# Create a TargetWeights objective
target_weights = opt.TargetWeights(total_weights)
# Execute the order_optimal_portfolio method with above objective and any constraint
order_optimal_portfolio(
objective = target_weights,
constraints = []
)
log.info( "Buy in: " + str([s for s in context.STOCKS]) )
record(stocks=context.stock_weights.sum(), bonds=context.bond_weights.sum())
The problem is when I call
weights = pd.Series(index=sell_list, data=0.0)
weights = opt.TargetWeights(weights)
order_optimal_portfolio(
objective = weights,
constraints = []
)
All my portfolios are sold, however, I just want to sell the ones in "sell_list". Please help, thanks!!