สร้าง features และ targets
เพื่อใช้ machine learning ในการเลือกพอร์ตโฟลิโอที่ดีที่สุด เราต้องสร้าง features และ targets ก่อน โดย features ที่เราสร้างในแบบฝึกหัดก่อนหน้าคือค่าเฉลี่ยเคลื่อนที่แบบถ่วงน้ำหนักเอ็กซ์โพเนนเชียล (exponentially weighted moving averages) ของราคาหุ้น ส่วน targets คือพอร์ตโฟลิโอที่ดีที่สุดซึ่งคัดเลือกจาก Sharpe ratio สูงสุด
เราจะใช้เมธอด .iterrows() ของ pandas เพื่อดึงคู่ index, value จาก DataFrame ewma_monthly แล้วกำหนดค่าปัจจุบันของ ewma_monthly ในลูปให้เป็น features จากนั้นใช้ index ของ Sharpe ratio สูงสุด (จาก max_sharpe_idxs) เพื่อดึง portfolio_weights ที่ดีที่สุดของแต่ละเดือน และกำหนดให้เป็น target
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Machine Learning สำหรับการเงินด้วย Python
คำแนะนำการฝึกหัด
- ใช้เมธอด
.iterrows()กับewma_monthlyเพื่อวนซ้ำผ่านindex, valueในลูป - ใช้
dateในลูปและbest_idxเพื่อ indexportfolio_weightsและดึงน้ำหนักพอร์ตโฟลิโอที่เหมาะสมที่สุดตาม Sharpe ratio สูงสุด - เพิ่ม
ewmaไปยัง features
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
targets, features = [], []
# Create features from price history and targets as ideal portfolio
for date, ewma in ewma_monthly.____:
# Get the index of the best sharpe ratio
best_idx = max_sharpe_idxs[date]
targets.append(portfolio_weights[____][____])
features.append(____) # add ewma to features
targets = np.array(targets)
features = np.array(features)
print(targets[-5:])