我有在 backtrader 中回测交易策略的文件。我想收集文件中的数据,然后我可以分析它们。现在我打印出我想要的信息,但我想让它自动写下来。有人可以告诉我怎么做吗?我想要存储的信息是:交易数量、盈利/亏损交易数量、回撤、最大回撤和账户发展百分比。我真的不明白如何实现分析器、观察器或编写器来让程序执行此操作。
这是现在的代码:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import datetime
import os.path
import sys
import backtrader.feeds as btfeeds
import backtrader as bt
import matplotlib
import argparse
class TestStrategy(bt.Strategy):
params = (
('exitbars', 5),('stop_loss', 0.98),('take_profit',1.04),
)
def log(self, txt, dt=None):
''' Logging function fot this strategy'''
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def __init__(self):
# Keep a reference to the "close" line in the data[0] dataseries
self.dataclose = self.datas[0].close
self.order = None
self.buyprice = None
self.buycomm = None
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
return
if order.status in [order.Completed]:
if order.isbuy():
self.log(
'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
else: # Sell
self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.bar_executed = len(self)
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
self.order = None
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
(trade.pnl, trade.pnlcomm))
def next(self):
if self.order:
return
if not self.position:
# Not yet ... we MIGHT BUY if ...
if self.dataclose[0] < self.dataclose[-1]:
if self.dataclose[-1] < self.dataclose[-2]:
self.order = self.buy()
else:
SL_price = ( self.params.stop_loss* self.buyprice)
TP_price = (self.params.take_profit * self.buyprice)
if self.dataclose[0] <= SL_price or self.dataclose[0] >= TP_price:
self.order = self.sell()
if __name__ == '__main__':
cerebro = bt.Cerebro()
cerebro.addobserver(bt.observers.DrawDown)
cerebro.addstrategy(TestStrategy)
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, '../../datas/orcl-1995-2014.txt')
data = bt.feeds.YahooFinanceCSVData(
dataname='AAPL.csv',
fromdate=datetime.datetime(2015, 1, 1),
todate=datetime.datetime(2021, 1, 1),
reverse=False)
cerebro.adddata(data)
cerebro.broker.setcash(100000.0)
cerebro.addsizer(bt.sizers.FixedSize, stake=1000)
cerebro.broker.setcommission(commission=0.001)
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
cerebro.plot()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
´´´