คำนวณ EWMA
ต่อไปเราจะสร้าง feature เพื่อนำไปใช้พยากรณ์พอร์ตโฟลิโอที่เหมาะสมที่สุด โดยในตอนนี้จะใช้การเปลี่ยนแปลงของราคาเป็น feature เราจะคำนวณค่าเฉลี่ยเคลื่อนที่แบบ exponentially-weighted รายวัน (EWMA) จากนั้น resample ให้เป็นรายเดือน และสุดท้ายจะเลื่อน moving average รายเดือนของราคาไปข้างหน้าหนึ่งเดือน เพื่อใช้เป็น feature ในการพยากรณ์พอร์ตโฟลิโอในอนาคต
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Machine Learning สำหรับการเงินด้วย Python
คำแนะนำการฝึกหัด
- ใช้
spanเท่ากับ 30 เพื่อคำนวณค่าเฉลี่ยเคลื่อนที่แบบ exponentially-weighted รายวัน (ewma_daily) - Resample ค่า ewma รายวันให้เป็นรายเดือน โดยใช้ความถี่ Business Monthly Start (BMS) และดึงวันแรกของเดือนด้วย
.first() - เลื่อน
ewma_monthlyไปข้างหน้าหนึ่งเดือน เพื่อนำค่า EWMA ของเดือนก่อนหน้ามาใช้เป็น feature ในการพยากรณ์พอร์ตโฟลิโอที่เหมาะสมในเดือนถัดไป
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Calculate exponentially-weighted moving average of daily returns
ewma_daily = returns_daily.ewm(span=____).mean()
# Resample daily returns to first business day of the month with the first day for that month
ewma_monthly = ewma_daily.resample(____).____
# Shift ewma for the month by 1 month forward so we can use it as a feature for future predictions
ewma_monthly = ewma_monthly.____.dropna()
print(ewma_monthly.iloc[-1])