예제 #1
0
def main():
    cerebro = bt.Cerebro()

    hist_start_date = datetime.utcnow() - timedelta(minutes=10)
    data_min = bt.feeds.CCXT(exchange='binance', symbol="BTC/USDT", name="btc_usdt_min", fromdate=hist_start_date,
                             timeframe=bt.TimeFrame.Minutes)
    cerebro.adddata(data_min)
    cerebro.addstrategy(TestStrategy)
    cerebro.run()
예제 #2
0
def connect_broker():
    apikey = 'siX-NO9IeVWstmn1zA2e904N'
    secret = 'ieEjNwz9TDAzg_B2EVkpgzkchDeNmyy9_UNB03B567Gwh0A_'

    cerebro = bt.Cerebro(quicknotify=True)

    # Add the strategy
    cerebro.addstrategy(TestStrategy)

    # Create our store
    config = {'apiKey': apikey, 'secret': secret, 'enableRateLimit': True}

    # IMPORTANT NOTE - Kraken (and some other exchanges) will not return any values
    # for get cash or value if You have never held any LTC coins in your account.
    # So switch LTC to a coin you have funded previously if you get errors
    store = CCXTStore(exchange='bitmex',
                      currency='BTC',
                      config=config,
                      retries=5,
                      debug=False,
                      testnet=True)

    print("I am here")
    print(store.exchange.urls)

    broker = store.getbroker()
    cerebro.setbroker(broker)

    # Get our data
    # Drop newest will prevent us from loading partial data from incomplete candles
    hist_start_date = datetime.utcnow() - timedelta(minutes=50)
    data = store.getdata(dataname='BTC/USD',
                         name="BTCUSD",
                         timeframe=bt.TimeFrame.Minutes,
                         fromdate=hist_start_date,
                         compression=1,
                         ohlcv_limit=50,
                         drop_newest=True)  #, historical=True)

    # Add the feed
    cerebro.adddata(data)

    # Run the strategy
    cerebro.run()
예제 #3
0
                self.sell(size=100)


#Variable for our starting cash
startcash = 10000

if __name__ == '__main__':
    cerebro = bt.Cerebro()

    hist_start_date = datetime.utcnow() - timedelta(minutes=1000)
    data_min = bt.feeds.CCXT(exchange='binance',
                             symbol="BTC/USDT",
                             name="btc_usd_min",
                             fromdate=hist_start_date,
                             todate=datetime.utcnow(),
                             timeframe=bt.TimeFrame.Minutes)
    cerebro.adddata(data_min)
    cerebro.broker.setcash(startcash)
    cerebro.addstrategy(firstStrategy)
    cerebro.run()

    # Get final portfolio Value
    portvalue = cerebro.broker.getvalue()
    pnl = portvalue - startcash

    # Print out the final result
    print('Final Portfolio Value: ${}'.format(portvalue))
    print('P/L: ${}'.format(pnl))

    # Finally plot the end results
    cerebro.plot(style='candlestick')
예제 #4
0
    # Create data feeds
    data_ticks = bt.feeds.CCXT(exchange='geminy',
                               symbol='BTC/USD',
                               name="btc_usd_tick",
                               timeframe=bt.TimeFrame.Ticks,
                               compression=1,
                               config=config)
    cerebro.adddata(data_ticks)


class TestStrategy(bt.Strategy):
    def next(self):
        print('*' * 5, 'NEXT:', bt.num2date(self.data.datetime[0]),
              self.data._name, self.data.open[0], self.data.high[0],
              self.data.low[0], self.data.close[0], self.data.volume[0],
              bt.TimeFrame.getname(self.data._timeframe), len(self.data))


if __name__ == '__main__':
    cerebro = bt.Cerebro()

    hist_start_date = datetime.utcnow() - timedelta(minutes=10)
    data_min = bt.feeds.CCXT(exchange='bitmex',
                             symbol="BTC/USD",
                             name="btc_usd_min",
                             fromdate=hist_start_date,
                             timeframe=bt.TimeFrame.Minutes)
    cerebro.adddata(data_min)
    cerebro.addstrategy(TestStrategy)
    cerebro.run()
