Python分析统计近30天内虚拟币合约爆仓造成的损失金额

选题背景

   近日国内针对虚拟币开始了严厉监管,监管部门态度十分明确,一方面维护正常经济金融秩序,另一方面保护人民群众财产安全,同时要求各大银行以及支付平台严查虚拟币交易,这无疑是保护人民财产安全的重要保障之一。

   比特币从诞生到今天已经有11年了,在其光鲜亮丽的背后隐藏这大量的危害,其中最主要的就是匿名性和价格波动,前者是的交易无法追踪则很多犯罪的关键线索无法被找到,后者使得进入市场的投资者面临一夜清空的危险。本项目将爬取全球主流交易所”爆仓”数据,以分析虚拟币的涨跌对虚拟币”合约爆仓”的影响,同时统计”爆仓”导致的虚拟币投资者财产损失,以告诫虚拟币的危害性。

 

 

 

 

 

爬虫项目的设计方案

1、爬虫名称

比特币合约爆仓数据的爬取与可视化分析

2、爬虫内容与数据分析特征

爬取最近30天内比特币价格、总爆仓金额、各大交易所总爆仓金额

3、方案概述

分析网站结构,找到需要爬取的数据位置以及来源

 

网站结构分析与获取数据来源

从主页中我们找到了需要爬取的内容

 

由于其数据是实时更新的,这需要我们检查改网站的Network下的XHR文件来确定数据来源

 

分析数据文件

从得到的数据文件中,我们可以得到89天内所有的数据

 

爬虫程序设计

1.爬取数据

从该json文件中提取数据并保存到变量中

 1 #导包
 2 import requests    #网页请求
 3 import jsonpath    #json解析
 4 import json        #json操作
 5 from datetime import datetime
 6 from bs4 import BeautifulSoup
 7 
 8 #获取json数据中最近30天的buyVolUsd数据
 9 def getBuyVolUsd(json_dict):
10     list = []
11     a = 58
12     b = 88
13     while a < b:
14         temp = jsonpath.jsonpath(json_dict,"$.data[{b}].buyVolUsd".format(b = b))
15         intdata = int(temp[0]/10000)
16         list.append(intdata)
17         b -= 1
18     list.reverse()
19     return list
20 
21 #获取json数据中最近30天的sellVolUsd数据
22 def getSellVolUsd(json_dict):
23     list = []
24     a = 58
25     b = 88
26     while a < b:
27         temp = jsonpath.jsonpath(json_dict,"$.data[{b}].sellVolUsd".format(b = b))
28         intdata = int(temp[0]/10000)
29         list.append(intdata)
30         b -= 1
31     list.reverse()
32     return list
33 
34 #获取json数据中最近30天的Price数据
35 def getPrice(json_dict):
36     list = []
37     a = 58
38     b = 88
39     while a < b:
40         temp = jsonpath.jsonpath(json_dict,"$.data[{b}].price".format(b = b))
41         intdata = int(temp[0])
42         list.append(intdata)
43         b -= 1
44     list.reverse()
45     return list
46 
47 #设置url地址与headers参数
48 json_url = 'https://fapi.bybt.com/api/futures/liquidation/chart?symbol=ALL'
49 headers={'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Mobile Safari/537.36'}
50 #获取url地址中的json数据
51 json_data = requests.get(url=json_url,headers=headers).text
52 get_json_time = (datetime.now()).strftime('%Y-%m-%d %H:%M:%S')
53 json_dict = json.loads(json_data)    #转化为dict字典
54 #调用函数获得列表
55 buy_vol_usd = getBuyVolUsd(json_dict)
56 sell_vol_usd = getSellVolUsd(json_dict)
57 price = getPrice(json_dict)
58 print('空单爆仓金额数据',buy_vol_usd,'\n')
59 print('多单爆仓金额数据',sell_vol_usd,'\n')
60 print('BTC价格数据',price)

 

运行结果:

 

2.创建时间索引

由于原数据并未带有时间日期数据,所以需要我们手动来创建一个时间索引,我们暂时只截取最近30天的数据做分析

 1 import datetime    #时间操作
 2 
 3 #将today前30天的日期通过list返回
 4 def getAllDate(today):
 5     list = []
 6     a = 0
 7     b = 30
 8     while a < b:
 9         temp = today + datetime.timedelta(a*-1)
10         date = temp.strftime('%m/%d')
11         list.append(date)
12         a += 1
13     list.reverse()
14     return list
15 
16 #获取时间列表
17 today = datetime.date.today()
18 AllDate = getAllDate(today)
19 print(AllDate)

运行结果:

 

 

3.制成DataFrame数据表

获得了时间和数据后,我们可以简单的制作一张DataFrame表来显示一下其数据

 1 import numpy as np
 2 import pandas as pd
 3 import matplotlib.pyplot as plt
 4 plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
 5 plt.rcParams['axes.unicode_minus']=False #用来正常显示中文标签
 6 index_list = ['BTC价格','空单爆仓金额(万元)','多单爆仓金额(万元)']
 7 buy_data = buy_vol_usd
 8 sell_data = sell_vol_usd
 9 price_data = price
10 df = pd.DataFrame([price_data,buy_data,sell_data],index = index_list,columns = AllDate)
11 df

运行结果:

 

4.通过plt制成可视化柱状图

简单的数据表不是那么直观的能看出其差距所在,这时候我们就需要制成柱状图了

1 df_buy = pd.DataFrame(buy_data,AllDate)
2 df_sell = pd.DataFrame(sell_data,AllDate)
3 df_buy.plot(kind='bar',width=0.8,color='red',edgecolor='black')
4 plt.xticks(rotation=360)
5 df_sell.plot(kind='bar',width=0.8,color='green',edgecolor='black')
6 plt.xticks(rotation=360)
7 plt.rcParams.update({'figure.figsize':'18,10'})
8 plt.show()

运行结果:

 

 

 

5.合并柱状图

 1 bar_index = np.arange(30)
 2 bar_width=0.33
 3 bar1 = plt.bar(bar_index,buy_data,width=0.3,color='green',edgecolor='black',label = '空单爆仓金额(万元)')
 4 
 5 for a in bar1:
 6     height = a.get_height()
 7     plt.text(a.get_x() + a.get_width() / 2, height+3, str(height), ha="center", va="bottom")
 8     
 9 bar1 = plt.bar(bar_index+bar_width,sell_data,width=0.3,color='red',edgecolor='black',label = '多单爆仓金额(万元)')
