def runstrat():
    args = parse_args()

    cerebro = bt.Cerebro()

    data = btfeeds.GenericCSVData(
        dataname=args.data,
        dtformat='%d/%m/%y',
        # tmformat='%H%M%S',  # already the default value
        # datetime=0,  # position at default
        time=1,  # position of time
        open=5,  # position of open
        high=5,
        low=5,
        close=5,
        volume=7,
        openinterest=-1,  # -1 for not present
        timeframe=bt.TimeFrame.Ticks)

    cerebro.resampledata(data,
                         timeframe=bt.TimeFrame.Minutes,
                         compression=args.compression)

    cerebro.addstrategy(St)

    cerebro.run()
    if args.plot:
        cerebro.plot(style='bar')
Exemple #2
0
def get_data(pair, years):
    path = f'data/{pair}/'
    dfs = []
    if not os.path.exists(path):
        os.mkdir(path)
    for year in years:
        try:
            download_data(pair, year)
        except AssertionError:
            print(f'{pair} {year} no data available')
            continue
        df = pd.read_csv(path + f'{year}.csv', sep=';', names=cfg.HEADERS)
        ts = df.iloc[:, 0].apply(
            lambda s: f'{s[:4]}-{s[4:6]}-{s[6:8]}T{s[9:11]}:{s[11:13]}')
        ts = pd.to_datetime(ts)
        df.iloc[:, 0] = ts
        dfs.append(df)
    df = pd.concat(dfs)
    # df.drop(columns='Volume', inplace=True)
    df.set_index('Timestamp', inplace=True)
    df.to_csv("data/cur_data.csv")
    btdata = btfeeds.GenericCSVData(dataname='data/cur_data.csv',
                                    nullvalue=0.0,
                                    datetime=0,
                                    open=1,
                                    high=2,
                                    low=3,
                                    close=4,
                                    volume=5,
                                    openinterest=-1)

    return btdata
Exemple #3
0
def run():

    cerebro = bt.Cerebro()

    # Create data feed using QuantRocket data and add to backtrader
    # (Put files in /tmp to have QuantRocket automatically clean them out after
    # a few hours)
    download_history_file(
        'usstock-free-1d',
        sids=['FIBBG000B9XRY4'],
        filepath_or_buffer='/tmp/backtrader-demo-1d.csv',
        fields=['Sid', 'Date', 'Open', 'Close', 'High', 'Low', 'Volume'])

    data = btfeeds.GenericCSVData(dataname='/tmp/backtrader-demo-1d.csv',
                                  dtformat=('%Y-%m-%d'),
                                  datetime=1,
                                  open=2,
                                  close=3,
                                  high=4,
                                  low=5,
                                  volume=6)
    cerebro.adddata(data)

    cerebro.addstrategy(DualMovingAverageStrategy)
    cerebro.run()

    # Save the plot to PDF so the satellite service can return it
    cerebro.plot(savefig=True, figfilename='/tmp/backtrader-plot.pdf')
Exemple #4
0
def run(args=None):

    args = parse_args(args)

    cerebro = bt.Cerebro()
    cerebro.broker.setcash(args.initial_cash)
    cerebro.broker.setcommission(args.commission)
    if args.log >= 1:
        print('Initial Cash: %.5f ' % cerebro.broker.getvalue())
        print('Commission: %.5f ' % (args.commission * 100))

    #Create Data Feed
    data = btfeed.GenericCSVData(dataname=args.filename,
                                 fromdate=init_date,
                                 todate=final_date,
                                 nullvalue=0.,
                                 dtformat=date_format,
                                 tmformat=time_format,
                                 datetime=date_column,
                                 time=time_column,
                                 high=high_column,
                                 low=low_column,
                                 open=open_column,
                                 close=close_column,
                                 volume=volume_column,
                                 openinterest=interest_column,
                                 timeframe=bt.TimeFrame.Ticks)

    cerebro.adddata(data)
    cerebro.addstrategy(SMA_ST, args)
    cerebro.addsizer(bt.sizers.SizerFix, stake=args.lot_volume)

    cerebro.addanalyzer(analyzer.PyFolio, _name='pyfolio')
    cerebro.addanalyzer(analyzer.DrawDown, _name='drawdown')
    cerebro.addanalyzer(analyzer.SharpeRatio,
                        _name='sharpe',
                        timeframe=bt.TimeFrame.Months)

    resultado = cerebro.run()

    res = resultado[0].analyzers.pyfolio.get_pf_items()
    dd = resultado[0].analyzers.drawdown.get_analysis()
    sr = resultado[0].analyzers.sharpe.get_analysis()

    if sr['sharperatio'] is None:
        sr_str = 0.
    else:
        sr_str = sr['sharperatio']

    retorno = 100. - (args.initial_cash / cerebro.broker.getvalue() * 100.)
    print('\nReturn: %.5f  \nDrawDown: %.2f  \nSharpe Ratio: %.2f\n' %
          (retorno, dd['drawdown'], sr_str))

    argplot = str(args.plot).upper()
    if 'FALSE'.startswith(argplot):
        pass
    else:
        cerebro.plot(style=args.plotstyle)
