
來源:早起Python
作者:讀者投稿
最近幾年,比特幣一直站在風口浪尖,一度被追捧為最佳的投資產(chǎn)品,擁護者認為這種加密貨幣是一種類似于黃金的儲值工具,可以對沖通脹和美元疲軟。其他人則認為,比特幣的暴漲只是一個經(jīng)濟刺激措施催生的巨大泡沫,并且必將破裂。
比特幣數(shù)據(jù)很多網(wǎng)站都有,并且也有很多成熟的API,所以取數(shù)據(jù)非常簡單,直接調(diào)用API接口即可,下面是獲取與寫入數(shù)據(jù)的全部代碼
import requests import json import csv import time time_stamp = int(time.time()) url = f"https://web-api.coinmarketcap.com/v1/cryptocurrency/ohlcv/historical?convert=USD&slug
=bitcoin&time_end={time_stamp}&time_start=1367107200"
rd = requests.get(url = url) # 返回的數(shù)據(jù)是 JSON 格式,使用 json 模塊解析 co =
json.loads(rd.content)
list1 = co['data']['quotes']
with open('BTC.csv','w' ,encoding='utf8',newline='') as f:
csvi = csv.writer(f)
csv_head = ["date","price","volume"]
csvi.writerow(csv_head)
for i in list1:
quote_date = i["time_open"][:10]
quote_price = "{:.2f}".format(i["quote"]["USD"]["close"])
quote_volume = "{:.2f}".format(i["quote"]["USD"]["volume"])
csvi.writerow([quote_date, quote_price, quote_volume])
執(zhí)行后,當前目錄就會生成BTC.csv數(shù)據(jù)文件
首先導入需要的包及相關設定
import pandas as pd import matplotlib as mpl from matplotlib import cm import numpy
as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker import
matplotlib.animation as animation from IPython.display import HTML from datetime import datetime
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.rc('axes',axisbelow=True)
mpl.rcParams['animation.embed_limit'] = 2**128
其中兩句plt.rcParams[]是用來設置顯示中文的
plt.rc('axes',axisbelow=True)的作用是設置外觀要求,即坐標軸置底。
mpl.rcParams['animation.embed_limit'] = 2**128這句是為了生成動畫而用的,由于動畫默認的最大體積為20971520.字節(jié)。如果需要調(diào)整生成的動畫最大體積,需要更改這個參數(shù)。
接下來數(shù)據(jù)并利用查看前5行與后5行
從表格初窺可以得知,13年初的價格在100美元左右,而到如今21年價格已經(jīng)飛漲到5萬左右了。具體在哪段時間飛漲如此之快呢,我們通過動態(tài)面積可視化來探索。
可視化之前,需要對數(shù)據(jù)進行處理,由于我們原本的數(shù)據(jù)是這樣的
是csv格式,且Date字段是字符串類型,而在Python中運用matplotlib畫時間序列圖都需要datetime時間戳格式才美觀,所以我們運用了如下代碼進行轉換
df = pd.read_csv('BTC.csv')
df['date']=[datetime.strptime(d, '%Y/%m/%d').date() for d in df['date']]
下面制作靜態(tài)面積圖,使用單色填充的話,可用如下代碼
Span=180 N_Span=0 df_temp=df.loc[N_Span*Span:(N_Span+1)*Span,:]
df_temp.head(5)
fig =plt.figure(figsize=(6,4), dpi=100)
plt.subplots_adjust(top=1,bottom=0,left=0,right=0.9,hspace=0,wspace=0)
plt.fill_between(df_temp.date.values, y1=df_temp.price.values, y2=0,alpha=0.75, facecolor='r',
linewidth=1,edgecolor ='none',zorder=1)
plt.plot(df_temp.date, df_temp.price, color='k',zorder=2)
plt.scatter(df_temp.date.values[-1], df_temp.price.values[-1], color='white',s=150,edgecolor ='k',
linewidth=2,zorder=3)
plt.text(df_temp.date.values[-1], df_temp.price.values[-1]*1.18,s=np.round(df_temp.price.values[-1],1),
size=10,ha='center', va='top')
plt.ylim(0, df_temp.price.max()*1.68)
plt.xticks(ticks=df_temp.date.values[0:Span+1:30],labels=df_temp.date.values[0:Span+1:30],rotation=0)
plt.margins(x=0.01)
ax = plt.gca()#獲取邊框 ax.spines['top'].set_color('none') # 設置上‘脊梁’為無色
ax.spines['right'].set_color('none') # 設置上‘脊梁’為無色 ax.spines['left'].set_color('none')
# 設置上‘脊梁’為無色 plt.grid(axis="y",c=(217/256,217/256,217/256),linewidth=1)
#設置網(wǎng)格線 plt.show()
其中Span設定的是多少天的價格,這里我們使用200天。N_Span代表權重;
df_temp=df.loc[N_Span*Span:(N_Span+1)*Span,:]代表的是選擇到179行為止的數(shù)據(jù),即180天。
plt.fill_between()是使用單色--紅色填充
得到如下效果
但是一個顏色填充總感覺不夠好看,所以下面使用漸變色填充,使用plt.bar()函數(shù)實現(xiàn)Spectral_r顏色映射。代碼如下:
Span_Date =180
Num_Date =360 #終止日期 df_temp=df.loc[Num_Date-Span_Date: Num_Date,:]
#選擇從Num_Date-Span_Date開始到Num_Date的180天的數(shù)據(jù) colors =
cm.Spectral_r(df_temp.price / float(max(df_temp.price)))
fig =plt.figure(figsize=(6,4), dpi=100)
plt.subplots_adjust(top=1,bottom=0,left=0,right=0.9,hspace=0,wspace=0)
plt.bar(df_temp.date.values,df_temp.price.values,color=colors,width=1,align="center",zorder=1)
plt.plot(df_temp.date, df_temp.price, color='k',zorder=2)
plt.scatter(df_temp.date.values[-1], df_temp.price.values[-1], color='white',s=150,edgecolor ='k',linewidth=2,zorder=3)
plt.text(df_temp.date.values[-1], df_temp.price.values[-1]*1.18,s=np.round(df_temp.price.values[-1],1),
size=10,ha='center', va='top')
plt.ylim(0, df_temp.price.max()*1.68)
plt.xticks(ticks=df_temp.date.values[0: Span_Date +1:30],labels=df_temp.date.values[0: Span_Date +1:30],rotation=0)
plt.margins(x=0.01)
ax = plt.gca()#獲取邊框 ax.spines['top'].set_color('none') # 設置上‘脊梁’為無色 ax.spines['right'].set_color('none')
# 設置上‘脊梁’為無色 ax.spines['left'].set_color('none') # 設置上‘脊梁’為無色 plt.grid(axis="y",
c=(217/256,217/256,217/256),linewidth=1) #設置網(wǎng)格線 plt.show()
這里的數(shù)據(jù)篩選有稍許不同,其中Span_Date設置初始時間,這里設置為180即從起始日開始算的180天.
Num_Date設置的是終止時間。
df_temp=df.loc[Num_Date-Span_Date: Num_Date,:]則是用loc函數(shù)篩選從180天到終止日期的數(shù)據(jù)。
效果如下:
最后,我們來將這幅圖動起來,先將剛剛的繪圖部分封裝
def draw_areachart(Num_Date):
Span_Date=180
ax.clear()
if Num_Date<Span_Date: df_temp=df.loc[0:Num_Date,:] df_span=df.loc[0:Span_Date,:]
colors = cm.Spectral_r(df_span.price.values / float(max(df_span.price.values)))
plt.bar(df_temp.date.values,df_temp.price.values,color=colors,width=1.5,align="center",zorder=1)
plt.plot(df_temp.date, df_temp.price, color='k',zorder=2) plt.scatter(df_temp.date.values[-1],
df_temp.price.values[-1], color='white',s=150,edgecolor ='k',linewidth=2,zorder=3)
plt.text(df_temp.date.values[-1], df_temp.price.values[-1]*1.18,s=np.round(df_temp.price.values[-1],1),
size=10,ha='center', va='top')
plt.ylim(0, df_span.price.max()*1.68)
plt.xlim(df_span.date.values[0], df_span.date.values[-1])
plt.xticks(ticks=df_span.date.values[0:Span_Date+1:30],labels=df_span.date.values[0:Span_Date+1:30],
rotation=0,fontsize=9)
else: df_temp=df.loc[Num_Date-Span_Date:Num_Date,:] colors = cm.Spectral_r(df_temp.price /
float(max(df_temp.price)))
plt.bar(df_temp.date.values[:-2],df_temp.price.values[:-2],color=colors[:-2],width=1.5,align="center",zorder=1)
plt.plot(df_temp.date[:-2], df_temp.price[:-2], color='k',zorder=2) plt.scatter(df_temp.date.values[-4],
df_temp.price.values[-4], color='white',s=150,edgecolor ='k',linewidth=2,zorder=3)
plt.text(df_temp.date.values[-1], df_temp.price.values[-1]*1.18,s=np.round(df_temp.price.values[-1],1),
size=10,ha='center', va='top')
plt.ylim(0, df_temp.price.max()*1.68)
plt.xlim(df_temp.date.values[0], df_temp.date.values[-1])
plt.xticks(ticks=df_temp.date.values[0:Span_Date+1:30],labels=df_temp.date.values[0:Span_Date+1:30],rotation=0,fontsize=9)
plt.margins(x=0.2) ax.spines['top'].set_color('none') # 設置上‘脊梁’為紅色
ax.spines['right'].set_color('none') # 設置上‘脊梁’為無色
ax.spines['left'].set_color('none') # 設置上‘脊梁’為無色
plt.grid(axis="y",c=(217/256,217/256,217/256),linewidth=1) #設置網(wǎng)格線
plt.text(0.01, 0.95,"BTC平均價格($)",transform=ax.transAxes, size=10, weight='light', ha='left')
ax.text(-0.07, 1.03, '2013年到2021年的比特幣BTC價格變化情況',transform=ax.transAxes, size=17, weight='light',
ha='left') fig, ax = plt.subplots(figsize=(6,4), dpi=100)
plt.subplots_adjust(top=1,bottom=0.1,left=0.1,right=0.9,hspace=0,wspace=0) draw_areachart(150)
之后使用matplotlib包的animation.FuncAnimation()函數(shù),之后調(diào)用上述編寫的draw_areachart(Num_Date)函數(shù)。
其中輸入的參數(shù)Num_Date是如靜態(tài)可視化中提及的日期作用一樣,賦值為np.arange(0,df.shape[0],1)。
最后使用Ipython包的HTML()函數(shù)將動畫轉換成動畫頁面的形式演示。代碼如下:
import matplotlib.animation as animation
from IPython.display import HTML
fig, ax = plt.subplots(figsize=(6,4), dpi=100)
plt.subplots_adjust(left=0.12, right=0.98, top=0.85, bottom=0.1,hspace=0,wspace=0)
animator = animation.FuncAnimation(fig, draw_areachart, frames=np.arange(0,df.shape[0],1),
interval=100) HTML(animator.to_jshtml())
函數(shù)FuncAnimation(fig,func,frames,init_func,interval,blit)是繪制動圖函數(shù)。其參數(shù)如下:
“
fig 表示繪制動圖的畫布名稱(figure);func為自定義繪圖函數(shù),如draw_barchart()函數(shù);frames為動畫長度,一次循環(huán)包含的幀數(shù),在函數(shù)運行時,其值會傳遞給函數(shù)draw_barchart (year)的形參“year”;init_func為自定義開始幀可省略;interval表示更新頻率,計量單位為ms;blit表示選擇更新所有點,還是僅更新產(chǎn)生變化的點,應選擇為True,但mac電腦用戶應選擇False,否則無法顯示。
”
最后效果就是這樣
可以看到在過去的一年中,由于機構的興趣日益增加,比特幣上漲超過了6倍,最高突破58000美元/枚,當然可以看到跌起來也是非常恐怖的,關于比特幣,你怎么看?
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關鍵? 在循環(huán)神經(jīng)網(wǎng)絡(RNN)家族中,長短期記憶網(wǎng)絡(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報考條件詳解與準備指南? ? 在數(shù)據(jù)驅(qū)動決策的時代浪潮下,CDA 數(shù)據(jù)分析師認證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計的實用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實施重大更新。 此次更新旨在確保認 ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務的價值轉化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡稱 BI)深度融合的時代,BI ...
2025-07-10SQL 在預測分析中的應用:從數(shù)據(jù)查詢到趨勢預判? ? 在數(shù)據(jù)驅(qū)動決策的時代,預測分析作為挖掘數(shù)據(jù)潛在價值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結束后:分析師的收尾工作與價值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結束)并非工作的終點,而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報考到取證的全攻略? 在數(shù)字經(jīng)濟蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢性檢驗:捕捉數(shù)據(jù)背后的時間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢性檢驗如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時間維度的精準切片? ? 在數(shù)據(jù)的世界里,時間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準 ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應用與實戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗:數(shù)據(jù)趨勢與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領域中,準確捕捉數(shù)據(jù)的趨勢變化以及識別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認證作為國內(nèi)權威的數(shù)據(jù)分析能力認證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應對策略? 長短期記憶網(wǎng)絡(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(RNN)的一種變體,憑借獨特的門控機制,在 ...
2025-07-07統(tǒng)計學方法在市場調(diào)研數(shù)據(jù)中的深度應用? 市場調(diào)研是企業(yè)洞察市場動態(tài)、了解消費者需求的重要途徑,而統(tǒng)計學方法則是市場調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉日期:解鎖數(shù)據(jù)處理的關鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準確性的基礎 ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03