10 
11 for a in bar1:
12     height = a.get_height()
13     plt.text(a.get_x() + a.get_width() / 2, height+3, str(height), ha="center", va="bottom")
14     
15 plt.xticks(bar_index + 3 * bar_width / 3,AllDate)
16 plt.xlabel('日期')
17 plt.ylabel('爆仓金额(万元)',rotation=360,labelpad = 50)
18 plt.legend()
19 plt.rcParams.update({'figure.figsize':'30,10'})
20 
21 
22 plt.twinx() # this is the important function
23 plt.plot(bar_index+0.151,price_data,'y')
24 plt.ylabel('BTC价格',rotation=360,labelpad = 50)
25 plt.title( '近30天爆仓金额柱状图\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
26 plt.show()

运行结果:

 

 

 从制图结果中,我们可以看到比特币的价格涨跌幅度波动很大,这使得在6/8多单爆仓金额是30天内最高的一天

 

6.制作pie饼图来查看两种爆仓的占比

 1 def getAllBuyData(data):
 2     a=0
 3     b=30
 4     temp=0
 5     while a < b:
 6         temp += data[a]
 7         a += 1
 8     return temp
 9 
10 def getAllSellData(data):
11     a=0
12     b=30
13     temp=0
14     while a < b:
15         temp += data[a]
16         a += 1
17     return temp
18 
19 def getPriceAvg(data):
20     a=0
21     b=30
22     temp=0
23     while a < b:
24         temp += data[a]
25         a += 1
26     return temp/30
27 
28 AllBuyData = getAllBuyData(buy_data)
29 AllSellData = getAllSellData(sell_data)
30 PriceAvg = getPriceAvg(price_data)
31 data_list = [AllBuyData,AllSellData]
32 
33 print('30天内空单爆仓总金额',AllBuyData)
34 print('30天内多单爆仓总金额',AllSellData)
35 print('30天内BTC平均价格',PriceAvg)
36 
37 groups = ['空单爆仓金额占比','多单爆仓金额占比']
38 plt.pie(data_list,autopct='%1.2f%%',labels=groups,explode=[0,0.007],textprops = {'fontsize': 30})
39 plt.title( '近30天爆仓金额多空占比\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
40 plt.legend(loc='upper left')
41 plt.show()

运行结果:

 

7.分析各交易所的保存数据

我们从解析的json文件中获得的数据并不只有总数据,其中还有各交易所的数据,我们也可以将它作为分析统计的对象

 1 def getExchangeBuyVolUsdData(json_dict):
 2     Bitmex = []
 3     Binance = []
 4     Okex = []
 5     Huobi = []
 6     Bybit = []
 7     FTX = []
 8     Deribit = []
 9     Bitfinex = []
10     a = 58
11     b = 88
12     while a < b:
13         Bitmex.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[0].buyVolUsd".format(b = b))[0])/10000))
14         Binance.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[1].buyVolUsd".format(b = b))[0])/10000))
15         Okex.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[2].buyVolUsd".format(b = b))[0])/10000))
16         Huobi.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[3].buyVolUsd".format(b = b))[0])/10000))
17         Bybit.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[4].buyVolUsd".format(b = b))[0])/10000))
18         FTX.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[5].buyVolUsd".format(b = b))[0])/10000))
19         Deribit.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[6].buyVolUsd".format(b = b))[0])/10000))
20         Bitfinex.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[7].buyVolUsd".format(b = b))[0])/10000))
21         b -= 1
22     Bitmex.reverse()
23     Binance.reverse()
24     Okex.reverse()
25     Huobi.reverse()
26     Bybit.reverse()
27     FTX.reverse()
28     Deribit.reverse()
29     Bitfinex.reverse()
30     return [Bitmex,Binance,Okex,Huobi,Bybit,FTX,Deribit,Bitfinex]
31 
32 ExchangeBuyVolUsdData = getExchangeBuyVolUsdData(json_dict)
33 
34 BitmexBuyVolUsdData = ExchangeBuyVolUsdData[0]
35 BinanceBuyVolUsdData = ExchangeBuyVolUsdData[1]
36 OkexBuyVolUsdData = ExchangeBuyVolUsdData[2]
37 HuobiBuyVolUsdData = ExchangeBuyVolUsdData[3]
38 BybitBuyVolUsdData = ExchangeBuyVolUsdData[4]
39 FTXBuyVolUsdData = ExchangeBuyVolUsdData[5]
40 DeribitBuyVolUsdData = ExchangeBuyVolUsdData[6]
41 BitfinexBuyVolUsdData = ExchangeBuyVolUsdData[7]
42 BuyVolUsdDataList = [BitmexBuyVolUsdData,BinanceBuyVolUsdData,OkexBuyVolUsdData,HuobiBuyVolUsdData,
43                      BybitBuyVolUsdData,FTXBuyVolUsdData,DeribitBuyVolUsdData,BitfinexBuyVolUsdData]
44 index_list = ['Bitmex','Binance','Okex','Huobi','Bybit','FTX','Deribit','Bitfinex']
45 df = pd.DataFrame(BuyVolUsdDataList,index = index_list,columns = AllDate)
46 df

运行结果:

 

 

 

8.将各大交易所爆仓数据制成折线图

 1 plt.figure(figsize=(20,10))
 2 plt.plot(AllDate,BuyVolUsdDataList[0],label = 'Bitmex空单爆仓金额(万元)',marker='s')
 3 plt.plot(AllDate,BuyVolUsdDataList[1],label = 'Binance空单爆仓金额(万元)',marker='s')
 4 plt.plot(AllDate,BuyVolUsdDataList[2],label = 'Okex空单爆仓金额(万元)',marker='s')
 5 plt.plot(AllDate,BuyVolUsdDataList[3],label = 'Huobi空单爆仓金额(万元)',marker='s')
 6 plt.plot(AllDate,BuyVolUsdDataList[4],label = 'Bybit空单爆仓金额(万元)',marker='s')
 7 plt.plot(AllDate,BuyVolUsdDataList[5],label = 'FTX空单爆仓金额(万元)',marker='s')
 8 plt.plot(AllDate,BuyVolUsdDataList[6],label = 'Deribit空单爆仓金额(万元)',marker='s')
 9 plt.plot(AllDate,BuyVolUsdDataList[7],label = 'Bitfinex空单爆仓金额(万元)',marker='s')
10 plt.ylabel('爆仓金额(万元)',rotation=360,labelpad = 50)
11 plt.xlabel('日期')
12 plt.legend()
13 
14 plt.twinx() # this is the important function
15 #绘制折线,可以有多种颜色及形状,c代表color,marker代表节点形状,ms代表marker size,label是折现名称。
16 plt.plot(AllDate,price_data,color = 'y',label = 'BTC价格',marker='o',ms=10,lw = 5,linestyle = ':')
17 plt.ylabel('BTC价格',rotation=360,labelpad = 50)
18 plt.legend(bbox_to_anchor=(1.08, 1))
19 plt.title( '近30日各大交易所空单爆仓金额\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
20 plt.show()

运行结果:

 

 

 

9.统计30天各大交易所爆仓总金额

 1 BitmexAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[0])
 2 BinanceAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[1])
 3 OkexAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[2])
 4 HuobiAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[3])
 5 BybitAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[4])
 6 FTXAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[5])
 7 DeribitAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[6])
 8 BitfinexAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[7])
 9 AllBuyVolUsdDataList = [BybitAllBuyVolUsdData,BitfinexAllBuyVolUsdData,OkexAllBuyVolUsdData,
10                         DeribitAllBuyVolUsdData,HuobiAllBuyVolUsdData,BitmexAllBuyVolUsdData,BinanceAllBuyVolUsdData,FTXAllBuyVolUsdData]
11 print('Bitmex30天空单爆仓合计',BitmexAllBuyVolUsdData,'万元($)')
12 print('Binance30天空单爆仓合计',BinanceAllBuyVolUsdData,'万元($)')
13 print('Okex30天空单爆仓合计',OkexAllBuyVolUsdData,'万元($)')
14 print('Huobi30天空单爆仓合计',HuobiAllBuyVolUsdData,'万元($)')
15 print('Bybit30天空单爆仓合计',BybitAllBuyVolUsdData,'万元($)')
16 print('FTX30天空单爆仓合计',FTXAllBuyVolUsdData,'万元($)')
17 print('Deribit30天空单爆仓合计',DeribitAllBuyVolUsdData,'万元($)')
18 print('Bitfinex30天空单爆仓合计',BitfinexAllBuyVolUsdData,'万元($)')
19 AllBuyVolUsdDataList

 运行结果:

 

