Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Accessing strategy instance variables after backtest run #294

Answered by kernc
zhang-alvin asked this question in Q&A
Discussion options

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.

You must be logged in to vote

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

Comment options

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()).

You must be logged in to vote
1 reply
Comment options

Ah of course, silly me. And to be consistent with the above example, it'd be output._strategy.sma1. Thanks @kernc.

Answer selected by zhang-alvin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /