Hello community,
I am starting with quantopian and I would really appreciate some help. I am working on improving this algorithm that buys the best 4 Sector ETFs each month, but when the SPY<MA200_SPY (bear market) it buys a bond instead and no ETFs. In this sense, I can't seem to find out why if one month I have a bond, and next I need 4 ETFs (and therefore I need to sell the bond), it doesn't actually sell it (that's why I have 5 positions, and double leverage). Any one could help me find out what's the problem with the restrictions below?
Furthemore, I have tried to tell the algorithm not to sell an ETF I already have, if next month it keeps being in the top 4 (I don't want to sell the same thing I need to immediately buy).
for stock in context.portfolio.positions:
#If the SP>SP_MA200
if spy_ma1>spy_ma200:
#If I have the bond in my portfolio, sell the bond
if sid(23921) in context.portfolio.positions:
order_target_percent(sid(23921), 0)
#If I don't have the bond (because I have ETFs)
else:
#If the ETFs on my portfolio are not on the Top 4 this month, sell the ETFs I have
if stock not in context.longs:
order_target_percent(stock, 0)
#If SP<SP_MA200
else:
#If we don't have the bond in the portfolio, sell the ETFs
if context.shy not in context.portfolio.positions:
order_target_percent(stock, 0)