使用python和pandas抓取S&P 500中股票的產業別,並繪製成圓餅圖。本文將爬蟲及繪製的程式碼放置在最後面。
首先抓取維基百科及GICS對於S&P 500中股票的分類,並擷取需要欄位。
import pandas as pd
table = pd.read_html("https://en.wikipedia.org/wiki/List_of_S%26P_500_companies")[0]#爬取網站及讀取需要的表格
table = table[['Symbol', 'GICS Sector']]#擷取需要的欄位
table
統計各產業的家數。
sector = table['GICS Sector'].value_counts()
sector
最後則是根據家數量繪製圓餅圖,當中的參數設定僅是作者認為好看的設定。
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 12})
fig, ax = plt.subplots(figsize=(10,6))
ax.pie(sector, colors=plt.cm.tab20.colors, labels=sector.index,
wedgeprops=dict(width=0.4, edgecolor='w'), autopct='%.2f%%', labeldistance=1.1, radius=1.1, pctdistance=0.75)
ax.set(aspect="equal", title='S&P 500 Sector')
plt.show()
本文程式碼在https://github.com/MinKuanIsHere/SP500SectorandQuote/blob/main/SP500Sector.ipynb