
來源:早起Python
作者:讀者投稿
最近幾年,比特幣一直站在風(fēng)口浪尖,一度被追捧為最佳的投資產(chǎn)品,擁護(hù)者認(rèn)為這種加密貨幣是一種類似于黃金的儲(chǔ)值工具,可以對(duì)沖通脹和美元疲軟。其他人則認(rèn)為,比特幣的暴漲只是一個(gè)經(jīng)濟(jì)刺激措施催生的巨大泡沫,并且必將破裂。
比特幣數(shù)據(jù)很多網(wǎng)站都有,并且也有很多成熟的API,所以取數(shù)據(jù)非常簡(jiǎn)單,直接調(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í)行后,當(dāng)前目錄就會(huì)生成BTC.csv數(shù)據(jù)文件
首先導(dǎo)入需要的包及相關(guān)設(shè)定
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[]是用來設(shè)置顯示中文的
plt.rc('axes',axisbelow=True)的作用是設(shè)置外觀要求,即坐標(biāo)軸置底。
mpl.rcParams['animation.embed_limit'] = 2**128這句是為了生成動(dòng)畫而用的,由于動(dòng)畫默認(rèn)的最大體積為20971520.字節(jié)。如果需要調(diào)整生成的動(dòng)畫最大體積,需要更改這個(gè)參數(shù)。
接下來數(shù)據(jù)并利用查看前5行與后5行
從表格初窺可以得知,13年初的價(jià)格在100美元左右,而到如今21年價(jià)格已經(jīng)飛漲到5萬左右了。具體在哪段時(shí)間飛漲如此之快呢,我們通過動(dòng)態(tài)面積可視化來探索。
可視化之前,需要對(duì)數(shù)據(jù)進(jìn)行處理,由于我們?cè)镜臄?shù)據(jù)是這樣的
是csv格式,且Date字段是字符串類型,而在Python中運(yùn)用matplotlib畫時(shí)間序列圖都需要datetime時(shí)間戳格式才美觀,所以我們運(yùn)用了如下代碼進(jìn)行轉(zhuǎn)換
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') # 設(shè)置上‘脊梁’為無色
ax.spines['right'].set_color('none') # 設(shè)置上‘脊梁’為無色 ax.spines['left'].set_color('none')
# 設(shè)置上‘脊梁’為無色 plt.grid(axis="y",c=(217/256,217/256,217/256),linewidth=1)
#設(shè)置網(wǎng)格線 plt.show()
其中Span設(shè)定的是多少天的價(jià)格,這里我們使用200天。N_Span代表權(quán)重;
df_temp=df.loc[N_Span*Span:(N_Span+1)*Span,:]代表的是選擇到179行為止的數(shù)據(jù),即180天。
plt.fill_between()是使用單色--紅色填充
得到如下效果
但是一個(gè)顏色填充總感覺不夠好看,所以下面使用漸變色填充,使用plt.bar()函數(shù)實(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') # 設(shè)置上‘脊梁’為無色 ax.spines['right'].set_color('none')
# 設(shè)置上‘脊梁’為無色 ax.spines['left'].set_color('none') # 設(shè)置上‘脊梁’為無色 plt.grid(axis="y",
c=(217/256,217/256,217/256),linewidth=1) #設(shè)置網(wǎng)格線 plt.show()
這里的數(shù)據(jù)篩選有稍許不同,其中Span_Date設(shè)置初始時(shí)間,這里設(shè)置為180即從起始日開始算的180天.
Num_Date設(shè)置的是終止時(shí)間。
df_temp=df.loc[Num_Date-Span_Date: Num_Date,:]則是用loc函數(shù)篩選從180天到終止日期的數(shù)據(jù)。
效果如下:
最后,我們來將這幅圖動(dòng)起來,先將剛剛的繪圖部分封裝
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') # 設(shè)置上‘脊梁’為紅色
ax.spines['right'].set_color('none') # 設(shè)置上‘脊梁’為無色
ax.spines['left'].set_color('none') # 設(shè)置上‘脊梁’為無色
plt.grid(axis="y",c=(217/256,217/256,217/256),linewidth=1) #設(shè)置網(wǎng)格線
plt.text(0.01, 0.95,"BTC平均價(jià)格($)",transform=ax.transAxes, size=10, weight='light', ha='left')
ax.text(-0.07, 1.03, '2013年到2021年的比特幣BTC價(jià)格變化情況',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ù)將動(dòng)畫轉(zhuǎn)換成動(dòng)畫頁(yè)面的形式演示。代碼如下:
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)是繪制動(dòng)圖函數(shù)。其參數(shù)如下:
“
fig 表示繪制動(dòng)圖的畫布名稱(figure);func為自定義繪圖函數(shù),如draw_barchart()函數(shù);frames為動(dòng)畫長(zhǎng)度,一次循環(huán)包含的幀數(shù),在函數(shù)運(yùn)行時(shí),其值會(huì)傳遞給函數(shù)draw_barchart (year)的形參“year”;init_func為自定義開始幀可省略;interval表示更新頻率,計(jì)量單位為ms;blit表示選擇更新所有點(diǎn),還是僅更新產(chǎn)生變化的點(diǎn),應(yīng)選擇為True,但mac電腦用戶應(yīng)選擇False,否則無法顯示。
”
最后效果就是這樣
可以看到在過去的一年中,由于機(jī)構(gòu)的興趣日益增加,比特幣上漲超過了6倍,最高突破58000美元/枚,當(dāng)然可以看到跌起來也是非??植赖?,關(guān)于比特幣,你怎么看?
數(shù)據(jù)分析咨詢請(qǐng)掃描二維碼
若不方便掃碼,搜微信號(hào):CDAshujufenxi
LSTM 模型輸入長(zhǎng)度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)家族中,長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)憑借其解決長(zhǎng)序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報(bào)考條件詳解與準(zhǔn)備指南? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代浪潮下,CDA 數(shù)據(jù)分析師認(rèn)證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計(jì)的實(shí)用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強(qiáng)大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠(chéng)摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實(shí)施重大更新。 此次更新旨在確保認(rèn) ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務(wù)的價(jià)值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡(jiǎn)稱 BI)深度融合的時(shí)代,BI ...
2025-07-10SQL 在預(yù)測(cè)分析中的應(yīng)用:從數(shù)據(jù)查詢到趨勢(shì)預(yù)判? ? 在數(shù)據(jù)驅(qū)動(dòng)決策的時(shí)代,預(yù)測(cè)分析作為挖掘數(shù)據(jù)潛在價(jià)值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價(jià)值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點(diǎn),而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報(bào)考到取證的全攻略? 在數(shù)字經(jīng)濟(jì)蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭(zhēng)搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢(shì)性檢驗(yàn):捕捉數(shù)據(jù)背后的時(shí)間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢(shì)性檢驗(yàn)如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時(shí)間維度的精準(zhǔn)切片? ? 在數(shù)據(jù)的世界里,時(shí)間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準(zhǔn) ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應(yīng)用與實(shí)戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認(rèn)證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗(yàn):數(shù)據(jù)趨勢(shì)與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準(zhǔn)確捕捉數(shù)據(jù)的趨勢(shì)變化以及識(shí)別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認(rèn)證作為國(guó)內(nèi)權(quán)威的數(shù)據(jù)分析能力認(rèn)證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應(yīng)對(duì)策略? 長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)的一種變體,憑借獨(dú)特的門控機(jī)制,在 ...
2025-07-07統(tǒng)計(jì)學(xué)方法在市場(chǎng)調(diào)研數(shù)據(jù)中的深度應(yīng)用? 市場(chǎng)調(diào)研是企業(yè)洞察市場(chǎng)動(dòng)態(tài)、了解消費(fèi)者需求的重要途徑,而統(tǒng)計(jì)學(xué)方法則是市場(chǎng)調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當(dāng)下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動(dòng)力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準(zhǔn)確性的基礎(chǔ) ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動(dòng)力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價(jià)值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03