def runstrategy():
    args = parse_args()

    # Create a cerebro
    cerebro = bt.Cerebro()

    # Get the dates from the args
    fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
    todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')

    testDate = datetime.datetime.strptime('2004-01-01', '%Y-%m-%d')

    # Create the 1st data
    data0 = btfeeds.YahooFinanceCSVData(dataname=args.data0,
                                        fromdate=fromdate,
                                        todate=todate)

    data0.addfilter(WeekDaysFiller, fillclose=False)
    # Add the 1st data to cerebro
    cerebro.adddata(data0)

    # Create the 2nd data
    data1 = btfeeds.YahooFinanceCSVData(dataname=args.data1,
                                        fromdate=testDate,
                                        todate=todate)

    data1.addfilter(WeekDaysFiller, fillclose=False)
    # Add the 2nd data to cerebro
    cerebro.adddata(data1)

    # Add the strategy
    cerebro.addstrategy(MultiDataStrategy,
                        period=args.period,
                        stake=args.stake)

    # Add the commission - only stocks like a for each operation
    cerebro.broker.setcash(args.cash)

    # Add the commission - only stocks like a for each operation
    cerebro.broker.setcommission(commission=args.commperc)

    # And run it
    cerebro.run(runonce=not args.runnext,
                preload=not args.nopreload,
                oldsync=args.oldsync)

    # Plot if requested
    if args.plot:
        cerebro.plot(numfigs=args.numfigs, volume=False, zdown=False)
Ejemplo n.º 2
0
def main():

    log, app_config, syncdb, run_fromdate, run_todate = setting_up()

    try:
        cerebro = bt.Cerebro(stdstats=False)

        strategy_classes = import_strategies(app_config)
        securities = load_securities(app_config, syncdb)
        found = False

        log.info('Analisys period is {} - {}'.format(run_fromdate, run_todate))

        # load_datafeeds(securities)
        #
        for security_id, _struct in securities.items():
            datafile = syncdb.select_security_datafeed(_struct, security_id,
                                                       run_fromdate,
                                                       run_todate)
            if datafile:
                data = btfeeds.YahooFinanceCSVData(dataname=datafile,
                                                   fromdate=run_fromdate,
                                                   todate=run_todate +
                                                   dt.timedelta(days=1),
                                                   adjclose=False,
                                                   decimals=5)

                cerebro.adddata(data, security_id)
                log.info('datafeed <{}> succesfully added to cerebro'.format(
                    security_id))
                found = True

        if found:
            #cerebro.addwriter(bt.WriterFile, csv=True, out="output.csv")
            cerebro.broker.setcash(10000.0)

            for strategy_label in strategy_classes:
                cerebro.addstrategy(strategy_classes[strategy_label],
                                    config=app_config,
                                    name=strategy_label,
                                    fromdate=run_fromdate,
                                    todate=run_todate)

            cerebro.run()
            #cerebro.plot(style='candlestick', barup='green', bardown='black')
            syncdb.close()
        else:
            log.warning('~ No security found ~')

        log.info('*** END SESSION ***')

    except Exception as e:
        log.error('ABEND : {}'.format(e))
        try:
            syncdb.close()
        except Exception:
            pass
        sys.exit(1)
Ejemplo n.º 3
0
def runstrategy():
    args = parse_args()

    # Create a cerebro
    cerebro = bt.Cerebro()

    # Get the dates from the args
    fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
    todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')

    # Create the 1st data
    data0 = btfeeds.YahooFinanceCSVData(
        dataname=args.data0,
        fromdate=fromdate,
        todate=todate)

    # Add the 1st data to cerebro
    cerebro.adddata(data0)

    # Create the 2nd data
    data1 = btfeeds.YahooFinanceCSVData(
        dataname=args.data1,
        fromdate=fromdate,
        todate=todate)

    # Add the 2nd data to cerebro
    cerebro.adddata(data1)

    # Add the strategy
    cerebro.addstrategy(MultiDataStrategy,
                        period=args.period,
                        stake=args.stake)

    # Add the commission - only stocks like a for each operation
    cerebro.broker.setcash(args.cash)

    # Add the commission - only stocks like a for each operation
    cerebro.broker.setcommission(commission=args.commperc)

    # And run it
    cerebro.run()

    # Plot if requested
    if args.plot:
        cerebro.plot(numfigs=args.numfigs, volume=False, zdown=False)
