Hi there,
I am trying to get my algo to liquidate its equity holdings when the 20 day moving average goes below the 150 day moving average and then buy and hold bonds during that time.
However, my algorithm continuously buys and sells the bonds during this time. How would I make it liquidate the equities and then buy and hold bonds?
def OnData(self, data):
if self.sma20.Current.Value >= self.sma150.Current.Value:
if self.flag3 > 0:
if self.flag2 == 1:
self.flag2 = 0
if self._changes == None: return
for security in self._changes.RemovedSecurities:
if security.Invested:
self.Liquidate(security.Symbol)
for security in self._changes.AddedSecurities:
self.SetHoldings(security.Symbol, 0.8/float(len(self._changes.AddedSecurities)))
self._changes = None
else:
self.Liquidate()
self.SetHoldings("TLT", 1.0 )
Alexandre Catarino
You could only liquidate the positions if TLT is not invested:
def OnData(self, data): if self.sma20.Current.Value >= self.sma150.Current.Value: if self.flag3 > 0: if self.flag2 == 1: self.flag2 = 0 if self._changes == None: return for security in self._changes.RemovedSecurities: if security.Invested: self.Liquidate(security.Symbol) # If new securities were added, liquidate TLT # before allocate on them count = len(self._changes.AddedSecurities) if count > 0: self.Liquidate("TLT") for security in self._changes.AddedSecurities: self.SetHoldings(security.Symbol, 0.8/count) self._changes = None # If sma20 < sma15 and TLT is not invested, liquidate all and buy TLT elif not self.Portfolio["TLT"].Invested: self.Liquidate() self.SetHoldings("TLT", 1.0 )
Since we don't have the whole algorithm, we couldn't test this implementation. If it doesn't work as expected, please share an algorithm (use the attach backtest button below) that shows the issue you are experiencing.
This procedure helps us, the community, to answer your questions quickly and effectively.
Alex Haseldine
Thanks a lot!
Alex Haseldine
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!