Exemple #5
0
def main():
    cerebro = bt.Cerebro()  # stdstats=False

    # Add a strategy
    cerebro.addstrategy(EMAStrategy)
    #cerebro.optstrategy(
    #    EMAStrategy,
    #    maperiod=range(10, 31)
    #)
    data = btfeeds.GenericCSVData(dataname='binance.csv',
                                  fromdate=datetime(2017, 7, 17),
                                  todate=datetime(2017, 7, 20),
                                  dtformat=("%d/%m/%Y %H:%M:%S"),
                                  timeframe=bt.TimeFrame.Minutes,
                                  datetime=0,
                                  open=1,
                                  high=2,
                                  low=3,
                                  close=4,
                                  volume=5,
                                  openinterest=-1)

    cerebro.adddata(data)
    # Add a FixedSize sizer according to the stake
    cerebro.addsizer(bt.sizers.PercentSizer, percents=99)

    # Set our desired cash start
    cerebro.broker.setcash(0.50)

    # Set the commission
    cerebro.broker.setcommission(commission=0.001)

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

    # add analyzers
    # Add the analyzers we are interested in
    cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="ta")
    cerebro.addanalyzer(bt.analyzers.SQN, _name="sqn")
    cerebro.addanalyzer(bt.analyzers.Returns, _name="returns")

    # Run over everything
    results = cerebro.run()
    runst = results[0]
    # Print out the final result
    print('Final Portfolio Value: %.8f' % cerebro.broker.getvalue())
    print('====================')
    print('== Analyzers')
    print('====================')
    analyzers = ["ta", "sqn"]
    for name in analyzers:
        printAnalyzersInfo(runst.analyzers.getbyname(name))
    print('---')
def input_tickData_csv(fileName):
    data = btfeeds.GenericCSVData(
        dataname=fileName,
        dtformat=('%Y-%m-%d'),
        datetime=0,
        high=2,
        low=3,
        open=1,
        close=4,
        volume=6,
    )
    return data
Exemple #7
0
def get_feeds(path):
    fs = get_filenames(path)
    feeds = {}

    for f in fs:
        f_str = f.split('.')[0]
        feeds[f_str] = btfeeds.GenericCSVData(dataname=path + f,
                                              fromdate=datetime(2015, 1, 1),
                                              todate=datetime(2018, 12, 31),
                                              openinterest=-1,
                                              timeframe=bt.TimeFrame.Minutes,
                                              compression=15)

    return feeds
Exemple #8
0
    def __init__(self,strategy,data=None):
        self.cerebro = bt.Cerebro()
        
        self.cerebro.broker.setcash(100000.0)
        self.cerebro.broker.setcommission(commission=0.0) # zero commission
    
        self.portfolioStartValue=self.cerebro.broker.getvalue()
                    
        if data is None:
            prefix = '/opt/ml/'
            self.train_data_path = os.path.join(prefix,'input/data/training/data.csv')
            self.output_path = os.path.join(prefix, 'output')
            self.model_path = os.path.join(prefix, 'model')  
            self.hyper_params_path = os.path.join(prefix, 'input/config/hyperparameters.json')
  

            with open(self.hyper_params_path, 'r') as f:
                self.hyper_params = json.load(f)
            print("hyper_params=%s" % (self.hyper_params))

            if 'sim_data' in self.hyper_params:
                self.data = AlgoSimData(self.train_data_path)
            else:
                self.data = btfeeds.GenericCSVData(
                    dataname=self.train_data_path,
                    dtformat=('%Y-%m-%d'),
                    timeframe=bt.TimeFrame.Minutes,
                    datetime=0,
                    time=-1,
                    high=2,
                    low=3,
                    open=1,
                    close=4,
                    volume=5,
                    openinterest=-1
            )
        else:
            self.hyper_params={}
            self.data=data
            
        self.cerebro.adddata(self.data)

        self.cerebro.addstrategy(strategy)

        self.cerebro.addanalyzer(btanalyzers.DrawDown, _name='dd')
        self.cerebro.addanalyzer(btanalyzers.SharpeRatio_A, _name='sharpe')
        self.cerebro.addanalyzer(btanalyzers.SQN, _name='sqn')
        self.cerebro.addanalyzer(btanalyzers.TradeAnalyzer, _name='ta')
