Make features and targets
To use machine learning to pick the best portfolio, we need to generate features and targets. Our features were just created in the last exercise – the exponentially weighted moving averages of prices. Our targets will be the best portfolios we found from the highest Sharpe ratio.
We will use pandas' .iterrows() method to get the index, value pairs for the ewma_monthly DataFrame. We'll set the current value of ewma_monthly in the loop to be our features. Then we'll use the index of the best Sharpe ratio (from max_sharpe_idxs) to get the best portfolio_weights for each month and set that as a target.
Deze oefening maakt deel uit van de cursus
Machine Learning for Finance in Python
Oefeninstructies
- Use the
.iterrows()method withewma_monthlyto iterate through theindex, valuein the loop. - Use the
datein the loop andbest_idxto indexportfolio_weightsto get the ideal portfolio weights based on the best Sharpe ratio. - Append the
ewmato the features.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
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:])