output results to json file
-
Is it possible to somehow output all results from backtrader into a json file or similar such that i can visualize it in my own program?
-
@bkak Yes. The analyzer results are included in the strategy object that is returned at the end of the backest. You can take those results and manipulate them as you see fit.
Here's an example of obtaining the results of the
cash_market
analyzer.results = cerebro.run() print(results[0].analyzers.getbyname("cash_market").get_analysis())
Here's the whole code converting the dictionary to json.
import backtrader as bt import json class CashMarket(bt.analyzers.Analyzer): """ Analyzer returning cash and market values """ def create_analysis(self): self.rets = {} self.vals = 0.0 def notify_cashvalue(self, cash, value): self.vals = (self.strategy.datetime.datetime().strftime("%Y-%m-%d"), cash, value) self.rets[len(self)] = self.vals def get_analysis(self): return self.rets class Strategy(bt.Strategy): def __init__(self): self.rsi = bt.ind.RSI(period=14) def next(self): if not self.position: if self.rsi <= 35: self.buy() elif self.rsi >= 65: self.close() if __name__ == "__main__": cerebro = bt.Cerebro() data = bt.feeds.GenericCSVData( dataname="data/2006-day-001.txt", dtformat=("%Y-%m-%d"), timeframe=bt.TimeFrame.Days, compression=1, ) cerebro.adddata(data) cerebro.addstrategy(Strategy) cerebro.addanalyzer(CashMarket, _name = "cash_market") # Execute results = cerebro.run() # Dictionary dictionary = results[0].analyzers.getbyname("cash_market").get_analysis() json_object = json.dumps(dictionary, indent=4) print(json_object)
-
@run-out said in output results to json file:
import backtrader as bt
import jsonclass CashMarket(bt.analyzers.Analyzer):
"""
Analyzer returning cash and market values
"""def create_analysis(self): self.rets = {} self.vals = 0.0 def notify_cashvalue(self, cash, value): self.vals = (self.strategy.datetime.datetime().strftime("%Y-%m-%d"), cash, value) self.rets[len(self)] = self.vals def get_analysis(self): return self.rets
class Strategy(bt.Strategy):
def __init__(self): self.rsi = bt.ind.RSI(period=14) def next(self): if not self.position: if self.rsi <= 35: self.buy() elif self.rsi >= 65: self.close()
if name == "main":
cerebro = bt.Cerebro() data = bt.feeds.GenericCSVData( dataname="data/2006-day-001.txt", dtformat=("%Y-%m-%d"), timeframe=bt.TimeFrame.Days, compression=1, ) cerebro.adddata(data) cerebro.addstrategy(Strategy) cerebro.addanalyzer(CashMarket, _name = "cash_market") # Execute results = cerebro.run() # Dictionary dictionary = results[0].analyzers.getbyname("cash_market").get_analysis() json_object = json.dumps(dictionary, indent=4) print(json_object)
Thank you for this very detailed example. However when i tried to run the code, the results list is empty. Do you have any idea why?
-
@bkak ah sorry, my mistake :) It seems to work great!