10.将空单爆仓数据制成pie饼图查看占比

1 colors_list = ['#DA4453','#E9573F','#F68B42','#8CC152','#37BC9B','#3BAFDA','#4A89DC','#967ADC']
2 Buylabels_list = ['Bybit','Bitfinex','Okex','Deribit','Huobi','Bitmex','Binance','FTX']
3 plt.pie(AllBuyVolUsdDataList,autopct='%1.2f%%',startangle=90,labels = Buylabels_list,textprops = {'fontsize': 15},
4         rotatelabels=True,colors = colors_list)
5 plt.title( '近30日各大交易所空单爆仓金额占比\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
6 plt.legend(loc='upper left')
7 plt.show()

运行结果:

 

11.将多单数据制成折线图

 1 def getExchangeSellVolUsdData(json_dict):
 2     Bitmex = []
 3     Binance = []
 4     Okex = []
 5     Huobi = []
 6     Bybit = []
 7     FTX = []
 8     Deribit = []
 9     Bitfinex = []
10     a = 58
11     b = 88
12     while a < b:
13         Bitmex.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[0].sellVolUsd".format(b = b))[0])/10000))
14         Binance.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[1].sellVolUsd".format(b = b))[0])/10000))
15         Okex.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[2].sellVolUsd".format(b = b))[0])/10000))
16         Huobi.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[3].sellVolUsd".format(b = b))[0])/10000))
17         Bybit.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[4].sellVolUsd".format(b = b))[0])/10000))
18         FTX.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[5].sellVolUsd".format(b = b))[0])/10000))
19         Deribit.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[6].sellVolUsd".format(b = b))[0])/10000))
20         Bitfinex.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[7].sellVolUsd".format(b = b))[0])/10000))
21         b -= 1
22     Bitmex.reverse()
23     Binance.reverse()
24     Okex.reverse()
25     Huobi.reverse()
26     Bybit.reverse()
27     FTX.reverse()
28     Deribit.reverse()
29     Bitfinex.reverse()
30     return [Bitmex,Binance,Okex,Huobi,Bybit,FTX,Deribit,Bitfinex]
31 
32 ExchangeSellVolUsdData = getExchangeSellVolUsdData(json_dict)
33 
34 BitmexSellVolUsdData = ExchangeSellVolUsdData[0]
35 BinanceSellVolUsdData = ExchangeSellVolUsdData[1]
36 OkexSellVolUsdData = ExchangeSellVolUsdData[2]
37 HuobiSellVolUsdData = ExchangeSellVolUsdData[3]
38 BybitSellVolUsdData = ExchangeSellVolUsdData[4]
39 FTXSellVolUsdData = ExchangeSellVolUsdData[5]
40 DeribitSellVolUsdData = ExchangeSellVolUsdData[6]
41 BitfinexSellVolUsdData = ExchangeSellVolUsdData[7]
42 SellVolUsdDataList = [BitmexSellVolUsdData,BinanceSellVolUsdData,OkexSellVolUsdData,HuobiSellVolUsdData,
43                       BybitSellVolUsdData,FTXSellVolUsdData,DeribitSellVolUsdData,BitfinexSellVolUsdData]
44 
45 plt.figure(figsize=(20,10))
46 plt.plot(AllDate,SellVolUsdDataList[0],label = 'Bitmex多单爆仓金额(万元)',marker='s')
47 plt.plot(AllDate,SellVolUsdDataList[1],label = 'Binance多单爆仓金额(万元)',marker='s')
48 plt.plot(AllDate,SellVolUsdDataList[2],label = 'Okex多单爆仓金额(万元)',marker='s')
49 plt.plot(AllDate,SellVolUsdDataList[3],label = 'Huobi多单爆仓金额(万元)',marker='s')
50 plt.plot(AllDate,SellVolUsdDataList[4],label = 'Bybit多单爆仓金额(万元)',marker='s')
51 plt.plot(AllDate,SellVolUsdDataList[5],label = 'FTX多单爆仓金额(万元)',marker='s')
52 plt.plot(AllDate,SellVolUsdDataList[6],label = 'Deribit多单爆仓金额(万元)',marker='s')
53 plt.plot(AllDate,SellVolUsdDataList[7],label = 'Bitfinex多单爆仓金额(万元)',marker='s')
54 plt.ylabel('爆仓金额(万元)',rotation=360,labelpad = 50)
55 plt.xlabel('日期')
56 plt.legend()
57 
58 plt.twinx() # this is the important function
59 #绘制折线,可以有多种颜色及形状,c代表color,marker代表节点形状,ms代表marker size,label是折现名称。
60 plt.plot(AllDate,price_data,color = 'y',label = 'BTC价格',marker='o',ms=10,lw = 5,linestyle = ':')
61 plt.ylabel('BTC价格',rotation=360,labelpad = 50)
62 plt.legend(bbox_to_anchor=(1.08, 1))
63 plt.title( '近30日各大交易所多单爆仓金额占比\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
64 plt.show()

运行结果:

 

 

 

 

 

 12.统计多单爆仓金额

 1 BitmexAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[0])
 2 BinanceAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[1])
 3 OkexAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[2])
 4 HuobiAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[3])
 5 BybitAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[4])
 6 FTXAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[5])
 7 DeribitAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[6])
 8 BitfinexAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[7])
 9 AllSellVolUsdDataList = [BybitAllSellVolUsdData,BitfinexAllSellVolUsdData,OkexAllSellVolUsdData,DeribitAllSellVolUsdData,
10                          HuobiAllSellVolUsdData,BitmexAllSellVolUsdData,BinanceAllSellVolUsdData,FTXAllSellVolUsdData]
11 print('Bitmex30天多单爆仓合计',BitmexAllSellVolUsdData,'万元($)')
12 print('Binance30天多单爆仓合计',BinanceAllSellVolUsdData,'万元($)')
13 print('Okex30天多单爆仓合计',OkexAllSellVolUsdData,'万元($)')
14 print('Huobi30天多单爆仓合计',HuobiAllSellVolUsdData,'万元($)')
15 print('Bybit30天多单爆仓合计',BybitAllSellVolUsdData,'万元($)')
16 print('FTX30天多单爆仓合计',FTXAllSellVolUsdData,'万元($)')
17 print('Deribit30天多单爆仓合计',DeribitAllSellVolUsdData,'万元($)')
18 print('Bitfinex30天多单爆仓合计',BitfinexAllSellVolUsdData,'万元($)')
19 AllSellVolUsdDataList

