Can someone help me?
I built a base code that filters many stocks whose turnover is above their origin, and buys them according to additional conditions in on data.
And there is some error in adding the stocks in the universe into the array self.activeStocks:
class WellDressedSkyBlueSardine(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2022, 1, 1)
self.SetEndDate(2023, 1, 1)
self.SetCash(10000)
self.rebalanceTime = datetime.min
self.activeStocks = set()
self.AddUniverse(self.CoarseFilterFunction)
self.UniverseSettings.Resolution = Resolution.Daily
self.portfolioTargets = []
self.stateData = { }
def CoarseFilterFunction(self, coarse: List[CoarseFundamental]) -> List[Symbol]:
if self.Time<= self.rebalanceTime:
return self.Universe.Unchanged
self.rebalanceTime = self.Time + timedelta(hours=2.9)
for c in coarse:
if c.Symbol not in self.stateData:
self.stateData[c.Symbol] = SelectionData(c.Symbol, 30)
avg = self.stateData[c.Symbol]
avg.update(c.EndTime, c.AdjustedPrice, c.DollarVolume)
# filter the values of selectionData(sd) above SMA
values = [sd for sd in self.stateData.values() if sd.volume > sd.sma.Current.Value and sd.volume_ratio > 0]
# sort sd by the largest % jump in volume.
values.sort(key=lambda sd: sd.volume_ratio, reverse= True)
entering_symbols = [sd.symbol for sd in values[:10]]
self.Debug("Entering symbols: " + ", ".join(str(symbol) for symbol in entering_symbols))
return entering_symbols
#def FineFilter(self, fine):
# # Sort symbols by price from lowest to highest
# sorted_symbols = sorted(fine, key=lambda f: f.Price, reverse=True)
# Return the symbol objects
# return [f.Symbol for f in sorted_symbols]
def OnSecuritiesChanged(self, changes):
for security in changes.AddedSecurities:
self.activeStocks.add(security.Symbol)
self.Debug("added to self.activeStocks" +str(security.Symbol))
self.Debug("in activeStocks"+ str(self.activeStocks))
# Adjust targets if universe has changed
self.portfolioTargets = [PortfolioTarget(symbol, 1/len(self.activeStocks))
for symbol in self.activeStocks]
self.Debug("in portfolioTargets"+ str(self.portfolioTargets))
The first and second debug line print a lot of shares
But the last two debug lines print empty arrays.
Why??? It does not make sense?
Mia Alissi
From the code you've provided, it seems like you're trying to add symbols to
self.activeStocks
when they are added to the universe. However, it's not clear whyself.activeStocks
andself.portfolioTargets
are empty when you print them.One possible issue could be the timing of when you're printing these variables. If
OnSecuritiesChanged
is not being called before you printself.activeStocks
andself.portfolioTargets
, they would still be empty.Another potential issue could be related to how you're handling removed securities. If securities are being removed from your universe, you should also remove them from
self.activeStocks
. This can be done in theOnSecuritiesChanged
method. Here's an example of how to do this:This code removes symbols from
self.activeStocks
when they are removed from the universe. If securities are being removed from your universe frequently, this could explain whyself.activeStocks
andself.portfolioTargets
are empty when you print them.If these suggestions don't solve your issue, it would be helpful to have more information about when and how often
OnSecuritiesChanged
is being called, and whether securities are being removed from your universe.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.
Shilo Hadad
Thanks!
I tried as you wrote to use OnSecuritiesChanged
But still it doesn't work...
I am copying the backtest here
This is a very basic form of what I'm trying to do - trade on high trading volume along with a close close to the high.
And it does not work...
Thanks for the comments!
Mia Alissi
Based on the provided code, there are a few potential issues that might be causing the algorithm not to work as expected:
OnEndOfDay
method, you are trying to remove a symbol fromself.RemovedSecurities1
while iterating over it. This can lead to unexpected behavior. Instead, you should create a copy of the set for iteration:OnEndOfDay
method, you are usingsymbol_data
which is not defined in the scope of thefor
loop for removed securities. You should get the data for the symbol first:In the
PriceIsNearHigh
method, you are comparing the close price with 90% of the high price. This means you are only considering prices that are within the top 10% of the day's range. If you want to consider prices that are close to the high, you might want to adjust this threshold.In the
MacdIsPositive
andRsiIsOverbought
methods, you are creating a new indicator each time the method is called. This will reset the indicator and it will not be ready until it has enough data. You should create these indicators in theInitialize
method or in theOnSecuritiesChanged
method when a new security is added, and then just use them in these methods.In the
CoarseFilterFunction
, you are creating a newSelectionData
object for each coarse object, even if it already exists inself.stateData
. This will reset the state data each time the universe selection is performed. You should check if the symbol already exists inself.stateData
and only create a newSelectionData
object if it doesn't.Please note that these are potential issues based on the provided code and the actual issues might be different based on the complete context and the data.
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.
Shilo Hadad
Wow really detailed answer! I appreciate very much.
I will work on it. Thanks!
Mia Alissi
You're welcome, Shilo! I'm glad you found the answer helpful. Don't hesitate to ask if you have any more questions or run into any issues while implementing the changes. Happy coding!
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.
Shilo Hadad
It still seems like nothing is happening
Could it be that the buying and selling should be in ondata and not in endofday?
Mia Alissi
Yes, that could be a potential issue. The
OnEndOfDay
method is called at the end of each trading day, and depending on the market hours of the securities you are trading, it might be too late to place any trades for that day.In the QuantConnect API Reference, it is mentioned that the
OnEndOfDay
method is called at the end of the algorithm day (or multiple times if trading multiple assets).If you want to place trades based on the data of the current day, it would be more appropriate to do this in the
OnData
method, which is called for each new data point.You can move the buying and selling logic from
OnEndOfDay
toOnData
and see if that resolves the issue.Remember to check if the necessary data is available before placing any trades. For example, you can use
if symbol in data:
to check if data for a particular symbol is available.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.
Shilo Hadad
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!