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

最新文章

  1. Angular.element和$document的使用方法分析,代替jquery
  2. linux下安装kears
  3. Futoshiki求解
  4. Ghostscript命令实践
  5. 02_setter注入
  6. kubuntu添加windows字体
  7. jmeter系列-------脚本调试
  8. 浅谈PHP7的新特性
  9. MYSQL之视图、触发器、存储过程、函数、事物、数据库锁和数据库备份
  10. range与enumerate的区别
  11. tensorflow激励函数-【老鱼学tensorflow】
  12. eclipse的基本使用和配置
  13. git与eclipse集成之代码冲突与解决
  14. 【splunk】按时间统计并找到异常值
  15. 手机计算器1+1=2---Appium自动化
  16. 岭回归和Lasso回归以及norm1和norm2
  17. T-SQL 事务2
  18. mysql 5.7 基于GTID 主从同步的1236故障处理(其它事务故障等同)
  19. Perforce-Server迁移
  20. Excel实现二级菜单联动

热门文章

  1. TortoiseGit (小乌龟安装配置及使用)
  2. gin模板语法
  3. 结合商业项目深入理解Go知识点
  4. python网络爬虫数据解析之正则
  5. Linux c 程序自动启动自己
  6. 【LeetCode链表#9】图解:两两交换链表节点
  7. 算法之Floyd-Warshall算法【c++】【图论】【最短路】
  8. 複合語句塊——關於while循環的
  9. strapi系列-如何创建一个定时任务-Cron Jobs
  10. 初探富文本之CRDT协同算法