-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Accessing strategy instance variables after backtest run #294
-
I'd like to access some of the indicators that I'm supplying for a backtest so that I can make custom plots. Using the tutorial example for reference:
from backtesting import Backtest, Strategy
from backtesting.lib import crossover
from backtesting.test import SMA, GOOG
#build strategy object based on abstract class
class SmaCross(Strategy):
n1 = 10
n2 = 20
def init(self):
close = self.data.Close
self.sma1 = self.I(SMA, close, self.n1)
self.sma2 = self.I(SMA, close, self.n2)
def next(self):
if crossover(self.sma1, self.sma2):
self.buy()
elif crossover(self.sma2, self.sma1):
self.sell()
bt = Backtest(GOOG, SmaCross,
cash=10000, commission=.002,
exclusive_orders=True)
output = bt.run()
I'd like to be able to access the SmaCross.sma1
and SmaCross.sma2
array after the backtests completes.
bt._strategy
doesn't seem to be an instance of the strategy:
bt._strategy.sma1
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-9f7e77c45178> in <module>
----> 1 bt._strategy.sma1
AttributeError: type object 'SmaCross' has no attribute 'sma1'
Is there a simple way to access the indicators after the run? One workaround that can work is by making a copy of the indicators as class members (non-instance variables), but that seems messy. Any help would be greatly appreciated.
Beta Was this translation helpful? Give feedback.
All reactions
bt._strategy
doesn't seem to be an instance of the strategy
Where'd you get bt._strategy
? It's stats._strategy
(stats = bt.run()
).
Replies: 1 comment 1 reply
-
bt._strategy
doesn't seem to be an instance of the strategy
Where'd you get bt._strategy
? It's stats._strategy
(stats = bt.run()
).
Beta Was this translation helpful? Give feedback.
All reactions
-
Ah of course, silly me. And to be consistent with the above example, it'd be output._strategy.sma1
. Thanks @kernc.
Beta Was this translation helpful? Give feedback.