def runstrat():
    args = parse_args()

    # Create a cerebro entity
    cerebro = bt.Cerebro(stdstats=False)

    # Add a strategy
    cerebro.addstrategy(bt.Strategy)

    # Load the Data
    datapath = args.dataname or '../../datas/ticksample.csv'

    data = btfeeds.GenericCSVData(
        dataname=datapath,
        dtformat='%Y-%m-%dT%H:%M:%S.%f',
        timeframe=bt.TimeFrame.Ticks,
    )

    # Handy dictionary for the argument timeframe conversion
    tframes = dict(ticks=bt.TimeFrame.Ticks,
                   microseconds=bt.TimeFrame.MicroSeconds,
                   seconds=bt.TimeFrame.Seconds,
                   minutes=bt.TimeFrame.Minutes,
                   daily=bt.TimeFrame.Days,
                   weekly=bt.TimeFrame.Weeks,
                   monthly=bt.TimeFrame.Months)

    # Resample the data
    cerebro.resampledata(data,
                         timeframe=tframes[args.timeframe],
                         compression=args.compression,
                         bar2edge=not args.nobar2edge,
                         adjbartime=not args.noadjbartime,
                         rightedge=args.rightedge)

    if args.writer:
        # add a writer
        cerebro.addwriter(bt.WriterFile, csv=args.wrcsv)

    # Run over everything
    cerebro.run()

    # Plot the result
    cerebro.plot(style='bar')
Exemple #10
0
def get_csv_GenericCSVData(stock_id="600016.SH",
                           start="20190101",
                           end="20191231"):
    # 日期格式转换
    dt_start = datetime.datetime.strptime(start, "%Y%m%d")
    dt_end = datetime.datetime.strptime(end, "%Y%m%d")
    # 读取文件
    data = btfeeds.GenericCSVData(dataname='fd_data/600016.SH.csv',
                                  fromdate=dt_start,
                                  todate=dt_end,
                                  nullvalue=0.0,
                                  dtformat=('%Y%m%d'),
                                  datetime=1,
                                  high=3,
                                  low=4,
                                  open=2,
                                  close=5,
                                  volume=9,
                                  openinterest=-1)
    return data
Exemple #11
0
def add_data(cerebro):
    for txt in ['IBM.txt']:
        data = btfeed.GenericCSVData(
            dataname=txt,
            dtformat='%m/%d/%Y',
            #tmformat='%H:%M',
            name=os.path.splitext(txt)[0],
            fromdate=datetime.datetime(1990, 1, 1),
            todate=datetime.datetime(2019, 6, 1),

            #  nullvalue=0.0,
            datetime=0,
            #time=1,
            open=1,
            high=2,
            low=3,
            close=4,
            volume=5,
            openinterest=-6)
        cerebro.adddata(data)
