Should variables be declared outside or inside of initialize?

Back

changes = None

def Initialize(self):
pass

or

def Initialize(self):
self.changes = None

 

Update Backtest







 
0

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.


This is more of a programming question but constant values that don't change over the course of execution should be outside of Initialize() (a class variable), while variables that will change should be inside Initialize() (an instance variable).

For example:

FREE_CASH = 0.2
MAX_POSITIONS = 10
MIN_VOLUME = 1000000
MIN_TIME_IN_UNIVERSE = 200

def Initialize(self):
self.SetTimeZone("America/New_York")
self.SetBrokerageModel(BrokerageName.AlphaStreams)

self.SetStartDate(2015, 1, 1)
self.SetCash(100000)

self.UniverseSettings.Resolution = Resolution.Hour
self.UniverseSettings.MinimumTimeInUniverse = Km.MIN_TIME_IN_UNIVERSE
self.AddUniverse(self.UniverseSelection)

self.Settings.FreePortfolioValuePercentage = Km.FREE_CASH
self.universe = {} # contains all tracked securities in the universe

You can see how MIN_VOLUME and MIN_TIME_IN_UNIVERSE are variables that won't change in execution, while self.universe does.

Here is a better explanation.

2

Update Backtest





0

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.


Loading...

This discussion is closed