首页 > 其他分享 >BackTrader 简单BTC的SMA15回测DEMO

BackTrader 简单BTC的SMA15回测DEMO

时间:2023-02-21 11:47:34浏览次数:46  
标签:SMA15 BackTrader DEMO self bt 2f quote price order

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

标签:SMA15,BackTrader,DEMO,self,bt,2f,quote,price,order
From: https://www.cnblogs.com/cuinima/p/16427974.html

相关文章

  • 爬虫利用bs4解析练习demo
    同样也是爬取新闻页的简要信息importrequestsfrombs4importBeautifulSoupBase_url="https://news.cnblogs.com"Base_path="/n/page/"headers={"User-......
  • 简单的python格网算法算数据密集度demo
    #格网算法计算数据集区域数据密集度importtimeimportrandomimportnumpyasnpimportpandasaspd#模拟数据集defcreate_data():data_x=[]data_y......
  • 爬虫利用Xpath解析练习demo
    爬取新闻页的简要信息importrequestsfromlxmlimportetreefromlxml.etreeimport_ElementBase_url="https://news.cnblogs.com"Base_path="/n/page/"heade......
  • 利用php爬虫querylist框架 监听CSDN 关注博主的文章,并发送邮件php爬虫Demo
    有时候挺喜欢一个人的csdn里面的文章,但是又想第一时间知道更新了什么,新鲜内容。所以做了一个极其简单的,爬ssdn网站的小工具,能实现功能即可。后面可以新增规则,监听官方网站的......
  • scout-elasticsearch-driver + laravel Demo学习
    项目地址:​​https://github.com/yb19890724/laravel-es​​1。在本地穿件数据库,修改.env的信息我的env文件​​点击下载​​2。env中配置es的地址。3.根目录下执行compo......
  • egg.js. demo
    丑团git前端expo​​​https://gitee.com/honbingitee/ugly-tuan-expo​​​后端egg.js​​https://gitee.com/honbingitee/ugly-tuan-egg​​/*eslint-disableinde......
  • fastapi_sqlalchemy_mysql_rbac_jwt_gooddemo
    /Users//codelearn/fastapi_sqlalchemy_mysql_01/init_test_data.py#!/usr/bin/envpython3#-*-coding:utf-8-*-importasynciofromemail_validatorimportEmai......
  • Dapr Workflow构建块的.NET Demo
    Dapr1.10版本中带来了最有亮点的特性就是工作流构建块的的发布,虽然是Alpha阶段,可以让我们尽早在应用系统中规划工作流,在使用Dapr的系统中更好的编写负责的分布式应用系......
  • SPI读写官方Demo
    //SPDX-License-Identifier:GPL-2.0-only/**SPItestingutility(usingspidevdriver)**Copyright(c)2007MontaVistaSoftware,Inc.*Copyright(c)......
  • C# 实现IP视频监控(摄像头)画面推送(简单的不能再简单的DEMO)
    最近继续在家休息,在完成上一个Python抓取某音乐网站爬虫后,琢磨着实现一个基于HTTP推送的IP视频监控,比如外出的时候,在家里开启一个监控端(摄像头+服务端),可以看到实时画面,如......