Exemple #12
0
def run(args=None):
    args = parse_args(args)
    print("[Initializing Cerebro]")
    cerebro = bt.Cerebro()
    if args.mode == 1:
        cerebro.addstrategy(backtesting, args)
        print("    Strategy added: BACKTESTING")
    elif args.mode == 2:
        cerebro.addstrategy(training, args)
        print("    Strategy added: TRAIN")
    cerebro.broker.setcash(args.initial_cash)
    print("    Initial money: %.2f" % cerebro.broker.getcash())
    cerebro.broker.setcommission(args.commission)
    print("    Comission: %.5f" % args.commission)
    data = btfeed.GenericCSVData(
        dataname=args.input_data,
        fromdata=init_date,
        todate=final_date,
        nullvalue=0.,
        dtformat=date_format,
        tmformat=time_format,
        #datetime = column_datetime,
        time=column_time,
        high=column_high,
        low=column_low,
        open=column_open,
        close=column_close,
        volume=column_volume,
        openinterest=column_interest,
        timeframe=bt.TimeFrame.Ticks)
    cerebro.adddata(data)
    print("    Data file: %s" % args.input_data)

    cerebro.addsizer(PercentCashSizer)

    print("[Starting Cerebro]")
    result = cerebro.run()
    print("\n    Final Value: %.2f" % cerebro.broker.getvalue())
    if args.mode <= 1:
        print("[Plotting]")
        cerebro.plot(plotstyle='candle')
Exemple #13
0
def strat_runner(asset, strat_name, cash=10000.0, test=False):
    cerebro = bt.Cerebro()
    cerebro.addstrategy(strat_name)

    for symbol in asset:
        path = f'{symbol}_{time_interval}_intraday_trading.csv'
        data = btfeeds.GenericCSVData(dataname=f'Data/{path}',
                                      nullvalue=0.0,
                                      dtformat='%Y-%m-%d %H:%M:%S',
                                      tmformat='%H:%M:%S',
                                      datetime=0,
                                      high=2,
                                      low=3,
                                      time=-1,
                                      open=1,
                                      close=4,
                                      volume=5,
                                      openinterest=-1)
        for i in data:
            print(i)

        cerebro.adddata(data)

    cerebro.broker.set_cash(cash)
    cerebro.broker.setcommission(commission=0.001)

    print('Starting Cash Amount Is %.2f' % cerebro.broker.get_cash())
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

    cerebro.run()

    print('Final portfolio: %.2f' % cerebro.broker.getvalue())
    print('Final Cash Amount Is %.2f' % cerebro.broker.get_cash())

    cerebro.plot(iplot=False)

    if test:
        # Skipps the logging process if test mode is of
        logger()

    data_flusher(asset, time_interval)
def main():
    #make some dummy data
    # DataFactory().make_data("monte_carlo", "test_data.csv")
    df = pd.read_csv('test_data.csv')

    #Initialis cerebro - the brains of the back trader framework
    cerebro = bt.Cerebro()
    cerebro.broker.setcash(100000.0)
    cerebro.addstrategy(MonteCarloStrat)

    
    data = btfeeds.GenericCSVData(
        dataname='test_data.csv',

        fromdate=datetime.datetime(2020, 1, 1),
        todate=datetime.datetime(2020, 1, 3),

        nullvalue=0.0,

        dtformat=('%Y-%m-%d'),

        datetime=0,
        high=1,
        low=2,
        open=3,
        close=4,
        volume=5,
        openinterest=-1
    )
    
    cerebro.adddata(data)



    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

    cerebro.run()
    # cerebro.plot()

    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
def main():
    cerebro = bt.Cerebro()
    # Add a strategy
    cerebro.addstrategy(EMAStrategy)

    data = btfeeds.GenericCSVData(dataname='binance.csv',
                                  fromdate=datetime(2018, 3, 1),
                                  todate=datetime(2018, 3, 2),
                                  dtformat=("%d/%m/%Y %H:%M:%S"),
                                  timeframe=bt.TimeFrame.Minutes,
                                  datetime=0,
                                  open=1,
                                  high=2,
                                  low=3,
                                  close=4,
                                  volume=5,
                                  openinterest=-1)

    cerebro.adddata(data)

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

    # Set our desired cash start
    cerebro.broker.setcash(50000.0)

    # Set the commission
    cerebro.broker.setcommission(commission=0.00)

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

    # Run over everything
    cerebro.run()

    # Print out the final result
    print('Final Portfolio Value: %.8f' % cerebro.broker.getvalue())
    cerebro.plot(style='candlestick')
    cerebro = bt.Cerebro()
    # data = btfeeds.YahooFinanceData(dataname='AAPL',
    #                                 fromdate=datetime.datetime(2019, 1, 1),
    #                                 todate=datetime.datetime(2019, 12, 31))
    # data = web.DataReader("^GSPC", 'yahoo', datetime.datetime(2010, 1, 1), datetime.datetime(2019, 12, 31))
    # data.reset_index(inplace=True)
    #
    # data.to_csv("D:/Time_Series_Research/new_data/GSPC.csv", index=0, header=1)

    data = btfeeds.GenericCSVData(
        dataname="D:/Time_Series_Research/new_data/GSPC.csv",
        fromdate=datetime.datetime(2019, 1, 1),
        todate=datetime.datetime(2019, 12, 31),
        nullvalue=0.0,
        dtformat=('%Y-%m-%d'),
        datetime=0,
        high=2,
        low=3,
        open=1,
        close=4,
        volume=5,
        openinterest=-1)
    cerebro.adddata(data)

    cerebro.addstrategy(RSI_Sta)
    # cerebro.optstrategy(
    #     RSI_Sta,
    #     period = range(6,16),
    #     upper = range(70,91),
    #     lower = range(10,31)
    # )
