Hi all,
Quite new here and I'm struggling to understand how can I keep the weight of yesterday for a security.
My idea is to buy when the signal happens 1% of portfolio and then to let the weight run without changing the weight everyday.
I have the following code, but what it does it either buys everything or sells everything. But what I want is to always buy 1% when there is a new one in my universe and keep the others the same.
weights = {}
# If there are securities in our longs
if context.longs:
long_weight = 0.01
else:
return weights
# Exit positions in our portfolio if they are not
# in our longs
for security in context.portfolio.positions:
if security not in context.longs and data.can_trade(security):
weights[security] = 0
#Buy securities when they are not in portfolio already, but they are in our longs
for security in context.longs:
if security not in context.portfolio.positions and data.can_trade(security) :
weights[security] = long_weight
return weights
def before_trading_start(context, data):
# Gets our pipeline output every day.
pipe_results = pipeline_output('my_pipeline')
# Go long in securities for which the 'longs' value is True,
# and check if they can be traded.
context.longs = []
for sec in pipe_results[pipe_results['longs']].index.tolist():
if data.can_trade(sec):
context.longs.append(sec)
def my_rebalance(context, data):
# Calculate target weights to rebalance
target_weights = compute_target_weights(context, data)
# If we have target weights, rebalance our portfolio
if target_weights:
order_optimal_portfolio(
objective=opt.TargetWeights(target_weights),
constraints=[constrain_gross_leverage,],
)