예제 #5
0
    df = ts.pro_bar(ts_code=code,
                    adj='qfq',
                    start_date=start_time,
                    end_date=end_time)
    df.index = pd.to_datetime(df.trade_date)
    df.sort_index(ascending=True, inplace=True)
    df['volume'] = df['vol']
    df['openinterest'] = 0
    df = df[['open', 'high', 'low', 'close', 'volume', 'openinterest']]
    return df


if __name__ == '__main__':
    cerebro = bt.Cerebro()

    cerebro.addstrategy(TestStrategy, maperiod5=5, maperiod30=30)

    cerebro.broker.setcash(100000.0)
    cerebro.broker.setcommission(commission=0.0005)
    # Add a FixedSize sizer according to the stake
    cerebro.addsizer(bt.sizers.FixedSize)

    data = bt.feeds.PandasData(dataname=get_data('688158.SH'))

    cerebro.adddata(data)

    # 添加分析对象
    cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name="sharpe")
    cerebro.addanalyzer(bt.analyzers.AnnualReturn, _name="AR")
    cerebro.addanalyzer(bt.analyzers.DrawDown, _name="DD")
    cerebro.addanalyzer(bt.analyzers.Returns, _name="RE")
예제 #6
0
    #         if order.isbuy():
    #             self.log('BUY EXECUTED, %.2f' % order.executed.price)
    #         elif order.issell():
    #             self.log('SELL EXECUTED, %.2f' % order.executed.price)
    #
    #         self.bar_executed = len(self)
    #     elif order.status in [order.Canceled, order.Margin, order.Rejected]:
    #         self.log('Order Canceled/Margin/Rejected')
    #     # Write down: no pending order
    #         self.order = None

    def next(self):
        self.log(f"{self.close[0]}-{self.plFound[0]},{self.phFound[0]}")


if __name__ == '__main__':
    cerebro = bt.Cerebro()
    # hist_start_data=datetime.utcnow()-timedelta(days=365)
    # data_min=bt.feeds.CCXT(exchange='bitmex',symbol="BTC/USD",name="btc_usd_min",fromdate=hist_start_data,todate=datetime.utcnow(),timeframe=bt.TimeFrame.Days)
    # cerebro.adddata(data_min)
    modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
    datapath = os.path.join(modpath, '.\hist_data\BINANCE_BTCUSDT.csv')
    data = bt.feeds.BacktraderCSVData(dataname=datapath,
                                      timeframe=bt.TimeFrame.Minutes)
    cerebro.adddata(data)
    cerebro.addstrategy(TrbStrategy)
    cerebro.broker.setcash(10000)
    cerebro.broker.setcommission(commission=0.001)
    cerebro.run()
    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
예제 #7
0
    df['openinterest'] = 0
    df = df[['open', 'high', 'low', 'close', 'volume', 'openinterest']]
    return df


if __name__ == "__main__":
    cerebro = bt.Cerebro()

    st_number = '688158.SH'
    df = get_data(st_number)

    data = bt.feeds.PandasData(dataname=df)

    cerebro.adddata(data)

    cerebro.addstrategy(SMACross)
    cerebro.addsizer(bt.sizers.AllInSizerInt)
    cerebro.broker.set_cash(100000)

    cerebro.addanalyzer(bt.analyzers.AnnualReturn, _name="annual_returns")
    cerebro.addanalyzer(bt.analyzers.DrawDown, _name="draw_down")
    cerebro.addanalyzer(bt.analyzers.Transactions, _name="transactions")

    results = cerebro.run()

    # 打印Analyzer结果到日志
    for result in results:

        annual_returns = result.analyzers.annual_returns.get_analysis()
        log.info("annual returns:")
        for year, ret in annual_returns.items():