BackTrader 简单BTC的SMA15回测DEMO

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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')

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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 @   冷光清坠落  阅读(207)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示