Exemple #17
0
                # Sell a 5% sell position (or whatever is afforded by the current stock holding)
                # "size" refers to the number of stocks to purchase
                self.order = self.sell(size=int((INIT_CASH / self.dataclose[0]) * 0.1))


if __name__ == "__main__":
    cerebro = bt.Cerebro()
    cerebro.addstrategy(RSIStrategy)
    cerebro.broker.setcommission(commission=COMMISSION_PER_TRANSACTION)

    data = btfeed.GenericCSVData(
        dataname=DATA_FILE,
        fromdate=datetime.datetime(2017, 1, 1),
        todate=datetime.datetime(2019, 1, 1),
        nullvalue=0.0,
        dtformat=("%Y-%m-%d"),
        datetime=0,
        open=1,
        high=2,
        low=3,
        close=4,
        volume=5,
        openinterest=-1,
    )
    cerebro.adddata(data)
    cerebro.broker.setcash(INIT_CASH)
    print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.run()
    print("Final Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.plot(figsize=(30, 15))
Exemple #18
0
import backtrader as bt
import backtrader
import backtrader.feeds as btfeeds
import backtrader.indicators as btind
from strategies import *

cerebro = bt.Cerebro()
cerebro.addindicator(VolatilitySwitch)
cerebro.addindicator(VolumeOsc, fastPeriod=14, slowPeriod=21)
cerebro.addindicator(AbsoluteStrengthOscillator)

cerebro.adddata(
    btfeeds.GenericCSVData(dataname='stocks/2020/TTD.csv',
                           dtformat=('%Y-%m-%d'),
                           datetime=0,
                           open=1,
                           high=2,
                           low=3,
                           close=4,
                           volume=6))

cerebro.run()
cerebro.plot()
    # Arrays with possible values can be assigned for each parameter
    strats = cerebro.optstrategy(CorrelationStrategy,
                                 period=15,
                                 bol_k_up=20,
                                 bol_k_down=25,
                                 bol_k_close=range(1, 30, 5),
                                 th_pear=49,
                                 sl_per=range(-22, -1, 5),
                                 tp_per=range(1, 22, 5),
                                 money_k=10,
                                 period_close=75,
                                 prolong=2.3)

    # Order of stocks should be the same in both files
    data_f = btfeeds.GenericCSVData(dataname='NOC_10.csv',
                                    openinterest=-1,
                                    dtformat="%Y-%m-%d",
                                    tmformat=-1)
    data_s = btfeeds.GenericCSVData(dataname='LMT_10.csv',
                                    openinterest=-1,
                                    dtformat="%Y-%m-%d",
                                    tmformat=-1)

    cerebro.adddata(data_f)
    cerebro.adddata(data_s)

    cerebro.broker.setcash(10000)
    # Sample commission from interactive broker pro
    cerebro.broker.setcommission(commission=0.0005, interest=0.0269)

    # Can't execute deals with volume bigger then 1% of market volume during that day
    filler = bt.broker.fillers.FixedSize()
Exemple #20
0
                                                trade.data._name,
                                                round(trade.pnl,2),
                                                round(trade.pnlcomm,2)))


if __name__ == '__main__':
    cerebro = bt.Cerebro()
    cerebro.addstrategy(WinnersLosersStrategy)
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())

    for symbol in assets:
        path = "{}_Intraday_Training".format(symbol)
        data = btfeeds.GenericCSVData(
            dataname='../Data/{}.csv'.format(path),
            nullvalue=0.0,
            dtformat=('%Y-%m-%d'),
            datetime=0,
            high=2,
            low=3,
            open=1,
            close=4,
            volume=5,
            openinterest=-1
        )
        cerebro.adddata(data, name=symbol)

    cerebro.broker.set_cash(10000)
    cerebro.broker.setcommission(commission=0.001)
    cerebro.run()
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
    cerebro.plot()
