Exemplo n.º 1
0
def check_stocks():
    commission = 0.5
    comm = bt.CommissionInfo(commission=commission)

    size = 10.0
    price = 10.0
    cash = 1.0

    marginok = comm.checkmargin(size=size, price=price, cash=cash)
    assert not marginok

    cash = 10000.0
    size = 100.0
    marginok = comm.checkmargin(size=size, price=price, cash=cash)
    assert marginok

    opcost = comm.getoperationcost(size=size, price=price)
    assert opcost == size * price

    pos = Position(size=size, price=price)
    value = comm.getvalue(pos, price)
    assert value == size * price

    commcost = comm.getcomm_pricesize(size, price)
    assert commcost == size * price * commission

    newprice = 5.0
    pnl = comm.profitandloss(pos, newprice)
    assert pnl == pos.size * (newprice - price)

    ca = comm.cashadjust(size, price, newprice)
    assert not ca
Exemplo n.º 2
0
def check_futures():
    commission = 0.5
    margin = 10.0
    mult = 10.0
    comm = bt.CommissionInfo(commission=commission, mult=mult, margin=margin)

    price = 10.0
    cash = 10000.0
    size = 100.0

    opcost = comm.getoperationcost(size=size, price=price)
    assert opcost == size * margin

    pos = Position(size=size, price=price)
    value = comm.getvalue(pos, price)
    assert value == size * margin

    commcost = comm.getcommission(size, price)
    assert commcost == size * commission

    newprice = 5.0
    pnl = comm.profitandloss(pos.size, pos.price, newprice)
    assert pnl == pos.size * (newprice - price) * mult

    ca = comm.cashadjust(size, price, newprice)
    assert ca == size * (newprice - price) * mult
Exemplo n.º 3
0
def multi_data_runner():
    cerebro = bt.Cerebro()
    cerebro.addstrategy(MultiDataStrategy)

    firstrate_path = '/Users/jinchaolin/FirstRateReady/futures-active_adjusted_1min_8sjor/'
    firstrate_file = 'ES' + '_continuous_adjusted_1min.txt'
    dataname = firstrate_path + firstrate_file
    data = bt.feeds.GenericCSVData(
        dataname=dataname,
        fromdate=datetime.datetime(2017, 1, 1),
        todate=datetime.datetime(2019, 1, 1),
        # nullvalue = 0.0,
        dtformat=('%Y-%m-%d %H:%M:%S'),
        openinterest=-1)
    # Add the Data Feed to Cerebro
    cerebro.adddata(data)
    cerebro.addanalyzer(btanalyzers.TimeReturn,
                        _name='time_return',
                        timeframe=bt.TimeFrame.Months)
    cerebro.broker.setcash(500_000.0)

    cerebro.addsizer(bt.sizers.FixedSize, stake=10)

    commES = bt.CommissionInfo(commission=2.0, margin=5000.0, mult=50.0)
    cerebro.broker.addcommissioninfo(commES, name='ES')
    res = cerebro.run()
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

    import pdb
    pdb.set_trace()

    cerebro.plot()
Exemplo n.º 4
0
def add_chain_data(cerebro, chains, with_comms=False):
    """Add all data from a future chain to Cerebro

    :param cerebro: object - Cerebro instance from Backtrader
    :param chains: list of object FutureChain - FutureChain to be added to Cerebro
    :param with_comms: bool - Add commissions with the data
    :return: object Cerebro
    """
    # Add Data to Cerebro
    for chain in chains:
        # Commissions - Note: When throwing margin rejects => due to missing data
        comms = bt.CommissionInfo(commission=chain.commission * 2, margin=chain.margin, mult=chain.point)
        # Add all data series
        for ct in chain.contracts:  # [0:15]
            # TODO: Check if missing data compared to Reference!
            if chain.future_type == oci.FutureType.Spread:
                data = SpreadPandasData(dataname=chain.data[ct])
            else:
                data = bt.feeds.PandasData(dataname=chain.data[ct])
            data.plotinfo.plot = False  # Do not plot this data
            cerebro.adddata(data, name=ct)
            # Commissions
            if with_comms:
                cerebro.broker.addcommissioninfo(comms, name=ct)
    return cerebro
