Accessing strategy results, orders and trades
I read the docs on returning strategy results. But I can't find much info on the strategy instance object, or its attributes.
strats = cerebro.run(tradehistory=True) print(type(strats))
So I first tried something like:
But I get the error:
AttributeError: 'Lines_LineSeries_LineIterator_DataAccessor_Strateg' object has no attribute 'trades
Then I saw an example, and tried to print orders via:
orders = [str(order).splitlines() for order in strats._orders] if len(orders) >0: print(orders)
And thats working. But trades is not:
Ive trade using both:
trades = [str(trade).splitlines() for trade in list(strats._trades.values())]
trades = [str(trade).splitlines() for trade in strats._trades]
But when I try and print trades using the first one I get:
trades = [str(trade).splitlines() for trade in list(strats._trades.values())] IndexError: list index out of range
And when I try the second I get:
[['<__main__.backtest.<locals>.StratData object at 0x7f07b681ee80>']]
So two questions:
How can I access/print the trades?
Can I just set my own dictionary in the strategy and return it? If so, can someone show sample code of how you can return your own dictionary from a strategy.
I know when people ask this type of question someone usually responds with the return the results doc page, but I've read it and all it says is:
result = cerebro.run(**kwargs) The format of result returned by run will vary depending on whether optimization is used (a strategy was added with optstrategy): All strategies added with addstrategy result will be a list of the instances run during the backtesting
I can't find any information on what the instance objects or their attributes contain, so I don't know what to try and access.
run-out last edited by
@protrasol I think my best recommendation for you would be to use your debugging tool. Just put a stop right after
cerebro.run()is returned to
strat, and you can explore everything that is inside the
stratobject. From there you can plan how to extract data.
Which IDE are you using? Pycharm and VSCode are free and have great debuggers.
Coding without this technique is like driving with a blindfold on. You are constantly trying to figure out what's happening.
@run-out thank you, that makes sense. Let me give that a shot, Im using pycharm, and I need to learn how to use the debugger better anyway.
run-out last edited by
@protrasol I use pycharm as well and can see everything inside the objects. You will like it!
@run-out Ugg, Im running my code remotely, and pycharm open-source doesn't support remote env. Oh well, I can work on getting the code working from local desktop.