# 최초금액
start_value = 100000000.0
# 일일 Debug모드
debug_mode = True
'''
환경세팅 - END
'''

cerebro = bt.Cerebro()  # create a "Cerebro" engine instance

data = btfeed.GenericCSVData(dataname="D:\\cpbyjjun\\data\\A122630.csv",
                             fromdate=datetime.datetime(2010, 3, 1),
                             todate=datetime.datetime(2020, 9, 15),
                             nullvalue=0.0,
                             dtformat=('%Y%m%d'),
                             datetime=0,
                             open=1,
                             high=2,
                             low=3,
                             close=4,
                             volume=6,
                             openinterest=-1)

cerebro.adddata(data)

cerebro.broker.setcash(start_value)  # 초기 자본 설정
cerebro.broker.setcommission(commission=0.003)  # 매매 수수료는 0.3% 설정
cerebro.addstrategy(TestStrategy)  # 자신만의 매매 전략 추가
cerebro.run()  # 백테스팅 시작
cerebro.plot()  # 그래프로 보여주기

printResult()
if __name__ == '__main__':
    # Create a cerebro entity
    cerebro = bt.Cerebro()

    # Add a strategy
    cerebro.addstrategy(RSIStrat)

    data = btfeeds.GenericCSVData(
    dataname='../data/bitmex/XBTUSD.csv',

    fromdate=datetime.datetime(2018, 2, 2, 0, 00, 0),
    todate=datetime.datetime(2018, 7, 7, 23, 00, 0),

    nullvalue=0.0,

    dtformat=('%Y-%m-%d %H:%M:%S'),

    datetime=1, # count index
    open=2,
    high=3,
    low=4,
    close=5,
    volume=6
)


    # Add the Data Feed to Cerebro
    cerebro.adddata(data)

    # Set our desired cash start
    cerebro.broker.setcash(1.0)
            self.data0.close[0],
        )


# Create a cerebro entity
cerebro = bt.Cerebro(stdstats=False)

# Add a strategy
cerebro.addstrategy(testStrategy)

# Load the Data
datapath = './ticksample.csv'

data = btfeeds.GenericCSVData(
    dataname=datapath,
    dtformat='%Y-%m-%dT%H:%M:%S.%f',
    timeframe=bt.TimeFrame.Ticks,
)

# Handy dictionary for the argument timeframe conversion
tframes = dict(ticks=bt.TimeFrame.Ticks,
               microseconds=bt.TimeFrame.MicroSeconds,
               seconds=bt.TimeFrame.Seconds,
               minutes=bt.TimeFrame.Minutes,
               daily=bt.TimeFrame.Days,
               weekly=bt.TimeFrame.Weeks,
               monthly=bt.TimeFrame.Months)

