ค้นหา ticker ของบริษัท Consumer Services ที่มีมูลค่าสูงสุด
นอกจากการกรองข้อมูลด้วยนิพจน์เงื่อนไขแล้ว ยังสามารถใช้ .loc[row_selector, column_selector] เพื่อกรองข้อมูลตามค่าที่ต้องการได้ นอกจากนี้ .set_index() ช่วยกำหนดคอลัมน์ที่มีค่าไม่ซ้ำกันให้เป็น index ของ DataFrame และ .idxmax() ใช้คืนค่า index ของค่าสูงสุด
ในแบบฝึกหัดนี้ จะนำเมธอดเหล่านี้มาใช้เพื่อหาบริษัท Consumer Services ที่มีมูลค่าสูงสุดในสามตลาดหลักทรัพย์ แล้วนำ ticker ของบริษัทนั้นมาพล็อตแนวโน้มราคาหุ้น โดย DataReader, date, pandas ในชื่อ pd และ matplotlib.pyplot ในชื่อ plt ถูก import ไว้แล้ว รวมถึง DataFrame listings จากแบบฝึกหัดก่อนหน้า
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การนำเข้าและจัดการข้อมูลทางการเงินใน Python
คำแนะนำการฝึกหัด
- ใช้
.set_index()เพื่อกำหนดคอลัมน์'Stock Symbol'เป็น index ของlistingsแล้วบันทึกไว้ในlistings_ss - ใช้
.loc[]เพื่อกรองแถวที่'Sector'มีค่าเท่ากับ'Consumer Services'เลือกคอลัมน์'Market Capitalization'และเรียก.idxmax()เพื่อกำหนด ticker ของบริษัท Consumer Services ที่มีมูลค่าสูงสุดให้กับticker - ใช้
date()กำหนดให้startเป็นวันที่ 1 มกราคม 2015 - ใช้
DataReader()เพื่อดึงข้อมูลหุ้นของtickerจาก'yahoo'ตั้งแต่startแล้วบันทึกไว้ในdata - พล็อตค่า
'close'และ'volume'ในdataโดยระบุอาร์กิวเมนต์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()