def runstrat(args=None):
    args = parse_args(args)

    cerebro = bt.Cerebro()
    cerebro.broker.set_cash(args.cash)
    cerebro.broker.set_int2pnl(args.no_int2pnl)

    dkwargs = dict()
    if args.fromdate is not None:
        fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
        dkwargs['fromdate'] = fromdate

    if args.todate is not None:
        todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')
        dkwargs['todate'] = todate

    # if dataset is None, args.data has been given
    data = bt.feeds.BacktraderCSVData(dataname=args.data, **dkwargs)
    cerebro.adddata(data)

    cerebro.signal_strategy(St)
    cerebro.addsizer(bt.sizers.FixedSize, stake=args.stake)

    sigtype = bt.signal.SIGNAL_LONGSHORT
    if args.long:
        sigtype = bt.signal.SIGNAL_LONG
    elif args.short:
        sigtype = bt.signal.SIGNAL_SHORT

    cerebro.add_signal(sigtype, SMACrossOver, p1=args.period1, p2=args.period2)

    if args.no_exit:
        if args.long:
            cerebro.add_signal(bt.signal.SIGNAL_LONGEXIT, NoExit)
        elif args.short:
            cerebro.add_signal(bt.signal.SIGNAL_SHORTEXIT, NoExit)

    comminfo = bt.CommissionInfo(mult=args.mult,
                                 margin=args.margin,
                                 stocklike=args.stocklike,
                                 interest=args.interest,
                                 interest_long=args.interest_long)

    cerebro.broker.addcommissioninfo(comminfo)

    cerebro.run()
    if args.plot:
        pkwargs = dict(style='bar')
        if args.plot is not True:  # evals to True but is not True
            npkwargs = eval('dict(' + args.plot + ')')  # args were passed
            pkwargs.update(npkwargs)

        cerebro.plot(**pkwargs)
Exemplo n.º 6
0
 def __init__(self):
     self.order = None  # keep track of our orders
     self.buyprice = None  # keeps track of our buy price
     self.sellprice = None
     self.trade = None  # store the current trade
     commission = 0.0
     self.comm = bt.CommissionInfo(commission=commission)  # object of commisionInfo class to get pnl
     # self.orderHist = []
     self.orderDict = {}  # stores a dictionary of each trade
     self.datelist = 0
     self.finalpnl = 0  # final pnl
     self.set_tradehistory(True)  # cerebro attribute -- ignore
     self.time_after_ml = datetime.time(10, 0, 0, 0)
     self.after_day = False  # to know when to stop trading
     self.datastatus = None
     self.signals = {}  # store the buy/sell signals from csv
Exemplo n.º 7
0
    # cerebro.addanalyzer(btanalyzers.PositionsValue, _name='position_value')# 有问题
    # cerebro.addanalyzer(btanalyzers.PyFolio, _name='pyfolio')# 有问题
    # cerebro.addanalyzer(btanalyzers.SQN, _name='sqn')
    cerebro.addanalyzer(btanalyzers.TimeReturn, _name='time_return', timeframe=bt.TimeFrame.Months)
    # cerebro.addanalyzer(btanalyzers.Transactions, _name='transactions')
    # cerebro.addanalyzer(btanalyzers.VWR, _name='variability_weighted_return')


    # Set our desired cash start
    cerebro.broker.setcash(1_000_000.0)

    # Add a FixedSize sizer according to the stake
    cerebro.addsizer(bt.sizers.FixedSize, stake=10)

    # Define commission
    commES = bt.CommissionInfo(commission=2.0, margin=5000.0, mult=50.0)

    # Set the commission
    # cerebro.broker.setcommission(commission=0.001)
    # cerebro.broker.setcommission(commission=2.0, margin=5000.0, mult=50.0, name='ES')
    cerebro.broker.addcommissioninfo(commES, name='ES')

    # Add a writer 
    cerebro.addwriter(bt.WriterFile, out='bt_res_2', csv=True)
    cerebro.addwriter(bt.WriterFile, out='bt_res', log_dir='/Users/jinchaolin/TradingBT/log/tmp/', csv=True)

    # Print out the starting conditions
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

    # Run over everything
    # res = cerebro.run()