เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

สร้าง 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 เพื่อ index portfolio_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:])
แก้ไขและรันโค้ด