取得市值最高的消費性服務公司代號
除了用條件運算式來索引資料外,你也可以用 .loc[row_selector, column_selector] 依指定值來篩選。此外,你可以用 .set_index() 將具有唯一值的特定欄設為 DataFrame 的索引,並用 .idxmax() 回傳最大值所對應的索引。
在這個練習中,你會運用這些選股方法,找出三大交易所中市值最高的消費性服務公司,並用其代號繪製股價走勢圖。DataReader、date、作為 pd 的 pandas,以及作為 plt 的 matplotlib.pyplot 已經匯入,上一個練習中的 listings DataFrame 也已提供。
本練習屬於課程
在 Python 中匯入與管理財務資料
練習說明
- 使用
.set_index()將listings的'Stock Symbol'欄設為索引,指定為listings_ss。 - 使用
.loc[]篩選'Sector'等於'Consumer Services'的列,選取欄位'Market Capitalization',並套用.idxmax(),將市值最高的 Consumer Services 公司代號指派給ticker。 - 使用
date(),將start設為 2015 年 1 月 1 日。 - 使用
DataReader()自'yahoo'擷取自start以來ticker的股價資料並儲存到data。 - 繪製
data中的'close'與'volume',參數使用secondary_y='volume'與title=ticker。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Set the index of listings to Stock Symbol
listings_ss = listings.____(____)
# Get ticker of the largest Consumer Services company
ticker = listings_ss.____[____, ____].____()
# Set the start date
start = ____
# Import the stock data
data = ____
# Plot close and volume
data[['close', 'volume']].plot(secondary_y=____, title=____)
# Show the plot
plt.show()