Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Plotting Date Ranges

The release,1.9.31.x added the capability to make partial plots.

  • Either with indices to the full length array oftimestamps kept instrategy instances

  • Or with actualdatetime.date ordatetime.datetime instances that limit what has to be plotted.

Everything still over the standardcerebro.plot. Example:

cerebro.plot(start=datetime.date(2005, 7, 1), end=datetime.date(2006, 1, 31))

Being that the straightforward way to do it for humans. Humans with extendedcapabilities can actually try indices to thedatetime timestamps as in:

cerebro.plot(start=75, end=185)

A very standard sample containing aSimple Moving Average (on-dataplotting), aStochastic (independent plotting) and aCrossOver of theStochastic lines is presented below. The arguments tocerebro.plot arepassed as command line arguments.

An execution with thedate approach:

./partial-plot.py --plot 'start=datetime.date(2005, 7, 1),end=datetime.date(2006, 1, 31)'

Theeval magic in python allows to directly writedatetime.date in thecommand line and map actually that to something sensible. The output chart

image

Let’s compare it with the full plot to see that data was actually skipped fromboth ends:

./partial-plot.py --plot

Theeval magic in python allows to directly writedatetime.date in thecommand line and map actually that to something sensible. The output chart

image

Sample Usage

$ ./partial-plot.py --helpusage: partial-plot.py [-h] [--data0 DATA0] [--fromdate FROMDATE]                       [--todate TODATE] [--cerebro kwargs] [--broker kwargs]                       [--sizer kwargs] [--strat kwargs] [--plot [kwargs]]Sample for partial plottingoptional arguments:  -h, --help           show this help message and exit  --data0 DATA0        Data to read in (default:                       ../../datas/2005-2006-day-001.txt)  --fromdate FROMDATE  Date[time] in YYYY-MM-DD[THH:MM:SS] format (default: )  --todate TODATE      Date[time] in YYYY-MM-DD[THH:MM:SS] format (default: )  --cerebro kwargs     kwargs in key=value format (default: )  --broker kwargs      kwargs in key=value format (default: )  --sizer kwargs       kwargs in key=value format (default: )  --strat kwargs       kwargs in key=value format (default: )  --plot [kwargs]      kwargs in key=value format (default: )

Sample Code

from __future__ import (absolute_import, division, print_function,                        unicode_literals)import argparseimport datetimeimport backtrader as btclass St(bt.Strategy):    params = (    )    def __init__(self):        bt.ind.SMA()        stoc = bt.ind.Stochastic()        bt.ind.CrossOver(stoc.lines.percK, stoc.lines.percD)    def next(self):        passdef 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 + ')'))def parse_args(pargs=None):    parser = argparse.ArgumentParser(        formatter_class=argparse.ArgumentDefaultsHelpFormatter,        description=(            'Sample for partial plotting'        )    )    parser.add_argument('--data0', default='../../datas/2005-2006-day-001.txt',                        required=False, help='Data to read in')    # Defaults for dates    parser.add_argument('--fromdate', required=False, default='',                        help='Date[time] in YYYY-MM-DD[THH:MM:SS] format')    parser.add_argument('--todate', required=False, default='',                        help='Date[time] in YYYY-MM-DD[THH:MM:SS] format')    parser.add_argument('--cerebro', required=False, default='',                        metavar='kwargs', help='kwargs in key=value format')    parser.add_argument('--broker', required=False, default='',                        metavar='kwargs', help='kwargs in key=value format')    parser.add_argument('--sizer', required=False, default='',                        metavar='kwargs', help='kwargs in key=value format')    parser.add_argument('--strat', required=False, default='',                        metavar='kwargs', help='kwargs in key=value format')    parser.add_argument('--plot', required=False, default='',                        nargs='?', const='{}',                        metavar='kwargs', help='kwargs in key=value format')    return parser.parse_args(pargs)if __name__ == '__main__':    runstrat()

[8]ページ先頭

©2009-2025 Movatter.jp