Ejemplo n.º 4
0
def backtest(algorithm, ticker):
    os.system("cls")
    cerebro = bt.Cerebro()
    cerebro.broker.setcash(10000)
    data = btfeeds.YahooFinanceCSVData(dataname="historical/sets/" + ticker +
                                       ".csv")
    cerebro.adddata(data)
    cerebro.addstrategy(algorithm)
    cerebro.run()
    cerebro.plot()
Ejemplo n.º 5
0
def runstrat():
    args = parse_args()

    cerebro = bt.Cerebro()
    data = btfeeds.YahooFinanceCSVData(dataname=args.data)
    cerebro.adddata(data)
    cerebro.addstrategy(St,
                        datalines=args.datalines,
                        lendetails=args.lendetails)

    cerebro.run(runonce=False, exactbars=args.save)
    if args.plot:
        cerebro.plot(style='bar')
Ejemplo n.º 6
0
import backtrader as bt
import backtrader.feeds as btfeeds
import datetime

datapath = 'IBOV.csv'

data = btfeeds.YahooFinanceCSVData(dataname=datapath,
                                   reversed=True,
                                   fromdate=datetime.datetime(2015, 1, 1),
                                   todate=datetime.datetime(2020, 1, 31),
                                   timeframe=bt.TimeFrame.Weeks)


class CrossSMA(bt.Strategy):

    params = dict(pfast=8, pslow=20)

    def __init__(self):
        sma1 = bt.ind.SMA(period=self.p.pfast)
        sma2 = bt.ind.SMA(period=self.p.pslow)
        self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal

    def next(self):
        if not self.position:
            if self.crossover > 0:
                self.buy()

        elif self.crossover < 0:
            self.close()

Ejemplo n.º 7
0
      if self.getposition(d).size != 0:
        if d.fastma < d.slowma:
          self.sell(d, size=self.getposition(d).size)

    # buy
    for d in self.datas:
      # don't buy twice
      if self.getposition(d).size != 0:
        continue
      
      if d.fastma > d.slowma:
        self.buy(d, size=int(self.broker.get_cash()/d))

cerebro = bt.Cerebro()
cerebro.adddata(btfeeds.YahooFinanceCSVData(
  dataname="SPY.csv"
))

#cerebro.broker.set_cash(10000) # we start with $10,000 by default!
cerebro.addstrategy(GoldenCross)
cerebro.run()

# extra optional stuff
print("% return:")
print((cerebro.broker.get_value() - 10000) / 10000)
print("CAGR:")
print(pow(cerebro.broker.get_value()/10000 ,1/25) - 1)
# these calculations can all be done with observers,
# but we won't get into that yet

# see our final plot, do everything before this!
Ejemplo n.º 8
0
import yfinance as yf
import pandas as pd
import backtrader as bt
import backtrader.feeds as btfeeds
import datetime
from strategy import RSIStrategy

#getting data from Yahoo finance site
data = btfeeds.YahooFinanceCSVData(dataname='ETH_data.csv')
cerebro = bt.Cerebro()
#set cash to 10000$
starting_cash = 10000
cerebro.broker.set_cash(starting_cash)
#adding the data to backtrader
cerebro.adddata(data)
#adding the strategy
cerebro.addstrategy(RSIStrategy)
#Binance commision on trades
cerebro.broker.setcommission(0.001)

print('Starting Portfolio Value: {}'.format(cerebro.broker.getvalue()))

cerebro.run()

print('Final Portfolio Value: {}'.format(cerebro.broker.getvalue()))

print('Total winnings/losses : {}$'.format(cerebro.broker.getvalue() -
                                           starting_cash))
#plotting the results
cerebro.plot()