运行结果:

 

13.将结果制成饼图

1 Selllabels_list = ['Bybit','Bitfinex','Okex','Deribit','Huobi','Bitmex','Binance','FTX']
2 plt.pie(AllSellVolUsdDataList,autopct='%1.2f%%',startangle=90,labels = Selllabels_list,textprops = {'fontsize': 15},rotatelabels=True,colors = colors_list)
3 plt.title( '近30日各大交易所多单爆仓金额占比\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
4 plt.legend(loc='upper left')
5 plt.show()

运行结果:

 

 

 

14.将多空两种数据制成合并饼图

 1 size = 0.3
 2 pie1color = ['#DA4453','#E9573F','#F68B42','#8CC152','#37BC9B','#3BAFDA','#4A89DC','#967ADC']
 3 pie2color = ['#ED5565','#FC6E51','#FFCE54','#A0D468','#48CFAD','#4FC1E9','#5D9CEC','#AC92EC']
 4 ExchangeDataPie = plt.pie(AllBuyVolUsdDataList,autopct='%1.2f%%',radius=1,startangle=90,pctdistance = 0.85,colors = pie1color,textprops = {'fontsize': 15},
 5         labels = Buylabels_list,wedgeprops=dict(width=size, edgecolor='w'),rotatelabels=True)
 6 plt.legend(loc='upper left', bbox_to_anchor=(-0.1, 1))
 7 ExchangeDataPie = plt.pie(AllSellVolUsdDataList,autopct='%1.2f%%',radius=1-size,startangle=90,pctdistance = 0.78,colors = pie2color,textprops = {'fontsize': 12},
 8         wedgeprops=dict(width=size, edgecolor='w'))
 9 plt.title( '近30日各大交易所空单与多单爆仓金额占比图\n外环:空单爆仓占比\n内环:多单爆仓占比\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
10 plt.show()

运行结果:

 

 

15.将各交易所爆仓总金额数据排序后用柱状图显示

from mpl_toolkits.axes_grid1.inset_locator import inset_axes
def getExchangeAllData(AllBuyVolUsdDataList,AllSellVolUsdDataList):
    list = []
    a = 0
    b = 8
    while a < 8:
        temp = AllBuyVolUsdDataList[a]+AllSellVolUsdDataList[a]
        list.append(temp)
        a += 1
    return list
ExchangeAllData = getExchangeAllData(AllBuyVolUsdDataList,AllSellVolUsdDataList)
ExchangeAllName = ['Bybit','Bitfinex','Okex','Deribit','Huobi','Bitmex','Binance','FTX']
ExchangeAllDataDict = dict(zip(ExchangeAllName, ExchangeAllData))
ExchangeAllDataDict = dict(sorted(ExchangeAllDataDict.items(), key=lambda d:d[1], reverse = True))
fig,ax1 = plt.subplots(figsize=(15,5))
colors_list = ['#DA4453','#E9573F','#F68B42','#8CC152','#37BC9B','#3BAFDA','#4A89DC','#967ADC']
ExchangeAllDataBar = plt.bar(ExchangeAllDataDict.keys(), ExchangeAllDataDict.values(),color = colors_list)
plt.xlabel('各大交易所')
plt.ylabel('总爆仓金额(万元)',rotation=360,labelpad = 50)
for a in ExchangeAllDataBar:
    height = a.get_height()
    plt.text(a.get_x() + a.get_width() / 2, height+3, str(height), ha="center", va="bottom",fontsize = 15)
plt.title( '近30日各大交易所爆仓总金额排行\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)

ax2 = inset_axes(ax1,width = '50%',height = '50%',loc='center right')
explode_list = [0,0,0,0,0,0,0,0]
bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(arrowprops=dict(arrowstyle="-"),
          bbox=bbox_props,va="center",)
wedges, ax2.texts = plt.pie(ExchangeAllData,radius=1,startangle=90,pctdistance=0.85,colors=pie1color,explode=explode_list)
for i, p in enumerate(wedges):
    ang = (p.theta2 - p.theta1)/2. + p.theta1 # ⻆度计算
    
    # ⻆度转弧度----->弧度转坐标
    y = np.sin(np.deg2rad(ang))
    x = np.cos(np.deg2rad(ang))
    ha = {-1: "right", 1: "left"}[int(np.sign(x))] # ⽔平对⻬⽅式
    connectionstyle = "angle,angleA=0,angleB={}".format(ang) # 箭头连接样式
    kw["arrowprops"].update({"connectionstyle": connectionstyle}) # 更新箭头连接⽅式
    plt.annotate(ExchangeAllName[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
                 ha=ha,**kw,fontsize = 10,weight = 'bold')
plt.title( '近30日各大交易所爆仓总金额占比',fontdict = {'fontsize' : 20},y=1.2)
plt.show()

运行结果:

 

 

 

16.综合各交易所的空单、多单、总金额数据制成饼图

 1 size = 0.3
 2 pie1color = ['#DA4453','#E9573F','#F68B42','#8CC152','#37BC9B','#3BAFDA','#4A89DC','#967ADC']
 3 pie2color = ['#ED5565','#FC6E51','#FFCE54','#A0D468','#48CFAD','#4FC1E9','#5D9CEC','#AC92EC']
 4 ExchangeDataPie = plt.pie(AllBuyVolUsdDataList,autopct='%1.2f%%',radius=1,startangle=90,pctdistance = 0.85,colors = pie1color,textprops = {'fontsize': 15},
 5         labels = Buylabels_list,wedgeprops=dict(width=size, edgecolor='w'),rotatelabels=True)
 6 plt.legend(loc='upper left', bbox_to_anchor=(-0.1, 1))
 7 ExchangeDataPie = plt.pie(AllSellVolUsdDataList,autopct='%1.2f%%',radius=1-size,startangle=90,pctdistance = 0.78,colors = pie2color,textprops = {'fontsize': 12},
 8         wedgeprops=dict(width=size, edgecolor='w'))
 9 ExchangeDataPie = plt.pie(ExchangeAllData,autopct='%1.2f%%',radius=1-size-size,startangle=90,pctdistance = 0.78,colors = pie1color,textprops = {'fontsize': 12},
10         wedgeprops=dict(width=size, edgecolor='w'))
11 plt.title( '近30日各大交易所空单与多单爆仓金额占比图\n外环:空单爆仓占比\n中环:多单爆仓占比\n内环:总爆仓占比\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 20},y=1)
12 plt.show()

运行结果:

 

代码总览

  1 #导包
  2 import requests    #网页请求
  3 import jsonpath    #json解析
  4 import json        #json操作
  5 from datetime import datetime
  6 from bs4 import BeautifulSoup
  7 
  8 #获取json数据中最近30天的buyVolUsd数据
  9 def getBuyVolUsd(json_dict):
 10     list = []
 11     a = 58
 12     b = 88
 13     while a < b:
 14         temp = jsonpath.jsonpath(json_dict,"$.data[{b}].buyVolUsd".format(b = b))
 15         intdata = int(temp[0]/10000)
 16         list.append(intdata)
 17         b -= 1
 18     list.reverse()
 19     return list
 20 
 21 #获取json数据中最近30天的sellVolUsd数据
 22 def getSellVolUsd(json_dict):
 23     list = []
 24     a = 58
 25     b = 88
 26     while a < b:
 27         temp = jsonpath.jsonpath(json_dict,"$.data[{b}].sellVolUsd".format(b = b))
 28         intdata = int(temp[0]/10000)
 29         list.append(intdata)
 30         b -= 1
 31     list.reverse()
 32     return list
 33 
 34 #获取json数据中最近30天的Price数据
 35 def getPrice(json_dict):
 36     list = []
 37     a = 58
 38     b = 88
 39     while a < b:
 40         temp = jsonpath.jsonpath(json_dict,"$.data[{b}].price".format(b = b))
 41         intdata = int(temp[0])
 42         list.append(intdata)
 43         b -= 1
 44     list.reverse()
 45     return list
 46 
 47 #设置url地址与headers参数
 48 json_url = 'https://fapi.bybt.com/api/futures/liquidation/chart?symbol=ALL'
 49 headers={'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Mobile Safari/537.36'}
 50 #获取url地址中的json数据
 51 json_data = requests.get(url=json_url,headers=headers).text
 52 get_json_time = (datetime.now()).strftime('%Y-%m-%d %H:%M:%S')
 53 json_dict = json.loads(json_data)    #转化为dict字典
 54 #调用函数获得列表
 55 buy_vol_usd = getBuyVolUsd(json_dict)
 56 sell_vol_usd = getSellVolUsd(json_dict)
 57 price = getPrice(json_dict)
 58 print('空单爆仓金额数据',buy_vol_usd,'\n')
 59 print('多单爆仓金额数据',sell_vol_usd,'\n')
 60 print('BTC价格数据',price)
 61 ———————————————————————————————————————————————————————————————————————
 62 import datetime    #时间操作
 63 
 64 #将today前30天的日期通过list返回
 65 def getAllDate(today):
 66     list = []
 67     a = 0
 68     b = 30
 69     while a < b:
 70         temp = today + datetime.timedelta(a*-1)
 71         date = temp.strftime('%m/%d')
 72         list.append(date)
 73         a += 1
 74     list.reverse()
 75     return list
 76 
 77 #获取时间列表
 78 today = datetime.date.today()
 79 AllDate = getAllDate(today)
 80 print(AllDate)
 81 ———————————————————————————————————————————————————————————————————————
 82 import numpy as np
 83 import pandas as pd
 84 import matplotlib.pyplot as plt
 85 plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
 86 plt.rcParams['axes.unicode_minus']=False #用来正常显示中文标签
 87 index_list = ['BTC价格','空单爆仓金额(万元)','多单爆仓金额(万元)']
 88 buy_data = buy_vol_usd
 89 sell_data = sell_vol_usd
 90 price_data = price
 91 df = pd.DataFrame([price_data,buy_data,sell_data],index = index_list,columns = AllDate)
 92 df
 93 
 94 df_buy = pd.DataFrame(buy_data,AllDate)
 95 df_sell = pd.DataFrame(sell_data,AllDate)
 96 df_buy.plot(kind='bar',width=0.8,color='red',edgecolor='black')
 97 plt.xticks(rotation=360)
 98 df_sell.plot(kind='bar',width=0.8,color='green',edgecolor='black')
 99 plt.xticks(rotation=360)
100 plt.rcParams.update({'figure.figsize':'15,10'})
101 plt.show()
102 ———————————————————————————————————————————————————————————————————————
103 bar_index = np.arange(30)
104 bar_width=0.33
105 bar1 = plt.bar(bar_index,buy_data,width=0.3,color='green',edgecolor='black',label = '空单爆仓金额(万元)')
106 
107 for a in bar1:
108     height = a.get_height()
109     plt.text(a.get_x() + a.get_width() / 2, height+3, str(height), ha="center", va="bottom")
110     
111 bar1 = plt.bar(bar_index+bar_width,sell_data,width=0.3,color='red',edgecolor='black',label = '多单爆仓金额(万元)')
112 
113 for a in bar1:
114     height = a.get_height()
115     plt.text(a.get_x() + a.get_width() / 2, height+3, str(height), ha="center", va="bottom")
116     
117 plt.xticks(bar_index + 3 * bar_width / 3,AllDate)
118 plt.xlabel('日期')
119 plt.ylabel('爆仓金额(万元)',rotation=360,labelpad = 50)
120 plt.legend()
121 plt.rcParams.update({'figure.figsize':'30,10'})
122 plt.twinx() # this is the important function
123 plt.plot(bar_index+0.151,price_data,'y')
124 plt.ylabel('BTC价格',rotation=360,labelpad = 50)
125 plt.title( '近30天爆仓金额柱状图\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
126 plt.show()
127 ———————————————————————————————————————————————————————————————————————
128 def getAllBuyData(data):
129     a=0
130     b=30
131     temp=0
132     while a < b:
133         temp += data[a]
134         a += 1
135     return temp
136 
137 def getAllSellData(data):
138     a=0
139     b=30
140     temp=0
141     while a < b:
142         temp += data[a]
143         a += 1
144     return temp
145 
146 def getPriceAvg(data):
147     a=0
148     b=30
149     temp=0
150     while a < b:
151         temp += data[a]
152         a += 1
153     return temp/30
154 
155 AllBuyData = getAllBuyData(buy_data)
156 AllSellData = getAllSellData(sell_data)
157 PriceAvg = getPriceAvg(price_data)
158 data_list = [AllBuyData,AllSellData]
159 
160 print('30天内空单爆仓总金额',AllBuyData)
161 print('30天内多单爆仓总金额',AllSellData)
162 print('30天内BTC平均价格',PriceAvg)
163 
164 groups = ['空单爆仓金额占比','多单爆仓金额占比']
165 plt.pie(data_list,autopct='%1.2f%%',labels=groups,explode=[0,0.007],textprops = {'fontsize': 30})
166 plt.title( '近30天爆仓金额多空占比\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
167 plt.legend(loc='upper left')
168 plt.show()
169 ———————————————————————————————————————————————————————————————————————
170 def getExchangeBuyVolUsdData(json_dict):
171     Bitmex = []
172     Binance = []
173     Okex = []
174     Huobi = []
175     Bybit = []
176     FTX = []
177     Deribit = []
178     Bitfinex = []
179     a = 58
180     b = 88
181     while a < b:
182         Bitmex.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[0].buyVolUsd".format(b = b))[0])/10000))
183         Binance.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[1].buyVolUsd".format(b = b))[0])/10000))
184         Okex.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[2].buyVolUsd".format(b = b))[0])/10000))
185         Huobi.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[3].buyVolUsd".format(b = b))[0])/10000))
186         Bybit.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[4].buyVolUsd".format(b = b))[0])/10000))
187         FTX.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[5].buyVolUsd".format(b = b))[0])/10000))
188         Deribit.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[6].buyVolUsd".format(b = b))[0])/10000))
189         Bitfinex.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[7].buyVolUsd".format(b = b))[0])/10000))
190         b -= 1
191     Bitmex.reverse()
192     Binance.reverse()
193     Okex.reverse()
194     Huobi.reverse()
195     Bybit.reverse()
196     FTX.reverse()
197     Deribit.reverse()
198     Bitfinex.reverse()
199     return [Bitmex,Binance,Okex,Huobi,Bybit,FTX,Deribit,Bitfinex]
200 
201 ExchangeBuyVolUsdData = getExchangeBuyVolUsdData(json_dict)
202 
203 BitmexBuyVolUsdData = ExchangeBuyVolUsdData[0]
204 BinanceBuyVolUsdData = ExchangeBuyVolUsdData[1]
205 OkexBuyVolUsdData = ExchangeBuyVolUsdData[2]
206 HuobiBuyVolUsdData = ExchangeBuyVolUsdData[3]
207 BybitBuyVolUsdData = ExchangeBuyVolUsdData[4]
208 FTXBuyVolUsdData = ExchangeBuyVolUsdData[5]
209 DeribitBuyVolUsdData = ExchangeBuyVolUsdData[6]
210 BitfinexBuyVolUsdData = ExchangeBuyVolUsdData[7]
211 BuyVolUsdDataList = [BitmexBuyVolUsdData,BinanceBuyVolUsdData,OkexBuyVolUsdData,HuobiBuyVolUsdData,
212                      BybitBuyVolUsdData,FTXBuyVolUsdData,DeribitBuyVolUsdData,BitfinexBuyVolUsdData]
213 index_list = ['Bitmex','Binance','Okex','Huobi','Bybit','FTX','Deribit','Bitfinex']
214 df = pd.DataFrame(BuyVolUsdDataList,index = index_list,columns = AllDate)
215 df
216 ———————————————————————————————————————————————————————————————————————
217 plt.figure(figsize=(20,10))
218 plt.plot(AllDate,BuyVolUsdDataList[0],label = 'Bitmex空单爆仓金额(万元)',marker='s')
219 plt.plot(AllDate,BuyVolUsdDataList[1],label = 'Binance空单爆仓金额(万元)',marker='s')
220 plt.plot(AllDate,BuyVolUsdDataList[2],label = 'Okex空单爆仓金额(万元)',marker='s')
221 plt.plot(AllDate,BuyVolUsdDataList[3],label = 'Huobi空单爆仓金额(万元)',marker='s')
222 plt.plot(AllDate,BuyVolUsdDataList[4],label = 'Bybit空单爆仓金额(万元)',marker='s')
223 plt.plot(AllDate,BuyVolUsdDataList[5],label = 'FTX空单爆仓金额(万元)',marker='s')
224 plt.plot(AllDate,BuyVolUsdDataList[6],label = 'Deribit空单爆仓金额(万元)',marker='s')
225 plt.plot(AllDate,BuyVolUsdDataList[7],label = 'Bitfinex空单爆仓金额(万元)',marker='s')
226 plt.ylabel('爆仓金额(万元)',rotation=360,labelpad = 50)
227 plt.xlabel('日期')
228 plt.legend()
229 
230 plt.twinx() # this is the important function
231 #绘制折线,可以有多种颜色及形状,c代表color,marker代表节点形状,ms代表marker size,label是折现名称。
232 plt.plot(AllDate,price_data,color = 'y',label = 'BTC价格',marker='o',ms=10,lw = 5,linestyle = ':')
233 plt.ylabel('BTC价格',rotation=360,labelpad = 50)
234 plt.legend(bbox_to_anchor=(1.08, 1))
235 plt.title( '近30日各大交易所空单爆仓金额\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
236 plt.show()
237 ———————————————————————————————————————————————————————————————————————
238 BitmexAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[0])
239 BinanceAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[1])
240 OkexAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[2])
241 HuobiAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[3])
242 BybitAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[4])
243 FTXAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[5])
244 DeribitAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[6])
245 BitfinexAllBuyVolUsdData = getAllBuyData(ExchangeBuyVolUsdData[7])
246 AllBuyVolUsdDataList = [BybitAllBuyVolUsdData,BitfinexAllBuyVolUsdData,OkexAllBuyVolUsdData,
247                         DeribitAllBuyVolUsdData,HuobiAllBuyVolUsdData,BitmexAllBuyVolUsdData,BinanceAllBuyVolUsdData,FTXAllBuyVolUsdData]
248 print('Bitmex30天空单爆仓合计',BitmexAllBuyVolUsdData,'万元($)')
249 print('Binance30天空单爆仓合计',BinanceAllBuyVolUsdData,'万元($)')
250 print('Okex30天空单爆仓合计',OkexAllBuyVolUsdData,'万元($)')
251 print('Huobi30天空单爆仓合计',HuobiAllBuyVolUsdData,'万元($)')
252 print('Bybit30天空单爆仓合计',BybitAllBuyVolUsdData,'万元($)')
253 print('FTX30天空单爆仓合计',FTXAllBuyVolUsdData,'万元($)')
254 print('Deribit30天空单爆仓合计',DeribitAllBuyVolUsdData,'万元($)')
255 print('Bitfinex30天空单爆仓合计',BitfinexAllBuyVolUsdData,'万元($)')
256 AllBuyVolUsdDataList
257 ———————————————————————————————————————————————————————————————————————
258 colors_list = ['#DA4453','#E9573F','#F68B42','#8CC152','#37BC9B','#3BAFDA','#4A89DC','#967ADC']
259 Buylabels_list = ['Bybit','Bitfinex','Okex','Deribit','Huobi','Bitmex','Binance','FTX']
260 plt.pie(AllBuyVolUsdDataList,autopct='%1.2f%%',startangle=90,labels = Buylabels_list,textprops = {'fontsize': 15},
261         rotatelabels=True,colors = colors_list)
262 plt.title( '近30日各大交易所空单爆仓金额占比\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
263 plt.legend(loc='upper left')
264 plt.show()
265 ———————————————————————————————————————————————————————————————————————
266 def getExchangeSellVolUsdData(json_dict):
267     Bitmex = []
268     Binance = []
269     Okex = []
270     Huobi = []
271     Bybit = []
272     FTX = []
273     Deribit = []
274     Bitfinex = []
275     a = 58
276     b = 88
277     while a < b:
278         Bitmex.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[0].sellVolUsd".format(b = b))[0])/10000))
279         Binance.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[1].sellVolUsd".format(b = b))[0])/10000))
280         Okex.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[2].sellVolUsd".format(b = b))[0])/10000))
281         Huobi.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[3].sellVolUsd".format(b = b))[0])/10000))
282         Bybit.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[4].sellVolUsd".format(b = b))[0])/10000))
283         FTX.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[5].sellVolUsd".format(b = b))[0])/10000))
284         Deribit.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[6].sellVolUsd".format(b = b))[0])/10000))
285         Bitfinex.append(int((jsonpath.jsonpath(json_dict,"$.data[{b}].list[7].sellVolUsd".format(b = b))[0])/10000))
286         b -= 1
287     Bitmex.reverse()
288     Binance.reverse()
289     Okex.reverse()
290     Huobi.reverse()
291     Bybit.reverse()
292     FTX.reverse()
293     Deribit.reverse()
294     Bitfinex.reverse()
295     return [Bitmex,Binance,Okex,Huobi,Bybit,FTX,Deribit,Bitfinex]
296 
297 ExchangeSellVolUsdData = getExchangeSellVolUsdData(json_dict)
298 
299 BitmexSellVolUsdData = ExchangeSellVolUsdData[0]
300 BinanceSellVolUsdData = ExchangeSellVolUsdData[1]
301 OkexSellVolUsdData = ExchangeSellVolUsdData[2]
302 HuobiSellVolUsdData = ExchangeSellVolUsdData[3]
303 BybitSellVolUsdData = ExchangeSellVolUsdData[4]
304 FTXSellVolUsdData = ExchangeSellVolUsdData[5]
305 DeribitSellVolUsdData = ExchangeSellVolUsdData[6]
306 BitfinexSellVolUsdData = ExchangeSellVolUsdData[7]
307 SellVolUsdDataList = [BitmexSellVolUsdData,BinanceSellVolUsdData,OkexSellVolUsdData,HuobiSellVolUsdData,
308                       BybitSellVolUsdData,FTXSellVolUsdData,DeribitSellVolUsdData,BitfinexSellVolUsdData]
309 
310 plt.figure(figsize=(20,10))
311 plt.plot(AllDate,SellVolUsdDataList[0],label = 'Bitmex多单爆仓金额(万元)',marker='s')
312 plt.plot(AllDate,SellVolUsdDataList[1],label = 'Binance多单爆仓金额(万元)',marker='s')
313 plt.plot(AllDate,SellVolUsdDataList[2],label = 'Okex多单爆仓金额(万元)',marker='s')
314 plt.plot(AllDate,SellVolUsdDataList[3],label = 'Huobi多单爆仓金额(万元)',marker='s')
315 plt.plot(AllDate,SellVolUsdDataList[4],label = 'Bybit多单爆仓金额(万元)',marker='s')
316 plt.plot(AllDate,SellVolUsdDataList[5],label = 'FTX多单爆仓金额(万元)',marker='s')
317 plt.plot(AllDate,SellVolUsdDataList[6],label = 'Deribit多单爆仓金额(万元)',marker='s')
318 plt.plot(AllDate,SellVolUsdDataList[7],label = 'Bitfinex多单爆仓金额(万元)',marker='s')
319 plt.ylabel('爆仓金额(万元)',rotation=360,labelpad = 50)
320 plt.xlabel('日期')
321 plt.legend()
322 
323 plt.twinx() # this is the important function
324 #绘制折线,可以有多种颜色及形状,c代表color,marker代表节点形状,ms代表marker size,label是折现名称。
325 plt.plot(AllDate,price_data,color = 'y',label = 'BTC价格',marker='o',ms=10,lw = 5,linestyle = ':')
326 plt.ylabel('BTC价格',rotation=360,labelpad = 50)
327 plt.legend(bbox_to_anchor=(1.08, 1))
328 plt.title( '近30日各大交易所多单爆仓金额占比\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
329 plt.show()
330 ———————————————————————————————————————————————————————————————————————
331 BitmexAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[0])
332 BinanceAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[1])
333 OkexAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[2])
334 HuobiAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[3])
335 BybitAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[4])
336 FTXAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[5])
337 DeribitAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[6])
338 BitfinexAllSellVolUsdData = getAllBuyData(ExchangeSellVolUsdData[7])
339 AllSellVolUsdDataList = [BybitAllSellVolUsdData,BitfinexAllSellVolUsdData,OkexAllSellVolUsdData,DeribitAllSellVolUsdData,
340                          HuobiAllSellVolUsdData,BitmexAllSellVolUsdData,BinanceAllSellVolUsdData,FTXAllSellVolUsdData]
341 print('Bitmex30天多单爆仓合计',BitmexAllSellVolUsdData,'万元($)')
342 print('Binance30天多单爆仓合计',BinanceAllSellVolUsdData,'万元($)')
343 print('Okex30天多单爆仓合计',OkexAllSellVolUsdData,'万元($)')
344 print('Huobi30天多单爆仓合计',HuobiAllSellVolUsdData,'万元($)')
345 print('Bybit30天多单爆仓合计',BybitAllSellVolUsdData,'万元($)')
346 print('FTX30天多单爆仓合计',FTXAllSellVolUsdData,'万元($)')
347 print('Deribit30天多单爆仓合计',DeribitAllSellVolUsdData,'万元($)')
348 print('Bitfinex30天多单爆仓合计',BitfinexAllSellVolUsdData,'万元($)')
349 AllSellVolUsdDataList
350 ———————————————————————————————————————————————————————————————————————
351 Selllabels_list = ['Bybit','Bitfinex','Okex','Deribit','Huobi','Bitmex','Binance','FTX']
352 plt.pie(AllSellVolUsdDataList,autopct='%1.2f%%',startangle=90,labels = Selllabels_list,textprops = {'fontsize': 15},rotatelabels=True,colors = colors_list)
353 plt.title( '近30日各大交易所多单爆仓金额占比\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
354 plt.legend(loc='upper left')
355 plt.show()
356 ———————————————————————————————————————————————————————————————————————
357 size = 0.3
358 pie1color = ['#DA4453','#E9573F','#F68B42','#8CC152','#37BC9B','#3BAFDA','#4A89DC','#967ADC']
359 pie2color = ['#ED5565','#FC6E51','#FFCE54','#A0D468','#48CFAD','#4FC1E9','#5D9CEC','#AC92EC']
360 ExchangeDataPie = plt.pie(AllBuyVolUsdDataList,autopct='%1.2f%%',radius=1,startangle=90,pctdistance = 0.85,colors = pie1color,textprops = {'fontsize': 15},
361         labels = Buylabels_list,wedgeprops=dict(width=size, edgecolor='w'),rotatelabels=True)
362 plt.legend(loc='upper left', bbox_to_anchor=(-0.1, 1))
363 ExchangeDataPie = plt.pie(AllSellVolUsdDataList,autopct='%1.2f%%',radius=1-size,startangle=90,pctdistance = 0.78,colors = pie2color,textprops = {'fontsize': 12},
364         wedgeprops=dict(width=size, edgecolor='w'))
365 plt.title( '近30日各大交易所空单与多单爆仓金额占比图\n外环:空单爆仓占比\n内环:多单爆仓占比\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
366 plt.show()
367 ———————————————————————————————————————————————————————————————————————
368 def getExchangeAllData(AllBuyVolUsdDataList,AllSellVolUsdDataList):
369     list = []
370     a = 0
371     b = 8
372     while a < 8:
373         temp = AllBuyVolUsdDataList[a]+AllSellVolUsdDataList[a]
374         list.append(temp)
375         a += 1
376     return list
377 ExchangeAllData = getExchangeAllData(AllBuyVolUsdDataList,AllSellVolUsdDataList)
378 ExchangeAllName = ['Bybit','Bitfinex','Okex','Deribit','Huobi','Bitmex','Binance','FTX']
379 ExchangeAllDataDict = dict(zip(ExchangeAllName, ExchangeAllData))
380 ExchangeAllDataDict = dict(sorted(ExchangeAllDataDict.items(), key=lambda d:d[1], reverse = True))
381 print(ExchangeAllDataDict)
382 ———————————————————————————————————————————————————————————————————————
383 from mpl_toolkits.axes_grid1.inset_locator import inset_axes
384 
385 fig,ax1 = plt.subplots(figsize=(15,5))
386 colors_list = ['#DA4453','#E9573F','#F68B42','#8CC152','#37BC9B','#3BAFDA','#4A89DC','#967ADC']
387 ExchangeAllDataBar = plt.bar(ExchangeAllDataDict.keys(), ExchangeAllDataDict.values(),color = colors_list)
388 plt.xlabel('各大交易所')
389 plt.ylabel('总爆仓金额(万元)',rotation=360,labelpad = 50)
390 for a in ExchangeAllDataBar:
391     height = a.get_height()
392     plt.text(a.get_x() + a.get_width() / 2, height+3, str(height), ha="center", va="bottom",fontsize = 15)
393 plt.title( '近30日各大交易所爆仓总金额排行\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 30},y=1.1)
394 
395 ax2 = inset_axes(ax1,width = '50%',height = '50%',loc='center right')
396 explode_list = [0,0,0,0,0,0,0,0]
397 bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
398 kw = dict(arrowprops=dict(arrowstyle="-"),
399           bbox=bbox_props,va="center",)
400 wedges, ax2.texts = plt.pie(ExchangeAllData,radius=1,startangle=90,pctdistance=0.85,colors=pie1color,explode=explode_list)
401 for i, p in enumerate(wedges):
402     ang = (p.theta2 - p.theta1)/2. + p.theta1 # ⻆度计算
403     
404     # ⻆度转弧度----->弧度转坐标
405     y = np.sin(np.deg2rad(ang))
406     x = np.cos(np.deg2rad(ang))
407     ha = {-1: "right", 1: "left"}[int(np.sign(x))] # ⽔平对⻬⽅式
408     connectionstyle = "angle,angleA=0,angleB={}".format(ang) # 箭头连接样式
409     kw["arrowprops"].update({"connectionstyle": connectionstyle}) # 更新箭头连接⽅式
410     plt.annotate(ExchangeAllName[i], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
411                  ha=ha,**kw,fontsize = 10,weight = 'bold')
412 plt.title( '近30日各大交易所爆仓总金额占比',fontdict = {'fontsize' : 20},y=1.2)
413 plt.show()
414 ———————————————————————————————————————————————————————————————————————
415 size = 0.3
416 pie1color = ['#DA4453','#E9573F','#F68B42','#8CC152','#37BC9B','#3BAFDA','#4A89DC','#967ADC']
417 pie2color = ['#ED5565','#FC6E51','#FFCE54','#A0D468','#48CFAD','#4FC1E9','#5D9CEC','#AC92EC']
418 ExchangeDataPie = plt.pie(AllBuyVolUsdDataList,autopct='%1.2f%%',radius=1,startangle=90,pctdistance = 0.85,colors = pie1color,textprops = {'fontsize': 15},
419         labels = Buylabels_list,wedgeprops=dict(width=size, edgecolor='w'),rotatelabels=True)
420 plt.legend(loc='upper left', bbox_to_anchor=(-0.1, 1))
421 ExchangeDataPie = plt.pie(AllSellVolUsdDataList,autopct='%1.2f%%',radius=1-size,startangle=90,pctdistance = 0.78,colors = pie2color,textprops = {'fontsize': 12},
422         wedgeprops=dict(width=size, edgecolor='w'))
423 ExchangeDataPie = plt.pie(ExchangeAllData,autopct='%1.2f%%',radius=1-size-size,startangle=90,pctdistance = 0.78,colors = pie1color,textprops = {'fontsize': 12},
424         wedgeprops=dict(width=size, edgecolor='w'))
425 plt.title( '近30日各大交易所空单与多单爆仓金额占比图\n外环:空单爆仓占比\n中环:多单爆仓占比\n内环:总爆仓占比\n该数据截止至{get_json_time}'.format(get_json_time = get_json_time),fontdict = {'fontsize' : 20},y=1)
426 plt.show()
Code

 

总结

通过上面的数据获取、分析与统计,我们不难看出虚拟币的波动巨大,在一个个爆仓数据都是人民群众的血汗钱,我们应该响应国家的政策,抵制虚拟币的交易与"挖矿"行为,这也同时保护了我们自己的钱袋子。

从整个数据爬取项目中我学习了许多新的知识内容,也扩充了我对于Python制图的知识库,学会了如何运用matplotlib.org来查看自己需要的图是如何构成的,以后的学习点将在于如何从更多方面分析数据以及更多的Python库应用。

posted @ 2021-06-26 21:58  hyoubu  阅读(264)  评论(0编辑  收藏  举报