本文整理汇总了Python中backtrader.Cerebro方法的典型用法代码示例。如果您正苦于以下问题:Python backtrader.Cerebro方法的具体用法?Python backtrader.Cerebro怎么用?Python backtrader.Cerebro使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类backtrader
的用法示例。
在下文中一共展示了backtrader.Cerebro方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: backtesting
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def backtesting(config):
cerebro = Cerebro()
cerebro.addstrategy(TestStrategy)
cerebro.adddata(CCXTFeed(exchange='binance',
dataname='BNB/USDT',
timeframe=TimeFrame.Minutes,
fromdate=datetime(2019, 1, 1, 0, 0),
todate=datetime(2019, 1, 1, 0, 2),
compression=1,
ohlcv_limit=2,
currency='BNB',
config=config,
retries=5))
finished_strategies = cerebro.run()
return finished_strategies
示例2: dopostinit
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def dopostinit(cls, _obj, *args, **kwargs):
# Go to parent
res = super(_MetaTALibIndicator, cls).dopostinit(_obj,
*args, **kwargs)
_obj, args, kwargs = res
# Get the minimum period by using the abstract interface and params
_obj._tabstract.set_function_args(**_obj.p._getkwargs())
_obj._lookback = lookback = _obj._tabstract.lookback + 1
_obj.updateminperiod(lookback)
if _obj._unstable:
_obj._lookback = 0
elif cls.__name__ in cls._KNOWN_UNSTABLE:
_obj._lookback = 0
cerebro = bt.metabase.findowner(_obj, bt.Cerebro)
tafuncinfo = _obj._tabstract.info
_obj._tafunc = getattr(talib, tafuncinfo['name'], None)
return _obj, args, kwargs # return the object and args
示例3: runstrat
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def runstrat(pargs=None):
args = parse_args(pargs)
cerebro = bt.Cerebro()
cerebro.broker.set_cash(args.cash)
cerebro.broker.set_coc(args.coc)
data0 = bt.feeds.YahooFinanceData(
dataname=args.data,
fromdate=datetime.datetime.strptime(args.fromdate, '%Y-%m-%d'),
todate=datetime.datetime.strptime(args.todate, '%Y-%m-%d'),
round=False)
cerebro.adddata(data0)
cerebro.addsizer(bt.sizers.FixedSize, stake=args.stake)
cerebro.addstrategy(TheStrategy, **(eval('dict(' + args.strat + ')')))
cerebro.addobserver(bt.observers.Value)
cerebro.addobserver(bt.observers.Trades)
cerebro.addobserver(bt.observers.BuySell, barplot=True)
cerebro.run(stdstats=False)
if args.plot:
cerebro.plot(**(eval('dict(' + args.plot + ')')))
示例4: runstrat
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def runstrat(pargs=None):
args = parse_args(pargs)
cerebro = bt.Cerebro()
cerebro.broker.set_cash(args.cash)
data0 = bt.feeds.YahooFinanceData(
dataname=args.data,
fromdate=datetime.datetime.strptime(args.fromdate, '%Y-%m-%d'),
todate=datetime.datetime.strptime(args.todate, '%Y-%m-%d'))
cerebro.adddata(data0)
cerebro.addstrategy(SmaCross, **(eval('dict(' + args.strat + ')')))
cerebro.addsizer(bt.sizers.FixedSize, stake=args.stake)
cerebro.run()
if args.plot:
cerebro.plot(**(eval('dict(' + args.plot + ')')))
示例5: runstrat
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def runstrat():
args = parse_args()
cerebro = bt.Cerebro()
data = getdata(args)
cerebro.adddata(data)
cerebro.addstrategy(
OrderExecutionStrategy,
exectype=args.exectype,
perc1=args.perc1,
perc2=args.perc2,
valid=args.valid,
smaperiod=args.smaperiod
)
cerebro.run()
if args.plot:
cerebro.plot(numfigs=args.numfigs, style=args.plotstyle)
示例6: cerebro
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def cerebro() -> bt.Cerebro:
cerebro = bt.Cerebro()
datapath = getdatadir('orcl-1995-2014.txt')
data = bt.feeds.YahooFinanceCSVData(
dataname=datapath,
fromdate=datetime.datetime(1998, 1, 1),
todate=datetime.datetime(2000, 12, 31),
reverse=False,
swapcloses=True,
)
cerebro.adddata(data)
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer)
cerebro.addanalyzer(bt.analyzers.SharpeRatio, compression=2)
cerebro.addanalyzer(bt.analyzers.TimeDrawDown)
return cerebro
示例7: test_std_backtest_2datas
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def test_std_backtest_2datas(cerebro: bt.Cerebro):
datapath = getdatadir('nvda-1999-2014.txt')
data = bt.feeds.YahooFinanceCSVData(
dataname=datapath,
fromdate=datetime.datetime(1998, 1, 1),
todate=datetime.datetime(2000, 12, 31),
reverse=False,
swapcloses=True,
)
cerebro.adddata(data)
cerebro.addstrategy(bt.strategies.MA_CrossOver)
cerebro.run()
s = backtrader_plotting.schemes.Blackly()
b = Bokeh(style='bar', scheme=s, output_mode=_output_mode, merge_data_hovers=True)
figs = cerebro.plot(b)
assert len(figs) == 1
assert_num_tabs(figs, 3)
assert_num_figures(figs, 5)
示例8: test_std_backtest_ind_subplot
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def test_std_backtest_ind_subplot(cerebro: bt.Cerebro):
cerebro.addstrategy(bt.strategies.MA_CrossOver)
cerebro.run()
plotconfig = {
'#:i-0': {
'subplot': True,
}
}
s = backtrader_plotting.schemes.Blackly()
b = Bokeh(style='bar', scheme=s, output_mode=_output_mode, plotconfig=plotconfig)
figs = cerebro.plot(b)
assert_num_tabs(figs, 3)
assert_num_figures(figs, 5)
示例9: test_optimize
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def test_optimize(cerebro: bt.Cerebro):
cerebro.optstrategy(bt.strategies.MA_CrossOver, slow=[5, 10, 20], fast=[5, 10, 20])
res = cerebro.run(optreturn=True)
b = Bokeh(style='bar', output_mode=_output_mode)
browser = OptBrowser(b, res)
model = browser.build_optresult_model()
# browser.start()
def count_children(obj):
numo = 1
if hasattr(obj, "children"):
numo = count_children(obj.children)
if hasattr(obj, '__len__'):
numo += len(obj)
return numo
num = count_children(model)
assert num == 3
示例10: test_optimize_no_optreturn
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def test_optimize_no_optreturn(cerebro_no_optreturn: bt.Cerebro):
cerebro_no_optreturn.optstrategy(bt.strategies.MA_CrossOver, slow=[5, 10, 20], fast=[5, 10, 20])
res = cerebro_no_optreturn.run()
s = backtrader_plotting.schemes.Blackly()
b = Bokeh(style='bar', output_mode=_output_mode, scheme=s)
browser = OptBrowser(b, res)
model = browser.build_optresult_model()
#browser.start()
def count_children(obj):
numo = 1
if hasattr(obj, "children"):
numo = count_children(obj.children)
if hasattr(obj, '__len__'):
numo += len(obj)
return numo
num = count_children(model)
assert num == 3
示例11: test_github_issue30
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def test_github_issue30():
cerebro = bt.Cerebro()
cerebro.addstrategy(MyStrategy)
data = bt.feeds.YahooFinanceCSVData(
dataname=getdatadir("orcl-1995-2014.txt"),
fromdate=datetime.datetime(2000, 1, 1),
todate=datetime.datetime(2001, 2, 28),
reverse=False,
)
cerebro.adddata(data)
cerebro.addanalyzer(bt.analyzers.SharpeRatio)
cerebro.run()
b = backtrader_plotting.Bokeh(filename='chart.html', style='bar', scheme=Tradimo(), output_mode='memory')
figs = cerebro.plot(b)
assert isinstance(figs[0][0], backtrader_plotting.bokeh.bokeh.FigurePage)
assert len(figs[0][0].figure_envs) == 4
assert len(figs[0][0].analyzers) == 1
示例12: runstrat
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def runstrat(args=None):
args = parse_args(args)
cerebro = bt.Cerebro()
# Data feed kwargs
kwargs = dict()
# Parse from/to-date
dtfmt, tmfmt = '%Y-%m-%d', 'T%H:%M:%S'
for a, d in ((getattr(args, x), x) for x in ['fromdate', 'todate']):
if a:
strpfmt = dtfmt + tmfmt * ('T' in a)
kwargs[d] = datetime.datetime.strptime(a, strpfmt)
# Data feed
data0 = bt.feeds.BacktraderCSVData(dataname=args.data0, **kwargs)
cerebro.adddata(data0)
# Broker
cerebro.broker = bt.brokers.BackBroker(**eval('dict(' + args.broker + ')'))
# Sizer
cerebro.addsizer(bt.sizers.FixedSize, **eval('dict(' + args.sizer + ')'))
# Strategy
cerebro.addstrategy(St, **eval('dict(' + args.strat + ')'))
# Execute
cerebro.run(**eval('dict(' + args.cerebro + ')'))
if args.plot: # Plot if requested to
cerebro.plot(**eval('dict(' + args.plot + ')'))
示例13: main
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def main():
class TestStrategy(bt.Strategy):
def __init__(self):
self.next_runs = 0
def next(self, dt=None):
dt = dt or self.datas[0].datetime.datetime(0)
print('%s closing price: %s' % (dt.isoformat(), self.datas[0].close[0]))
self.next_runs += 1
cerebro = bt.Cerebro()
cerebro.addstrategy(TestStrategy)
# Add the feed
cerebro.adddata(CCXTFeed(exchange='binance',
dataname='BNB/USDT',
timeframe=bt.TimeFrame.Minutes,
fromdate=datetime(2019, 1, 1, 0, 0),
todate=datetime(2019, 1, 1, 0, 2),
compression=1,
ohlcv_limit=2,
currency='BNB',
retries=5,
# 'apiKey' and 'secret' are skipped
config={'enableRateLimit': True, 'nonce': lambda: str(int(time.time() * 1000))}))
# Run the strategy
cerebro.run()
示例14: donew
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def donew(cls, *args, **kwargs):
_obj, args, kwargs = super(MetaStrategy, cls).donew(*args, **kwargs)
# Find the owner and store it
_obj.env = _obj.cerebro = cerebro = findowner(_obj, bt.Cerebro)
_obj._id = cerebro._next_stid()
return _obj, args, kwargs
示例15: runstrat
# 需要导入模块: import backtrader [as 别名]
# 或者: from backtrader import Cerebro [as 别名]
def runstrat(args=None):
args = parse_args(args)
cerebro = bt.Cerebro()
# Data feed kwargs
kwargs = dict()
# Parse from/to-date
dtfmt, tmfmt = '%Y-%m-%d', 'T%H:%M:%S'
for a, d in ((getattr(args, x), x) for x in ['fromdate', 'todate']):
if a:
strpfmt = dtfmt + tmfmt * ('T' in a)
kwargs[d] = datetime.datetime.strptime(a, strpfmt)
data0 = bt.feeds.BacktraderCSVData(dataname=args.data0, **kwargs)
cerebro.adddata(data0)
# Broker
cerebro.broker = bt.brokers.BackBroker(**eval('dict(' + args.broker + ')'))
# Sizer
cerebro.addsizer(bt.sizers.FixedSize, **eval('dict(' + args.sizer + ')'))
# Strategy
StClass = APPROACHES[args.approach]
cerebro.addstrategy(StClass, **eval('dict(' + args.strat + ')'))
# Execute
cerebro.run(**eval('dict(' + args.cerebro + ')'))
if args.plot: # Plot if requested to
cerebro.plot(**eval('dict(' + args.plot + ')'))