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

BackTrader 简单BTC的SMA15回测DEMO的更多相关文章

  1. OnePy--构建属于自己的量化回测框架

    本文主要记录我构建量化回测系统的学习历程. 被遗弃的项目:Chandlercjy/OnePy_Old 新更新中的项目:Chandlercjy/OnePy 目录 1. 那究竟应该学习哪种编程语言比较好呢 ...

  2. 如何使用TradingView(TV)回测数字货币交易策略

    更多精彩内容,欢迎关注公众号:数量技术宅.想要获取本期分享的完整策略代码,请加技术宅微信:sljsz01 TradingView平台简介 前段时间,有粉丝找到技术宅,表示他有一个常用的交易平台,叫做T ...

  3. WeQuant比特币交易策略回测记录

    程序参数 PARAMS = { "start_time": "2017-02-01 00:00:00", "end_time": " ...

  4. 量化投资策略:常见的几种Python回测框架(库)

    量化投资策略:常见的几种Python回测框架(库) 原文地址:http://blog.csdn.net/lawme/article/details/51454237 本文章为转载文章.这段时间在研究量 ...

  5. 回测框架pybacktest简介(一)

    pybacktest 教程 本教程让你快速了解 pybacktest's 的功能.为此,我们回测精典交易策略移动平均线MA交叉. MA快线上穿慢线时,买进做多 MA快线下穿慢线时,卖出做空 进场规则, ...

  6. 回测框架pybacktest简介(二)

    pybacktest 的疑点 第(一)节“教程”原文,是用 ipython notebook 写成,程序代码是一些片段组成. 为了阅读方便,合并在一起. 本文转载于:http://blog.csdn. ...

  7. WeQuant教程—1.3 利用回测工具降低交易风险

    量化系统投入实际使用之前,人们会希望提前测试交易的效果.这个期间往往涉及代码的改动和参数的调整.最常见的做法是将历史数据输入量化系统,让量化系统根据既定的交易逻辑进行操作,观察和分析交易结果,找到问题 ...

  8. FMZ发明者量化平台回测机制说明

    原文连接:https://www.fmz.com/digest-topic/4009 大部分策略在实盘之前都需要回测进行验证,FMZ支持部分品种数字货币现货.期货和永续合约,以及商品期货所有品种.但发 ...

  9. 手把手教你用Python搭建自己的量化回测框架【均值回归策略】

    手把手教你用Python搭建自己的量化回测框架[均值回归策略] 引言 大部分量化策略都可以归类为均值回归与动量策略.事实上,只有当股票价格是均值回归或趋势的,交易策略才能盈利.否则,价格是随机游走的, ...

  10. 用Python编写的第一个回测程序

    用Python编写的第一个回测程序 2016-08-06 def savfig(figureObj, fn_prefix1='backtest8', fn_prefix2='_1_'): import ...

随机推荐

  1. vivo 低代码平台【后羿】的探索与实践

    作者:vivo 互联网前端团队- Wang Ning 本文根据王宁老师在"2022 vivo开发者大会"现场演讲内容整理而成.公众号回复[2022 VDC]获取互联网技术分会场议题 ...

  2. java中String类型的相关知识的简单总结

    java中String类型的相关知识总结 一.常用方法: 1.构造方法: byte数组 可指定offset和length 可指定charset char数组 可指定offset和count 字符序列 ...

  3. ArcGIS工具 - 按要素裁切数据库

    在GIS处理数据中,经常需要分图,将整个任务区划分成若干块,由不同的人协作完成.为了节省分图裁切时间,减少人员操作失误,为源GIS专门制作了按要素裁切数据库工具,以提高数据生产效率. 需求描述 裁切单 ...

  4. ArcGIS工具 - 导出数据库结构

    为了保证数据的一致性,数据库结构的正确性在数据库建设和管理过程中显示十分重要,在各个地理信息类项目的技术规定中都对空间数据库的结构进行明确和详细的定义,有时为了方便检查或文档编辑需要将数据结构导出,为 ...

  5. 如何在 Nuxt 3 中使用 wavesurfer.js

    安装 wavesurfer.js 在项目中安装 wavesurfer.js npm install --save wavesurfer.js 常规方式引入 如果你的根目录中没有 components ...

  6. Debian 软件包管理

    Debian 软件包管理 Debian 软件包管理 基础软件包管理知识 sources.list 文件格式 新手建议 档案库临时小故障 软件包依赖关系 APT 进行软件包管理 基本操作 软件包管理操作 ...

  7. Array list练习

    Array list练习 数据添加到集合 生成6个1~33之间的随机整数,添加到集合,并遍历 public class Test01ArrayList { public static void mai ...

  8. 2023牛客寒假算法基础集训营5 A-L

    比赛链接 A 题解 知识点:前缀和,二分. 找到小于等于 \(x\) 的最后一个物品,往前取 \(k\) 个即可,用前缀和查询. 时间复杂度 \(O(n + q\log n)\) 空间复杂度 \(O( ...

  9. 浅谈Pytest中的warning处理

    浅谈Pytest中的warning处理 没有处理warning 我们写一个简单的测试 import pytest def test_demo(): import warnings warnings.w ...

  10. Javaweb-Tomcat(安装+配置环境)

    Tomcat跟着教程,但是在bin目录下点击startup只能闪退的总结 1.先下载 直接搜tomcat下载就可以了(free) 2.解压到你想要的文件中 3.直接进入bin目录,找startup.b ...