Accessing data after finished run
algoguy235 last edited by
Inside my strategy, I'm doing some algabraic caluclations and I want to be able to access those as arrays after my backtest run is finished.
I tried creating an SMA(var ,period=1) but I still don't know how to access the data.
I assuming it's somewhere in strategy.* but where? Any help?
ab_trader last edited by
You run your strategy as
result = cerebro.run()
resultobject contains everything.
Reference Returning the results section in Cerebro
algoguy235 last edited by
I've read the page though it's not clear to me to get access to the data. The documentation says do it like so.
thestrats = cerebro.run(tradehistory=True) thestrat = thestrats
And then I've figured out how to get price data, trades, and orders
# raw data open = thestrat.data_open.array high = thestrat.data_high.array ... # trades trades = [str(trade).splitlines() for trade in list(thestrat._trades.values())] # orders orders = [str(order).splitlines() for order in thestrat._orders]
But where I'm stuck now is how can I do this same thing with indicators?
Søren Pallesen last edited by
@algoguy235 did have any luck figuring this out?
Whereas orders are created by the system, indicators are created by end users. Something that could be my own code
class MyStrategy(bt.Strategy): def __init__(self): self.my_smas = [bt.ind.SMA(period=x) for x in range(5, 30, 5)]
Accessing the indicators later is a matter of getting
thestratas shown above and accessing the
my_smasattribute (a list containing several Simple Moving Averages)
algoguy235 last edited by algoguy235
class MyStrategy(bt.Strategy): def __init__(self): self.__special_array_for_later = [[None, 0, 0, 0,...]] #note nested brackets def next(self): if some_condition: do_some_special_calculations() def do_some_special_calculations(self) self.__special_array_for_later.append([current_dt, calc1, calc2, calc3, ...])
Then when it's all over I do this little move:
special_array = thestrat._MyStrategy__special_array_for_later
it turns out that
thestrat._MyStrategy*has a bunch of tricks for debugging and other internals.
From there I make my dataframe and do all the things I need.
It seems to be working perfectly for the backtest environment. Not sure what's gonna happen when this all switches over to live 😬 but working good so far 👍🏼
Another thing to note. I do my calculate AND append work in a separate function that gets called when some_condition is true. I do that because I don't want to weigh down my next(self) function with unnecessary code. Then when the run is over, I line up the special_array with my other rawdata and trades arrays using dt selections in pandas - during the data pre-processing and analysis steps. I don't know the exact overhead I'm saving by doing this. If I were to use indicators, they would calculate every cycle, but would be easier to line up after. I opted to save the overhead, and do the alignment later. But I imagine both would work.