Hello,
I am new to QuantConnect, I am trying to migrate a Quantopian Project. However, I am having difficulty accessing data object from other classes.
I am using the Algorithm Framework. I have a complicated indicator(s) which is in a class that does not extend any other class, let’s called it Class X. The reason for this, is that I want to save a lot of class variables per security and keep them updated.
So, I create an instance of this Class X per security so the AlphaModel could check the logic by accessing the class variables for each security, and then decide to return insights or not.
The Problem: I can not pass the data Object appropriately, so I can access it in Class X
Please see attached
Any hint is highly appreciated
+ Expand
# region imports
from AlgorithmImports import *
# endregion
class SwimmingBlueTermite(QCAlgorithm):
def Initialize(self):
self.SetStartDate(2020, 1, 1) # Set Start Date
self.SetEndDate(2022,1,1)
self.SetCash(100000) # Set Strategy Cash
self.num_coarse = 500
self.__numberOfSymbolsFine = 4
self.UniverseSettings.Resolution = Resolution.Daily
self.AddUniverse(self.CoarseSelectionFunction, self.FineSelectionFunction)
self.AddAlpha(TestAlphaModel())
# Portfolio construction model
self.SetPortfolioConstruction(EqualWeightingPortfolioConstructionModel())
# Risk model
self.SetRiskManagement(NullRiskManagementModel())
# Execution model
self.SetExecution(ImmediateExecutionModel())
# set a warm-up period to initialize the indicator
self.SetWarmUp(timedelta(60))
# Take 500 stocks worth more than $10, with more than $10M daily
def CoarseSelectionFunction(self, coarse):
sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True)
filtered = [ x.Symbol for x in sortedByDollarVolume
if x.Price > 10 and x.DollarVolume > 10000000 ]
return filtered[:500]
# sort the data by P/E ratio and take the top 'NumberOfSymbolsFine'
def FineSelectionFunction(self, fine):
# sort descending by P/E ratio
sortedByPeRatio = sorted(fine, key=lambda x: x.ValuationRatios.PERatio, reverse=True)
# take the top entries from our sorted collection
return [ x.Symbol for x in sortedByPeRatio[:self.__numberOfSymbolsFine] ]
def OnSecuritiesChanges(self, changes):
# Remove security
for security in changes.RemovedSecurities:
self.ActiveSecurities.remove(security)
# Add security
for security in changes.AddedSecurities:
if security not in self.ActiveSecurities:
self.ActiveSecurities.append(security)
class TestAlphaModel(AlphaModel):
def __init__(self):
self.InstancePerSecurity = []
self.ListComprehensionCount = 0
def Update(self, algorithm, data):
if (self.ListComprehensionCount == 0):
self.InstancePerSecurity = [ClassX(security, data) for security in algorithm.ActiveSecurities.Keys]
self.ListComprehensionCount += 1
insights = []
for instance in self.InstancePerSecurity:
instance.Run()
class ClassX():
def __init__(self, security, data):
self.security = security
self.data = data
def Run(self):
# Returns Error "Runtime Error: type(s) expected"
if self.data.Bars.ContainsKey[self.security]:
pass
Adam W
I'm a bit confused about what the logic of this code should be.
This part here:
says that when the first datapoint is received, save the data (TradeBar or QuoteBar) as an attribute in the ClassX instances.
Wouldn't you want to run the check (the stuff in .Run()) every time data is received? In which case simply put the data argument into the .Run method instead of saving it as an attribute.
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.
Adham Al-Harazi
Thank you, Fred & Adam.
Yes, Fred. The data is best passed during the update method not as an attribute. The original code did that, but trying many ways to solve the problem landed me to that implementation. Thanks again.
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.
Adham Al-Harazi
Thank you, Fred & Adam.
Yes, Adam. The data is best passed during the update method of the Alpha to the Run method of Class X not as an attribute.
The original code did that, but trying many ways to solve the problem landed me to that implementation. Thanks again.
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!