BackTrader 简单BTC的SMA15回测DEMO

import time
import requests
import json
import csv
from requests.packages.urllib3 import disable_warnings
disable_warnings()
#BTC历史价格获取
if __name__ == '__main__':


    time_stamp = int(time.time())
    print(f"Now timestamp: {time_stamp}")
    # 1367107200
    request_link = f"https://web-api.coinmarketcap.com/v1/cryptocurrency/ohlcv/historical?convert=USD&slug=bitcoin&time_end={time_stamp}&time_start=1367107200"
    print("Request link: " + request_link)
    r = requests.get(url = request_link,timeout=120,verify=False)
    #print(r.content)
    # 返回的数据是 JSON 格式,使用 json 模块解析
    content = json.loads(r.content)
    #print(type(content))
    quoteList = content['data']['quotes']
    #print(quoteList)

    with open('BTC.csv','w' ,encoding='utf8',newline='') as f:
        csv_write = csv.writer(f)
        csv_head = ["Date","Open","High","Low","Close","Volume"]
        csv_write.writerow(csv_head)

        for quote in quoteList:
            quote_date = quote["time_open"][:10]
            open_price = "{:.2f}".format(quote["quote"]["USD"]["open"])
            high_price = "{:.2f}".format(quote["quote"]["USD"]["high"])
            low_price = "{:.2f}".format(quote["quote"]["USD"]["low"])
            close_price = "{:.2f}".format(quote["quote"]["USD"]["close"])
            quote_volume = "{:.2f}".format(quote["quote"]["USD"]["volume"])
            csv_write.writerow([quote_date, open_price, high_price,low_price ,close_price ,quote_volume])
    print('over')

  

import backtrader as bt
import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
import numpy as np
#talib
class MyStrategy(bt.Strategy):
    def __init__(self):
        self.dataclose = self.data0.close
        self.order = None
        self.buyprice = None
        self.buycomm = None
        self.sma = bt.indicators.MovingAverageSimple(self.data0,period=15)
        # self.macd = bt.indicators.MACD(self.data0,period_me1=12,period_me2=26,period_signal=9)
        # self.boll = bt.indicators.BollingerBands(self.data0,period=21)
        # self.mcross = bt.indicators.CrossOver(self.macd.macd, self.macd.signal)
    def next(self):

        if not self.position:
            if self.dataclose[0] > self.sma[0]:
                self.buy()
        else:
            if self.dataclose[0] > self.sma[0]:
                self.close()

        # if not self.position:
        #     if self.mcross:
        #         if


    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            return
        if order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    'BUY EXECUTED, Price: % .2f, Cost: % .2f, Comm % .2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))
                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            else:
                self.log(
                    'SELL EXECUTED, Price: % .2f, Cost: % .2f, Comm % .2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))
                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            self.bar_executed = len(self)
        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('Order Canceled/Margin/Rejected')
        self.order = None

    def notify_trade(self, trade):
        if not trade.isclosed:
            return
        self.log(' OPERATION PROFIT, GROSS %.2f, NET %.2f' %
             (trade.pnl,trade.pnlcomm))
    def log(self,txt,dt=None,doprint=True):
        if doprint:
            dt = dt or self.datas[0].datetime.date(0)
            print('%s, %s' % (dt.isoformat(), txt))



if __name__ == '__main__':
    cerebro = bt.Cerebro()
    dataframe = pd.read_csv('BTC.csv')
    dataframe['Datetime'] = pd.to_datetime(dataframe['Date'])
    dataframe.set_index('Datetime',inplace=True)
    data_btc = bt.feeds.PandasData(dataname=dataframe,timeframe = bt.TimeFrame.Days)
    #timeframe = bt.TimeFrame.Days
    cerebro.adddata(data_btc)

    cerebro.addstrategy(MyStrategy)
    cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name= 'SharpeRatio')
    cerebro.addanalyzer(bt.analyzers.DrawDown ,_name= 'DrawDown')

    cerebro.broker.set_cash(10000)
    cerebro.broker.setcommission(0.001)
    cerebro.addsizer(bt.sizers.PercentSizer,percents = 90)

    result = cerebro.run()
    print('夏普比率:',result[0].analyzers.SharpeRatio.get_analysis()['sharperatio'])
    print('最大回撤:',result[0].analyzers.DrawDown.get_analysis()['max']['drawdown'])
    cerebro.plot()

  来源:https://www.bilibili.com/video/BV1QR4y147rS?spm_id_from=333.1007.top_right_bar_window_history.content.click&vd_source=c81b130b6f8bb3082bdb42226729d69c

posted @ 2023-02-21 11:33  冷光清坠落  阅读(99)  评论(0编辑  收藏  举报