Reputation: 949
I've got a function (get_score) that uses variables from other functions(self.__sma) in the same class.
My question: How can I access these variables from the get_score function? (error: global name is not defined).
Also, i heard that using global variables causes a shitstorm(just based from what I read on here). Thanks in advance.
Here is some code:
testlist = ['TREE', 'HAPPY']
Class MyStrategy(strategy.BacktestingStrategy):
def __init__(self, feed, instrument):
super(MyStrategy, self).__init__(feed, 1000)
self.__position = [] #None
self.__instrument = instrument
self.setUseAdjustedValues(True)
self.__prices = feed[instrument].getPriceDataSeries()
self.__sma = ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod)
def get_score(self,banana)
fruit_lover= self.__sma
return fruit_lover + banana
def onBars(self, bars):
for x in bars.getInstruments():
list_large = {}
for y in testlist:
list_large.update({y : self.get_score(5)})
Upvotes: 0
Views: 163
Reputation: 231665
With a copy of your script, and a bunch of stubs, and too many syntax corrections:
testlist = ['TREE', 'HAPPY']
class MyStrategy(): #strategy.BacktestingStrategy): # lowercase class
def __init__(self, feed, instrument):
#super(MyStrategy, self).__init__(feed, 1000)
self.__position = [] #None
self.__instrument = instrument
#self.setUseAdjustedValues(True)
self.__prices = 123 #feed[instrument].getPriceDataSeries()
self.__sma = 100 # ma.SMA(feed[instrument].getPriceDataSeries(), smaPeriod)
def get_score(self,banana): # add :
fruit_lover= self.__sma
return fruit_lover + banana
def onBars(self, bars):
#for x in bars.getInstruments():
list_large = {}
for y in testlist:
list_large.update({y : self.get_score(5)})
self.list_large = list_large # save list_large
s = MyStrategy('feed', 'inst')
print(vars(s)) # look at attributes set in __init__
print(s.get_score(10)) # test get_score by itself
s.onBars('bars') # test onBars
print(s.list_large)
I get the following run:
0009:~/mypy$ python stack40814540.py
{'_MyStrategy__position': [],
'_MyStrategy__instrument': 'inst',
'_MyStrategy__sma': 100,
'_MyStrategy__prices': 123}
110
{'TREE': 105, 'HAPPY': 105}
I have no problem accessing __sma
attribute in the other methods.
Because the name starts with __
(and not ending __
), it is coded as a 'pseudo-private' variable, as can be seen in the vars
display. But that doesn't harm access from another method.
For a beginner I'd suggest skipping that feature, and just use names like self.sma
. Code will be easier to debug.
Make sure you understand my changes; and run some similar tests.
Upvotes: 1