특징과 타깃 만들기
Machine Learning으로 최적의 포트폴리오를 선택하려면, 특징(features)과 타깃(targets)을 만들어야 해요. 바로 이전 연습 문제에서 지수 가중 이동 평균(EWMA) 가격을 계산해 특징을 준비했어요. 타깃은 가장 높은 Sharpe 비율에서 찾은 최적의 포트폴리오가 됩니다.
여기서는 pandas의 .iterrows() 메서드를 사용해 ewma_monthly DataFrame의 index, value 쌍을 가져올 거예요. 루프 안에서 현재 ewma_monthly 값을 우리의 특징으로 설정하고, max_sharpe_idxs에 있는 최고 Sharpe 비율의 인덱스를 사용해 매월 최적의 portfolio_weights를 가져와 해당 값을 타깃으로 설정해요.
이 연습은 강의의 일부입니다
Python으로 배우는 금융 분야 Machine Learning
연습 안내
- 루프에서
.iterrows()메서드를ewma_monthly에 사용해index, value를 순회하세요. - 루프의
date와best_idx를 사용해portfolio_weights를 인덱싱하여 최고 Sharpe 비율에 근거한 이상적인 포트폴리오 가중치를 가져오세요. 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:])