# Resample the data
cerebro.resampledata(
    data,
Exemple #24
0
# data = btfeeds.YahooFinanceCSVData(
#     dataname=datapath,
#     reversed=True,
#     fromdate=datetime.datetime(2015, 1, 1),
#     todate=datetime.datetime.now(),
#     timeframe=bt.TimeFrame.Days
#     )

data = btfeeds.GenericCSVData(dataname='datasets/MGLU3.M15.csv',
                              reversed=False,
                              fromdate=datetime.datetime(2020, 2, 1),
                              todate=datetime.datetime(2020, 2, 8),
                              nullvalue=0.0,
                              dtformat=('%Y-%m-%d %H:%M:%S'),
                              datetime=0,
                              open=1,
                              high=2,
                              low=3,
                              close=4,
                              volume=5,
                              openinterest=None)

if __name__ == '__main__':
    cerebro = bt.Cerebro()
    cerebro.adddata(data)
    cerebro.broker.setcash(100000.0)
    cerebro.addsizer(bt.sizers.FixedSize, stake=1000)
    cerebro.addstrategy(BUY123_STRETEGY)
    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
    cerebro.run()
Exemple #25
0
# Create a cerebro entity
cerebro = bt.Cerebro()

# Add a strategy
cerebro.addstrategy(TestStrategy)
cerebro.addsizer(bt.sizers.FixedSize, stake=STAKE)

# Create a Data Feed
data = btfeeds.GenericCSVData(dataname=PRICES_PATH,
                              timeframe=bt.TimeFrame.Ticks,
                              nullvalue=0.0,
                              datetime=0,
                              time=1,
                              dtformat='%Y.%m.%d',
                              tmformat='%H:%M:%S.%f',
                              high=4,
                              low=4,
                              open=4,
                              close=4,
                              volume=-1,
                              openinterest=-1,
                              separator='\t')

# Add the Data Feed to Cerebro
cerebro.replaydata(data, timeframe=bt.TimeFrame.Minutes, compression=1)
cerebro.replaydata(data, timeframe=bt.TimeFrame.Minutes, compression=5)
cerebro.replaydata(data, timeframe=bt.TimeFrame.Minutes, compression=60)
cerebro.replaydata(data, timeframe=bt.TimeFrame.Days, compression=1)
#cerebro.replaydata(data, timeframe=bt.TimeFrame.Weeks, compression=1)

# Set our desired cash start
Exemple #26
0
                self.order = self.sell()

if __name__ == '__main__':
    cerebro = bt.Cerebro()
    cerebro.addstrategy(TestStrategy)
    datapath = os.path.abspath(
        os.getcwd() + '/BTC_' +
        str(datetime.datetime.now().strftime("%Y_%m_%d")))

    # Create a Data Feed
    data = btfeeds.GenericCSVData(dataname=datapath,
                                  fromdate=datetime.datetime(2018, 1, 1),
                                  dtformat=('%Y-%m-%d %H:%M:%S'),
                                  datetime=0,
                                  high=2,
                                  low=3,
                                  open=1,
                                  close=4,
                                  volume=5,
                                  openinterest=-1,
                                  timeframe=bt.TimeFrame.Minutes,
                                  compression=30)

    cerebro.adddata(data)

    cerebro.broker.setcash(1000.0)

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

    cerebro.broker.setcommission(commission=0.005)

    print('Starting Balance: %.2f' % cerebro.broker.getvalue())
Exemple #27
0
    def run_test(self,
                 data_file_list,
                 strategy_to_test,
                 backtesting_parameters,
                 analysis_parameters,
                 risk_models,
                 analyzers=[],
                 **kwargs):
        """
        Run method for the wrapper which wrap the ASTA-Framework structure to backtrader structure.
        :param analysis_parameters: dict with analysis parameters for strategy
        :param strategy_to_test: name of the strategy as string
        :param data_file_list: a list with files to read as string
        :param backtesting_parameters: Dict with parameters for testing, the Key "strategy_to_test" contains the strategy class to test.
        :param analyzers: List with class of btanalyzer, ex.: [btanalyzer.TradeAnalyzer]
        :param risk_models: other testing relevant parameters as dict
        :return: backtesting_result_instance final instance, backtrader test result
        """
        cerebro = bt.Cerebro()

        # add the backtrader strategy wrapper, real strategy will be build there with the backtesting_parameters dict
        # backtesting_result_instance.addstrategy(BacktraderStrategyWrapper, all_parameter, news_data)
        cerebro.addstrategy(BacktraderStrategyWrapper,
                            strategy_to_test=strategy_to_test,
                            backtesting_parameters=backtesting_parameters,
                            analysis_parameters=analysis_parameters,
                            risk_model=risk_models,
                            status_update=False,
                            **kwargs)

        # load the data from given file list and add it to backtrader instance
        if isinstance(data_file_list, list):
            for file_path in data_file_list:
                # TODO warum string?
                if isinstance(file_path, str):
                    stock_name = basename(file_path)
                    data = btfeeds.GenericCSVData(
                        name=stock_name,
                        dataname=file_path,
                        dtformat=GlobalVariables.get_stock_data_dtformat(),
                        nullvalue=0.0,
                        datetime=0,
                        open=1,
                        high=2,
                        low=3,
                        close=4,
                        volume=5,
                        openinterest=-1)
                    cerebro.adddata(data, name=data._name)
                else:
                    # compatibility for backtrader pandas data feed
                    cerebro.adddata(file_path, name=file_path._name)

        else:
            raise NotImplementedError("Data must be a list")

        # Set our desired cash start
        cerebro.broker.setcash(backtesting_parameters['initial_cash'])

        for analyzer in analyzers:
            cerebro.addanalyzer(analyzer)

        # Set the commission
        # https://www.backtrader.com/docu/commission-schemes/commission-schemes.html
        # 0.5% of the operation value --> 2500 € --> 12.5 per Buy/Sell
        cerebro.broker.setcommission(
            commission=backtesting_parameters['trade_commission_percent'])
        # Print out the starting conditions
        logger.info('Starting Portfolio Value: %.2f' %
                    cerebro.broker.getvalue())
        logger.info('--------------------')

        backtest_result = cerebro.run()
        analyzers = backtest_result[0].analyzers

        for analyzer in analyzers:
            test = analyzer.get_analysis()
            logger.info(str(analyzer) + ": " + str(test))

        # Print out the final result
        logger.info('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

        return cerebro, backtest_result
Exemple #28
0
        cerebro = bt.Cerebro()
        cerebro.addstrategy(strat)

        cerebro.addanalyzer(bt.analyzers.AnnualReturn)
        cerebro.addanalyzer(bt.analyzers.DrawDown)
        cerebro.addanalyzer(bt.analyzers.SharpeRatio,
                            annualize=True,
                            riskfreerate=0.01)

        # add data
        for filename in stocks:
            cerebro.adddata(
                btfeeds.GenericCSVData(dataname=dir + '/' + filename,
                                       dtformat=('%Y-%m-%d'),
                                       datetime=0,
                                       open=1,
                                       high=2,
                                       low=3,
                                       close=4,
                                       volume=6))

        # run stretegy and get stats
        results = cerebro.run()[0]
        sharpes.append(results.analyzers[2].get_analysis()['sharperatio'])
        if sharpes[-1] is None: sharpes[-1] = 0
        returns = results.analyzers[0].rets
        cagrs.append(sum(returns) / len(returns))
        maxdrawdowns.append(
            results.analyzers[1].get_analysis()['max'].drawdown / 100)
        if maxdrawdowns[-1] == 0: maxdrawdowns[-1] = 0.0001
        romads.append(cagrs[-1] / maxdrawdowns[-1])
Exemple #29
0
max = 0

for ma1 in range(5, 25, 2):
    for ma2 in range(8, 50, 3):
        for atr in [x * 0.1 for x in range(0, 11, 5)]:
            if (ma1 < ma2):
                default_value = 0
                strategy_value = 0
                for coin in coins:
                    data = btfeeds.GenericCSVData(
                        dataname="market_data/" + coin + "/" +
                        "1h?09-01-2017?01-01-2018.txt",
                        datetime=0,
                        open=1,
                        high=2,
                        low=3,
                        close=4,
                        volume=5,
                        openinterest=-1,
                        dtformat='%Y-%m-%d %H:%M:%S',
                        timeframe=bt.TimeFrame.Ticks,
                        nullvalue=0.0)
                    # print(data.params.dataname)
                    #
                    # default_cerebro = bt.Cerebro()
                    # default_cerebro.addstrategy(Strategy.Default)
                    # default_cerebro.broker.setcash(1000000.0)
                    # default_cerebro.adddata(data)
                    # default_cerebro.addsizer(bt.sizers.PercentSizer, percents=99)
                    # default_cerebro.broker.setcommission(commission=0.002)
                    # default_cerebro.run()
Exemple #30
0

class SmaCross(bt.SignalStrategy):
    params = (
        ('pfast', 10),
        ('pslow', 30),
    )

    def __init__(self):
        sma1, sma2 = bt.ind.SMA(period=self.p.pfast), bt.ind.SMA(
            period=self.p.pslow)
        self.signal_add(bt.SIGNAL_LONG, bt.ind.CrossOver(sma1, sma2))


cerebro = bt.Cerebro()

data = btfeeds.GenericCSVData(
    dataname='feeds/NIO.csv',
    #dataname='feeds/sin.csv',
    fromdate=datetime(2020, 1, 1),
    todate=datetime(2020, 7, 1),
    nullvalue=0.0,
    dtformat=('%Y-%m-%d'),
    datetime=0,
    close=4,
)

cerebro.adddata(data)
cerebro.addstrategy(SmaCross)
cerebro.run()
cerebro.plot()